Servlet建立一个图片验证码程序

来源:互联网 发布:库里2012季后赛数据 编辑:程序博客网 时间:2024/06/14 21:56



软件:MyEclipse

技术:Servlet

1、首先创建一个javaweb工程,工程名为ForthServlet

2、在该工程中新建一个servlet,报名为:com.helloweenvsfei.servlet。类名为:IdentityServlet。

该类内容为:

package com.helloweenvsfei.servlet;

importJava.awt.Color;
import Java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
 * Servlet implementation class IdentityServlet
 */
@WebServlet(
  description = "This is hzy's Servlet",
  urlPatterns = {
    "/IdentityServlet",
    "/666/IdentityServlet"
  })
public class IdentityServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
      
   public static final char[] CHARS={'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H',
    'J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'};
   //不包括难以辨认的字符
   public static Random random=new Random();//随机数
   public static String getRandomString()//获取6位随机数
   {
   StringBuffer buffer=new StringBuffer();//字符串缓存
   for(int i=0;i<6;i++)
   {
    buffer.append(CHARS[random.nextInt(CHARS.length)]);
   
   }
   return buffer.toString();
   }
   public static Color getRandomColor()
   {
 return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));  
   }
   public static Color getReverseColor(Color c)
   {
    return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
   
   }
    public IdentityServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see Servlet#init(ServletConfig)
  */
 public void init(ServletConfig config) throws ServletException {
  // TODO Auto-generated method stub
 }

 /**
  * @see Servlet#destroy()
  */
 public void destroy() {
  // TODO Auto-generated method stub
 }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("image/jpeg");
  String randomString=getRandomString();
  request.getSession(true).setAttribute("randomString", randomString);
  int width=100;
  int height=30;
  
  Color color=getRandomColor();
     Color reverse=getReverseColor(color);
    
     BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
     Graphics2D g=bi.createGraphics();
  g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));
  g.setColor(color);
  g.fillRect(0, 0, width, height);
  g.setColor(reverse);
  g.drawString(randomString, 18, 20);
  for(int i=0,n=random.nextInt(100);i<n;i++)
  {
   g.drawRect(random.nextInt(width),random.nextInt(height), 1,1);
   
  }
  ServletOutputStream out=response.getOutputStream();
  JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
  encoder.encode(bi);
  out.flush();
 }

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

}

2、修改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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ForthServlet</display-name>
  <servlet>
  <servlet-name>IdentityServlet</servlet-name>
  <servlet-class>com.helloweenvsfei.servlet.IdentityServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>IdentityServlet</servlet-name>
  <url-pattern>/666/IdentityServlet</url-pattern>
  </servlet-mapping>
  <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>
< /web-app>

3、在Web_Root目录下新建一个Identity.html

<!DOCTYPE html>
< html>
  <head>
    <title>identityl.html</title>
 
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
 
  <body>
    <script>
    function reloadImage()
    {
    document.getElementById('btn').disabled=true;
    document.getElementById('identity').src='666/IdentityServlet?ts='+new Date().getTime();
 
    }
    </script>
    <img src="666/IdentityServlet" id="identity" onload="btn.disabled=false;"/>
    <input type=button value="换个图片" onclick="reloadImage()" id="btn">  </body>
< /html>

4、输出网址http://localhost:8080/ForthServlet/identityl.html


0 0
原创粉丝点击