Bootstrap

Java Web验证码

1.导入jar包

2. 生成验证码的Servlet

package com.whoami.servletProject;

import cn.dsna.util.images.ValidateCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "CreateCodeServlet",value = "/createCode")
public class CreateCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ValidateCode code = new ValidateCode(200,30,4,20);
        //参数1 : 图片宽度
        //参数2 : 图片高度
        //参数3 : 验证码的位数
        //参数4 : 干扰线的个数
        code.write(response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
//用getCode方法可以获取验证码,取到验证码之后可以存到session之中,用作验证
code.getCode();

3.验证效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
    <form action="/login" method="post">
        username:<input type="text" name="username"/><br/>
        password:<input type="password" name="password"/><br/>
        <!-- 显示验证码  src的url必须是上面servlet的url一样-->
        code:<input type="text" name="inputVcode"/><img src="/createCode"><br>
        <input type="submit" value="login"/>
    </form>
</body>
</html>

验证码效果

;