如何便捷的给页面中添加验证码

validatecode.jar的使用


验证码的作用:防止机器攻击。

  1. 项目中添加第三方jar包validatecode.jar
  2. 创建返回验证码的servlet!
<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
</head>
<body>
<form action="/servlet2/register" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"><br/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"><br/></td>
        </tr>
        <tr>
            <td>确认密码:</td>
            <td><input type="password" name="repassword"><br/></td>
        </tr>
        <tr>
            <td>邮箱:</td>
            <td><input type="text" name="email"><br/></td>
        </tr>
        <tr>
            <td>验证码:</td>
            <td><input type="text" name="vcode"><img id="img1" src="validateservlet" onclick=" changeImg()"><a href="" onclick="return changeImg()">点击,换一个</a><br/></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="提交"><br/></td>
        </tr>
    </table>
    <script type="text/javascript">
        function changeImg() {
     
            var img1 = document.getElementById("img1");
            img1.src="validateservlet?n="+Math.random();//加个随机数,让浏览器视为不同的请求
            return false;
        }

    </script>

</form>
</body>

</html>
@WebServlet(name = "RegisterServlet" ,value="/validateservlet")
public class RegisterServlet extends HttpServlet {
     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     

        ValidateCode validateCode=new ValidateCode(100,30,4,20);
        String code = validateCode.getCode();
        System.out.println(code);
        validateCode.write(response.getOutputStream());
        System.out.println(request.getRequestURL());

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        doPost(request, response);
    }
}

@WebServlet(name = "Servlet3",value="/register")
public class Servlet3 extends HttpServlet {
     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     

        request.setCharacterEncoding("utf-8");
        User user=new User();
        try {
     
            BeanUtils.populate(user,request.getParameterMap());
            System.out.println(user.toString());
        } catch (IllegalAccessException e) {
     
            e.printStackTrace();
        } catch (InvocationTargetException e) {
     
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     

        doPost(request, response);
    }
}

如何便捷的给页面中添加验证码_第1张图片

你可能感兴趣的:(html)