登录验证码
public class VerifyCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 1.生成图片 * 2.记录验证码至Session域中 * 3.发送验证码 */ VerifyCode vc=new VerifyCode(); BufferedImage bi=vc.getImage();
request.getSession().setAttribute("session_vcode",vc.getText());
VerifyCode.output(bi, response.getOutputStream()); }
} |
LoginServlet
/** * 1.拿到Session中的验证码 * 2.拿到浏览器传来的验证码 * 3.比较 */ String vcode=(String) request.getSession().getAttribute("session_vcode"); String prame=request.getParameter("verifyCode"); if (!vcode.equalsIgnoreCase(prame)) { request.setAttribute("message", "验证码不一致"); request.getRequestDispatcher("anli/login.jsp").forward(request, response); return; } |
Login.jsp
<script type="text/javascript"> function _change(){ var imgc=document.getElementById("img"); imgc.src="<%=path%>/VerifyCodeServlet?a="+new Date().getTime(); } </script> </head>
<body> This is my JSP page. <br> <h1>登陆页面</h1> <% String uname=""; Cookie[]cookies=request.getCookies(); if(cookies!=null){ for(Cookie c:cookies){ if("uname".equals(c.getName())){ uname=c.getValue(); } } } %> <% String message=""; String mes=(String)request.getAttribute("message"); if(mes!=null){ message=mes; } %> <font color="red"><b><%=message %></b></font> <form action="<%=path%>/LoginServlet" method="post"> <!-- 获取cookie中的uname的值放到 用户名文本框中 --> 用户名:<input type="text" name="username" value="<%= uname%>"><br> 密 码:<input type="password" name="password"><br> 验证码:<input type="text" name="verifyCode" size="5"> <img id="img" src="<%=path%>/VerifyCodeServlet"><a href="javascript:_change()">换一张</a><br> <input type="submit" value="提交">
</form> |