1. 程式人生 > >javaweb中使用servlet實現驗證碼

javaweb中使用servlet實現驗證碼

1、jsp頁面

在jsp頁面中,我們要有下面幾部分:
1.輸入框
2.驗證碼圖片
3.看不清按鈕
4.提交按鈕

預期效果:

思路:

2、jsp頁面程式碼:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request
.getServerPort()+path+"/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta
http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
<script type="text/javascript"> //reloadCode方法:實現"點選看不清重新整理"的功能 function reloadCode(){ //time變數的功能是強制重新整理,忽略瀏覽器的快取機制 var time = new Date().getTime(); document.getElementById("imagecode").src="<%=request.getContextPath() %>/servlet/servletImage?d="+time;//傳進的time變數,因為time在變化,所以url也在變化,因此可以說是強制重新整理 } </script> </head> <body> <!--表單的方式跳轉到loginservlet--> <form action="<%=request.getContextPath() %>/servlet/loginservlet" method = "get"> 驗證碼:<input type="text" name="checkcode"/> <img alt="驗證碼" id="imagecode" src="<%=request.getContextPath() %>/servlet/servletImage"><!--src的方式實現連結到servletImage--> <a href="javascript: reloadCode();">看不清楚,換一張!</a> <input type="submit" value="提交" /> </form> </body> </html>

3、servletImage

該servlet實現的主要功能是描繪出驗證碼的圖片,裡面隨機畫出4個字母與數字的組合,因為在jsp頁面中只用到了get方法跳轉,所以重寫servlet中的doget方法。

package servlet;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

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

public class servletImage extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public servletImage() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //驗證碼是通過img標籤觸發的,所以是get方式,重寫servlet方法:
        /*
         * BufferedImage(int width, int height, int imageType) 
                                 構建了一個 BufferedImage一個預定義的影象型別。 
           TYPE_INT_RGB  代表8位RGB分量包裝成整數畫素的影象。                       
         */
        BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        Color c = new Color(200,150,255);
        g.setColor(c);//背景顏色
        g.fillRect(0, 0, 68, 22);//背景框

        //字母數字組合:
        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVEXYZ123456789".toCharArray();
        Random r = new Random();
        int len = ch.length;
        int index;
        StringBuffer sb = new StringBuffer();
        for(int i =0;i<4;i++){
            index = r.nextInt(len);//隨機獲得一個起始位置
            g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));//給字型一個隨機的顏色
            g.drawString(ch[index]+"", (i*15)+3, 18);
            sb.append(ch[index]);
        }
        request.getSession().setAttribute("piccode", sb.toString());//將生產的驗證碼儲存下來,以便之後的檢驗輸入是否一致
        ImageIO.write(bi,"JPG",response.getOutputStream());
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

4、loginServlet

該servlet主要實現驗證輸入的驗證碼和之前的圖片上的驗證碼是否一致,之前的圖片上的驗證碼儲存在了session中
package servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

public class loginservlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public loginservlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //首先獲得之前儲存在session中的驗證碼
            String piccode = (String) request.getSession().getAttribute("piccode");
            String checkcode = request.getParameter("checkcode");
            response.setContentType("text/html;charset =UTF-8");
            PrintWriter out = response.getWriter();
            //response.setContentType("text/html;charset =UTF-8");
            if(checkcode.equals(piccode)){
                out.print("輸入正確");
            }else{
                out.print("輸入不正確!");
            }
            out.flush();
            out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

相關推薦

javaweb使用servlet實現驗證

1、jsp頁面 在jsp頁面中,我們要有下面幾部分: 1.輸入框 2.驗證碼圖片 3.看不清按鈕 4.提交按鈕 預期效果: 思路: 2、jsp頁面程式碼: <%@ page language="java" import="java.

java使用Servlet實現驗證

一、驗證碼作用 驗證碼定義:是一種區別使用者是計算機還是人的公共全自動程式; 二、使用servlet實現驗證碼 1、製作頁面 ①輸入框 ②顯示驗證碼的圖片 圖片的路徑直接指向servlet,可以在servlet中動態生成驗證碼。

javaWeb用kaptcha實現驗證

基本配置 1、匯入kaptcha的jar包 2、在web.xml中完成基本配置 <servlet> <servlet-name>Kaptcha</servlet-name> <serv

laravel如何實現驗證驗證及使用

開發環境: laravel5.5 php7.1.11 mysql 驗證碼 是防止惡意破解密碼、刷票、論壇灌水、刷頁的手段。驗證碼有 多種型別。 現在我給大家實現如何使用圖片驗證碼,其原理是讓使用者輸

JAVAWEB專案如何實現驗證

驗證碼基礎 一.什麼是驗證碼及它的作用    :驗證碼為全自動區分計算機和人類的圖靈測試的縮寫,是一種區分使用者是計算機的公共全自動程式,這個問題可以由計算機生成並評判,但是必須只有人類才能解答.可以防止惡意破解密碼、刷票、論壇灌水、有效防止某個黑客對某一個特定註冊使用者

node如何實現驗證

node-ccap模組生成captcha驗證碼 來源 http://cnodejs.org/topic/50f90d8edf9e9fcc58a5ee0b 用node做web開發很多都可能碰到需要驗證碼的地方,之前在github上搜索,有一些比如node-captcha等

servlet實現驗證的功能

1:使用的工具 myeclipse2015 jdk1.8 tomcat8.0 2:目錄結構 3:原始碼 index.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%&

Spring整合Cage,實現驗證功能

ger 類型 body match exce sub pom esp rec 1.pom.xml中添加Cage依賴。 <dependency> <groupId>com.github.cage</groupId

Django實現驗證功能

安裝Pillow pip install Pillow==3.4.1 windows下如果安裝報錯: 點選此處 下載對應的版本到本地,下載到那裡,就去那個目錄下: pip install Pi

註冊/找回密碼等功能傳送手機驗證後倒計時效果的實現(基於vue)

註冊/找回密碼等功能中傳送手機驗證碼後倒計時效果的實現,基於vue、element-ui<template> <el-button size="small" type="prima

JavaWeb: Servlet生成驗證

package cn.itcast; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.

Java Swing 圖形界面實現驗證驗證可動態刷新)

string ble urn repaint xtend efault event adapt 內容 import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.To

Java實現驗證(上)

ins check dom 後臺 類繼承 訪問 and text 出錯   眾所周知,現在登錄註冊各種網站賬號很多都要求輸入驗證碼。設置驗證碼,毫無疑問降低了用戶體驗,但為什麽各種網站還仍然使用驗證碼呢?   很明顯,驗證碼有其特殊的作用:驗證碼是一種區分用戶是計算機還是人

PHP實現驗證制作

php 驗證碼 captcha.php(PHP產生驗證碼並儲存Session):<?php //開啟Session session_start(); //繪制底圖 $image = imagecreatetruecolor(100, 30);//返回資源型的值 $bgcolor =

關於豆瓣登錄,並實現驗證輸入的方法

保持 學習 gen index token 如果 抓取 with open comment 最近想把模擬登錄的知識學習下,所以就進行了豆瓣賬號的簡單登錄,以下是代碼: # -*- coding:utf-8 -*- ‘‘‘豆瓣模擬登陸,並實現發一條狀態‘‘‘ impor

Python使用Timer實現驗證功能

input thread sel def AC check cache IT imp from threading import Timer import random class Code: def __init__(self): s

PHP實現驗證

channels echo img -type order pos 函數返回 個數 body (1)常見的驗證碼哪些? 圖像類型、語音類型、視頻類型、短信類型等 (2)使用驗證碼的好處在哪裏? ①防止惡意的破解密碼如一些黑客為了獲取到用戶信息,通過不同的手段向服務器

shop--6.店鋪註冊--使用kaptcha實現驗證

ssa p s request ava edi eth ring formdata input 1.引入jar包 https://mvnrepository.com/中搜索com.github.penggle 找到kaptcha,將其dependency拷貝到pom.xml

PHP JS CSS session實現驗證功能

驗證碼 ges ron oss art tex lse 個數 bcd PHP JS CSS session實現驗證碼功能 頁面<?php//校驗驗證碼if (isset($_POST["authcode"])) {session_start();

網頁登陸註冊(jsp實現)驗證

cte exp .com tran cti version height 一個 dog 這是一個登陸頁面,有登陸驗證和驗證碼的功能(1)生成驗證碼的servlet:import javax.imageio.ImageIO;import javax.servlet.Servl