1. 程式人生 > >使用Servlet實現圖形驗證碼登入頁面

使用Servlet實現圖形驗證碼登入頁面

1.介紹

首先需要寫一個生成圖形驗證碼的Servlet:
我這裡的Servlet為:createImageServlet
然後我們使用登入頁面來驗證是否能獲取圖形驗證碼。
登入後通過Servlet判斷使用者名稱密碼是否為張三和123(這裡簡單操作就不連線資料庫了)
登入頁面:login.jsp
這個頁面就是一個表單
判斷使用者名稱的Servlet:logCheckServlet
如果使用者名稱密碼正確則請求轉發回去登入頁面輸出登入成功
否則請求轉發回去輸出登入失敗
我們還需要做的一件事情就是驗證輸入的驗證碼是否與驗證碼圖片內容匹配。匹配錯則輸出驗證碼不是正確。
最後一個Servlet是當驗證碼看不清楚點選切換圖片的Servlet即重新整理驗證碼Servlet:changeCheckCodeServlet

2.程式碼:

生成圖形驗證碼Servlet:
createImageServlet:

package control;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class createImageServlet
 */
public class createImageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jpeg");
        HttpSession session = request.getSession();
        int width = 60;
        int height = 20;
        //設定瀏覽器不要快取此圖片
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //建立記憶體影象並獲得其圖形上下文
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        //產生隨機驗證碼
        //定義驗證碼的字元表
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[4];
        for(int i = 0;i<4;i++){
            int rand = (int)(Math.random()*36);
            rands[i] = chars.charAt(rand);
        }
        //產生影象,畫背景
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        //隨機產生120個干擾點
        for(int i = 0;i<120;i++){
            int x = (int)(Math.random()*width);
            int y = (int)(Math.random()*height);
            int red = (int)(Math.random()*255);
            int green = (int)(Math.random()*255);
            int blue = (int)(Math.random()*255);
            g.setColor(new Color(red,green,blue));
            g.drawOval(x, y, 1, 0);
        }
        g.setColor(Color.BLACK);
        g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
        //在不同的高度上輸出驗證碼的不同字元
        g.drawString("" +rands[0], 1,17);
        g.drawString("" +rands[1], 16,15);
        g.drawString("" +rands[2], 31,18);
        g.drawString("" +rands[3], 46,16);
        g.dispose();
        //將影象輸出到客戶端
        ServletOutputStream sos = response.getOutputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", baos);
        byte[] buffer = baos.toByteArray();
        response.setContentLength(buffer.length);
        sos.write(buffer);
        baos.close();
        sos.close();
        //將驗證碼存放到session中
        session.setAttribute("createImageServlet", new String(rands));
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

登入頁面: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 action="post" name = "form1">
    使用者名稱<input type = "text" name = "userid" onclick = "mes.innerHTML="value = "${param.userid }"/><br/>
    密&nbsp;&nbsp;&nbsp;碼<input type = "password" name = "userpwd" value = "${param.userpwd }"/><br/>
    驗證碼<input type = "text" name = "checkcode"/>
    <img border="0" src="createImageServlet"/>
    <input type = "submit" value = "換一張" onclick = "form1.action='changeCheckCodeServlet'"/>
    <br/>
    <input type = "submit" value = "登入" onclick = "form1.action = 'logCheckServlet'"/>
    <input type = "reset" value = "重置"/>
    <div id = "mes">${info }</div>
    </form>
</body>
</html>

登入驗證Servlet:logCheckServlet

package control;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class logCheckServlet
 */
public class logCheckServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userid = request.getParameter("userid");
        String userpwd = request.getParameter("userpwd");
        String usercheckcode = request.getParameter("checkcode");
        String info = "";
        HttpSession session = request.getSession();
        String servercheckcode = (String)session.getAttribute("createImageServlet");
        if(!servercheckcode.equalsIgnoreCase(usercheckcode)){
            info = "驗證碼不正確,請重新輸入";
        }else if("張三".equals(userid)&&"123".equals(userpwd)){
            info = "登陸成功";
        }else{
            info = "使用者名稱或密碼不正確";
        }
        request.setAttribute("info", info);
        request.getRequestDispatcher("/login.jsp").forward(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

更新驗證碼Servlet:changeCheckCodeServlet:

package control;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class changeCheckCodeServlet
 */
public class changeCheckCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

配置檔案: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">
  <display-name>testImage</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>
  <servlet>
    <description></description>
    <display-name>createImageServlet</display-name>
    <servlet-name>createImageServlet</servlet-name>
    <servlet-class>control.createImageServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>createImageServlet</servlet-name>
    <url-pattern>/createImageServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>logCheckServlet</display-name>
    <servlet-name>logCheckServlet</servlet-name>
    <servlet-class>control.logCheckServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>logCheckServlet</servlet-name>
    <url-pattern>/logCheckServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>changeCheckCodeServlet</display-name>
    <servlet-name>changeCheckCodeServlet</servlet-name>
    <servlet-class>control.changeCheckCodeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>changeCheckCodeServlet</servlet-name>
    <url-pattern>/changeCheckCodeServlet</url-pattern>
  </servlet-mapping>
</web-app>

web.xml配置的Servlet對映地址不要隨意更改,請保持一致即能實現。

3.實現


如果實現不了歡迎來我的自建部落格評論,我的郵箱會自動收到,也可以及時回覆你們,關注一下,大家一起學習。
自建部落格:http://47.107.118.184