Servlet實現圖形驗證碼,servlet圖形驗證碼

來源:互聯網
上載者:User

Servlet實現圖形驗證碼,servlet圖形驗證碼
1. 開發環境

|-- tomcat7

|-- eclipse

|-- jdk1.7

 

2. 項目結構

|-- demo

    |-- src

        |-- asia.hchx.filter

            |-- CharacterFilter

            |-- LoginFilter

       |-- asia.hchx.servlet

            |-- LoginServlet

            |-- VerifyImage

    |-- WebContent

        |-- index.jsp

        |-- login.jsp

 

3. 測試步驟|-- 建立web項目

 

|-- 配置開發圖形驗證碼Servlet
package asia.phome.servlet;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.io.OutputStream;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/verifyCode.do")public class VerifyImage extends HttpServlet {// 產生隨即的字型private Font getFont() {Random random = new Random();Font font[] = new Font[5];font[0] = new Font("Ravie", Font.PLAIN, 24);font[1] = new Font("Antique Olive Compact", Font.PLAIN, 24);font[2] = new Font("Forte", Font.PLAIN, 24);font[3] = new Font("Wide Latin", Font.PLAIN, 24);font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 24);return font[random.nextInt(5)];}protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// 設定回應標頭 Content-type類型resp.setContentType("image/jpeg");// 以下三句是用於設定頁面不緩衝resp.setHeader("Pragma", "No-cache");resp.setHeader("Cache-Control", "No-cache");resp.setDateHeader("Expires", 0);OutputStream os = resp.getOutputStream();int width = 83, height = 30;// 建立指定寬、高和BufferedImage對象BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics g = image.getGraphics(); // 該畫筆畫在image上Color c = g.getColor(); // 儲存當前畫筆的顏色,用完畫筆後要回複現場g.fillRect(0, 0, width, height);char[] ch = "abcdefghigklmnopqrstuvwxyz".concat("ABCDEFGHIJKLMNOPQRSTUV").concat("WXYZ0123456789").toCharArray(); // 隨即產生的字串// 不包括 i// l(小寫L)// o(小寫O)// 1(數字1)0(數字0)int length = ch.length; // 隨即字串的長度String sRand = ""; // 儲存隨即產生的字串Random random = new Random();for (int i = 0; i < 4; i++) {// 設定字型g.setFont(getFont());// 隨即產生0-9的數字String rand = new Character(ch[random.nextInt(length)]).toString();sRand += rand;// 設定隨機顏色g.setColor(new Color(random.nextInt(255), random.nextInt(255),random.nextInt(255)));g.drawString(rand, 20 * i + 6, 25);}// 產生隨即幹擾點for (int i = 0; i < 40; i++) {int x1 = random.nextInt(width);int y1 = random.nextInt(height);g.drawOval(x1, y1, 2, 2);}g.setColor(c); // 將畫筆的顏色再設定回去g.dispose();// 將驗證碼記錄到sessionreq.getSession().setAttribute("safecode", sRand);// 輸出映像到頁面ImageIO.write(image, "JPEG", os);}protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doGet(req, resp);}}



 

|-- 登入頁面配置圖形驗證碼login.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><body><form method="post" action="${pageContext.request.contextPath }/login.do">username:<input type="text" name="username"/><br />password:<input type="text" name="password"/><br /><!-- img中的src屬性中,配置VerifyImage的請求 -->verify code:<img src="${pageContext.request.contextPath }/verifyCode.do"/><input type="text" name="verifyCode"/><br /><input type="checkbox" value="1" name="rememberMe"/>記住密碼<br /><input type="submit" value="登陸"/></form></body></html>

 

|-- 登入的Servlet配置——LoginServlet
package asia.phome.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;@WebServlet("/login.do")public class LoginServlet extends HttpServlet{Logger log = Logger.getLogger(LoginServlet.class);@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {log.debug("開始執行doGet方法");this.doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {log.debug("開始執行doPost方法");req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=UTF-8");log.debug("開始接收參數");String username = req.getParameter("username");String password = req.getParameter("password");String safeCode = req.getParameter("verifyCode");log.debug("接收到參數:username =" + username + ";password=" + password+ ";safecode=" + safeCode);// 擷取驗證碼String sc = (String) req.getSession().getAttribute("safecode");log.warn("伺服器中的驗證碼:" + sc);if (!sc.equalsIgnoreCase(safeCode)) {log.warn("驗證碼輸入有誤!");resp.sendRedirect("login.jsp");return;}String isRe = req.getParameter("rememberMe");log.debug("是否記住密碼:" + isRe);if ("1".equals(isRe)) {/* *  記住密碼 *  在用戶端的Cookie中,寫入一個字串標識 */// 建立cookielog.debug("建立Cookie");Cookie cookie = new Cookie("rememberMe", username);// 將cookie綁定到響應中log.debug("綁定Cookie到響應中");resp.addCookie(cookie);}if ("admin".equals(username)&& "admin".equals(password)) {log.debug("登入成功,跳轉到Index.jsp頁面");req.getSession().setAttribute("loginuser", username);resp.sendRedirect("index.jsp");} else {log.debug("登入失敗,跳轉到error.jsp頁面");resp.sendRedirect("error.jsp");}}}


 


|-- 測試

運行項目,頁面上出現如形驗證碼

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.