「サーブレット学習ノート」--Webサイトのフォーム検証コードを生成します.


一、知識点1、原理:検証コードを生成するには、まずランダム文字列を生成し、その後、ランダム文字列を画像の形式で描画して出力するのが一般的である.2、検証コードの役割:参考:http://zhidao.baidu.com/link?url=WXmjEr4b-Xh5ps8Yv-8A3r0EK5dE8jh0G52U-kEh6McHcMchquHFfsOX1AchvImkoWNB8nUny9o3Nv0GTfFtha . 3.フォームで<img>タグのsrc属性を使用してValidateCodeServeretクラスをデバッグして検証コードを生成することができ、src属性の値はクラス名に対応する.例:<img src="ValidateCodeServlet" />.
二、例コード1、ValidateCodeServicelet.java
package com.code;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
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 ValidateCodeServlet extends HttpServlet {

    private static final long serialVersionUID = -7949003651752048970L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //      
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");//       MIME     
        int width = 65;
        int height = 25;
        /*             ,   65,   20*/
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();//              ,     
        Random random = new Random();//          
        g.setColor(getRandomColor(180,250));//        
        g.fillRect(0,0,width,height);//     ,   (0,0),   width,   height
        g.setFont(new Font("Times New Roman", Font.PLAIN, 23));//      
        for (int i = 0; i < 150; i++) {//  150      
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, xl, yl);//      (x,y)   (x+xl, y+yl)      
        }
        String strCode = "";//       ,            
        for(int i=0; i<4; i++){
            String strNumber = String.valueOf(random.nextInt(10));//        10  ,    string 
            strCode += strNumber;
            g.setColor(new Color(15+random.nextInt(120) , 15+random.nextInt(120) , 15+random.nextInt(120)));//       
            g.drawString(strNumber, 13*i+6, 20);//           ,   (x=13*i+6 , y=20)
        }
        request.getSession().setAttribute("code", strCode);//       session 
        g.dispose();//                     
        ImageIO.write(image, "JPEG", response.getOutputStream());//  JPEG     
        response.getOutputStream().flush();//     
        response.getOutputStream().close();//     

    }
    /*        */
    private Color getRandomColor(int fc, int bc) {//fc    ;bc     
        Random random = new Random();
        Color randomColor = null;
        if(fc > 255) fc = 255;
        if(bc > 255) bc = 255;
        int red = random.nextInt(bc - fc);//  0~255      
        int green = random.nextInt(bc - fc);
        int blue = random.nextInt(bc - fc);
        randomColor = new Color(red,green,blue);
        return randomColor;//        、           sRGB  
    }

}

2、web.xmlでのValidateCodeServiceletの構成
  <servlet>
    <servlet-name>ValidateCodeServlet</servlet-name>
    <servlet-class>com.code.ValidateCodeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ValidateCodeServlet</servlet-name>
    <url-pattern>/ValidateCodeServlet</url-pattern>
  </servlet-mapping>

3、index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; request.setCharacterEncoding("utf-8"); %>

<!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">

    <script type="text/javascript"> function myReload(){ document.getElementById("createCheckCode").src=document.getElementById("createCheckCode").src + "?nocache="+new Date().getTime(); } </script>  
</head>

<body>

    <form action="RegServlet" method="post" onsubmit="return reg(this);">
        <table align="center">
            <tr>
                <td>  ID</td>
                <td><input type="text" name="userID" /></td>
            </tr>
            <tr>
                <td>    </td>
                <td><input type="text" name="username" /></td>
            </tr>
            <tr>
                <td>  </td>
                <td><input type="password" name="password" /></td>
            </tr>
            <tr>
                <td>   </td>
                <td><img id="createCheckCode" src="ValidateCodeServlet" /> <a href="" onClick="myReload()"></a></td>
            </tr>
            <tr>
                <td>     </td>
                <td><input type="text" name="code"/></td>
            </tr>
            <tr>
                <td><input type="reset" value="  " /></td>
                <td>&nbsp;<input type="submit" value="  " /></td>
            </tr>
        </table>
    </form>
</body>
</html>

4、効果図Servlet学习笔记--生成网站表单验证码_第1张图片