JSP + Servlet实现生成登录验证码示例(2)

<servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>PictureCheckCode</servlet-name> <servlet-class>servlet.PictureCheckCode</servlet-class> </servlet> <servlet-mapping> <servlet-name>PictureCheckCode</servlet-name> <url-pattern>/pictureCheckCode</url-pattern> </servlet-mapping>

3.jsp页面输出验证码

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登录页面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script language="javascript"> function myReload() { document.getElementById("CreateCheckCode").src = document .getElementById("CreateCheckCode").src + "?nocache=" + new Date().getTime(); } </script> </head> <body> <form action="loginServlet" method="get"> <p> 验证码:<input type="text"> <img src="https://www.jb51.net/pictureCheckCode"> <br> <a href=""> 看不清,换一个</a> </p> <br><input type="submit" value="提交"> </form> </body> </html>

4.后台Servlet判断验证码是否与输入一致

通过request.getParameter(“checkCode”)获取输入验证码,与session.getAttribute(“randCheckCode”)比较是否一致。

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("checkCode"); HttpSession session = request.getSession(); if (!code.equals(session.getAttribute("randCheckCode"))) { request.setAttribute("errormsg", "验证码不正确"); } System.out.println(request.getAttribute("errormsg")); }

运行结果:

JSP + Servlet实现生成登录验证码示例

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzjffx.html