1、首先需要集成下面的jar
2、在web.xml配置验证码的servlet
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>BaseServlet</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>cn.itcast.filter.EncodingFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>VerifyCodeServlet</servlet-name> <servlet-class>cn.itcast.vcode.servlet.VerifyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>VerifyCodeServlet</servlet-name> <url-pattern>/VerifyCodeServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>KeServlet</servlet-name> <servlet-class>com.weiyuan.test.KeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>KeServlet</servlet-name> <url-pattern>/33</url-pattern> </servlet-mapping> </web-app>
然后编写登陆的jsp文件:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <script type="text/javascript"> function changeImg(){ var img =document.getElementById("img"); //后面给上一个参数new Date().getTime()每次都不一样,每次都会重新去请求VerifyCodeServlet,而不使用原来缓存中的图片 img.src="/BaseServlet/VerifyCodeServlet?a="+new Date().getTime(); } </script> <body> <form action="/BaseServlet/LoginServlet" method="post"> <input type="hidden" name="method" value="login"></input> 用户名:<input type="text" name="username"></input></br> 密码:<input type="text" name="pwd"></input></br> 验证码:<input type="text" name="verifyCode"></input></br> <img id ="img" src="/BaseServlet/VerifyCodeServlet"> <a href="javascript:changeImg()">更换验证码</a></br> <input type="submit" value="提交"></input> </form> </body> </html>
其中:
BaseServlet是当前的工程项目
在servlet中我们可以通过session获得缓存中session中的验证码,通过客户端在表单中提交的验证码和在session后台中缓存的验证码,我们就可以知道用户提交的验证码是否正确
String verfiyCode= request.getParameter("verifyCode");
String vcode = (String) request.getSession().getAttribute("vCode");