Session可避免表單的重復提交:實現一次表單提交,可避免惡意提交;
1.首先建立一個Servlet類:ValidateColorServlet,里邊有獲取驗證碼的方法,並且驗證碼是大小寫區分:
public class ValidateColorServlet extends HttpServlet { public static final String CHECK_CODE_KEY = "CHECK_CODE_KEY"; private static final long serialVersionUID = 1L; //設置驗證圖片的寬度, 高度, 驗證碼的個數 private int width = 152; private int height = 40; private int codeCount = 6; //驗證碼字體的高度 private int fontHeight = 4; //驗證碼中的單個字符基線. 即:驗證碼中的單個字符位於驗證碼圖形左上角的 (codeX, codeY) 位置處 private int codeX = 0; private int codeY = 0; //驗證碼由哪些字符組成 char [] codeSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz23456789".toCharArray(); //初始化驗證碼圖形屬性 public void init(){ fontHeight = height - 2; codeX = width / (codeCount + 2); codeY = height - 4; } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //定義一個類型為 BufferedImage.TYPE_INT_BGR 類型的圖像緩存 BufferedImage buffImg = null; buffImg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); //在 buffImg 中創建一個 Graphics2D 圖像 Graphics2D graphics = null; graphics = buffImg.createGraphics(); //設置一個顏色, 使 Graphics2D 對象的后續圖形使用這個顏色 graphics.setColor(Color.WHITE); //填充一個指定的矩形: x - 要填充矩形的 x 坐標; y - 要填充矩形的 y 坐標; width - 要填充矩形的寬度; height - 要填充矩形的高度 graphics.fillRect(0, 0, width, height); //創建一個 Font 對象: name - 字體名稱; style - Font 的樣式常量; size - Font 的點大小 Font font = null; font = new Font("", Font.BOLD, fontHeight); //使 Graphics2D 對象的后續圖形使用此字體 graphics.setFont(font); graphics.setColor(Color.BLACK); //繪制指定矩形的邊框, 繪制出的矩形將比構件寬一個也高一個像素 graphics.drawRect(0, 0, width - 1, height - 1); //隨機產生 15 條干擾線, 使圖像中的認證碼不易被其它程序探測到 Random random = null; random = new Random(); graphics.setColor(Color.GREEN); for(int i = 0; i < 55; i++){ int x = random.nextInt(width); int y = random.nextInt(height); int x1 = random.nextInt(20); int y1 = random.nextInt(20); graphics.drawLine(x, y, x + x1, y + y1); } //創建 randomCode 對象, 用於保存隨機產生的驗證碼, 以便用戶登錄后進行驗證 StringBuffer randomCode; randomCode = new StringBuffer(); for(int i = 0; i < codeCount; i++){ //得到隨機產生的驗證碼數字 String strRand = null; strRand = String.valueOf(codeSequence[random.nextInt(36)]); //把正在產生的隨機字符放入到 StringBuffer 中 randomCode.append(strRand); //用隨機產生的顏色將驗證碼繪制到圖像中 graphics.setColor(Color.BLUE); graphics.drawString(strRand, (i + 1)* codeX, codeY); } //再把存放有所有隨機字符的 StringBuffer 對應的字符串放入到 HttpSession 中 request.getSession().setAttribute(CHECK_CODE_KEY, randomCode.toString()); //禁止圖像緩存 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); //將圖像輸出到輸出流中 ServletOutputStream sos = null; sos = response.getOutputStream(); ImageIO.write(buffImg, "jpeg", sos); sos.close(); } }
2.index.jsp頁面,輸入用戶名字,輸入驗證碼:checkCode:<input type="text" name="CHECK_CODE_PARAM_NAME"/>;獲取驗證碼:是以插入圖片的形式獲取的<img alt="" src="<%=request.getContextPath() %>/validateColorServlet">,然后form表單提交到Servlet類:CheckCodeServlet
<%@ 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> <body> <font color="red"> <%=session.getAttribute("message")==null ? "" : session.getAttribute("message") %> </font> <form action="<%=request.getContextPath() %>/checkCodeServlet" method="post"> name:<input type="text" name="name"/> <br><br> checkCode:<input type="text" name="CHECK_CODE_PARAM_NAME"/> <img alt="" src="<%=request.getContextPath() %>/validateColorServlet"> <br><br> <input type="submit" value="Submit"/> </form> </body> </html>
3.建立一個Servlet類:CheckCodeServlet,獲取表單輸入的驗證碼和通過session的getsession()方法獲取系統給予的驗證碼,並進行判斷,看是否相等,然后重定向到index.jsp頁面,輸出結果;
public class CheckCodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 獲取請求參數: CHECK_CODE_PARAM_NAME String paramCode = request.getParameter("CHECK_CODE_PARAM_NAME"); //2. 獲取 session 中的 CHECK_CODE_KEY 屬性值 String sessionCode = (String)request.getSession().getAttribute("CHECK_CODE_KEY"); System.out.println(paramCode); System.out.println(sessionCode); //3. 比對. 看是否一致, 若一致說明驗證碼正確, 若不一致, 說明驗證碼錯誤 if(!(paramCode == null && !paramCode.equals(sessionCode))){ request.getSession().setAttribute("message", "驗證碼不一致!"); response.sendRedirect(request.getContextPath() + "/check/index.jsp"); return; } System.out.println("受理請求!"); } }
4.lib下的web.xml文件為:
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <description></description> <display-name>ValidateColorServlet</display-name> <servlet-name>ValidateColorServlet</servlet-name> <servlet-class>com.lanqiao.javatest.ValidateColorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ValidateColorServlet</servlet-name> <url-pattern>/validateColorServlet</url-pattern> </servlet-mapping>
<servlet> <description></description> <display-name>CheckCodeServlet</display-name> <servlet-name>CheckCodeServlet</servlet-name> <servlet-class>com.lanqiao.javatest.CheckCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckCodeServlet</servlet-name> <url-pattern>/checkCodeServlet</url-pattern> </servlet-mapping> </web-app>