- 生成验证码
<%@ 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>表单提交</title> <script type="text/javascript"> function _hyz() { /* 1. 获取img元素 2. 改变src的指向 */ var img = document.getElementById("img"); //需要加一个参数才能干掉浏览器的缓存 img.src = "/tools/VerifyCodeServlet?a=" + new Date().getTime(); } </script> </head> <body> <!-- 生成验证码: 1. 写表单,其中包含图片(验证码) 2. 让图片显示出来: 把<img>的src指向VerifyCodeServlet,你需要在web.xml中部署VerifyCodeServlet --> <form action="/tools/loginServlet" method="post"> <!-- 添加一个参数:method=login --> <input type="hidden" name="method" value="login"> 用户名:<input type="text" name="name"/><br /> 密码:<input type="password" name="pwd" /><br /> 验证码:<input type="text" name="verifyCode" /><br /> <img src="/tools/VerifyCodeServlet" id="img"/><br /> <a href="javascript:_hyz()">换一张</a> <input type="submit" value="提交" /> </form> </body> </html>
- 配置web.xml文件
<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
package cn.itcast.test;
import java.io.IOException;
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 cn.itcast.servlet.BaseServlet;
/**
- @author Guozhen_Zhao
- 创建时间:2018年1月28日 下午1:41:38
-
备注:br/>*/
@WebServlet("/loginServlet")
public class loginServlet extends BaseServlet {public String login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//检验验证码
//1. 获取表单中的验证码
String verifyCode = request.getParameter("verifyCode");
//2. 获取图片上的文字
String vcode = (String)request.getSession().getAttribute("vCode");
//3. 检验
System.out.println(verifyCode.equalsIgnoreCase(vcode));return null;
}
}
转载于:https://blog.51cto.com/13416247/2065966