servlet图片验证码

第一,先建立一个servlet命名为IdentityServlet

package com.myweb.servlet;

import java.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.ServletException;
import javax.servlet.ServletOutputStream;
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;

public class IdentityServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 104097266476284687L;
	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() { // 获取六位随机数
		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 void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg");
		String randomString = getRandomString(); // 随机字符串
		request.getSession(true).setAttribute("randomString", randomString); //放到session
		int width = 100;
		int height = 30;
		Color color = getRandomColor(); // 随机颜色,用于背景色
		Color reverse = getReverseColor(color); // 反色,用于前景色
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_BGR);// 创建一个彩色照片
		Graphics2D g = bi.createGraphics();
		g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));//设置字体
		g.setColor(reverse);
		g.drawString(randomString, 18, 20);
		for(int i =0,n=random.nextInt(100); i < n; i++){  //画最多100个噪音点
			g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);//随机噪音点s
		}                                            
		ServletOutputStream out= response.getOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);//编码器
		System.out.println(randomString);
		encoder.encode(bi);  //对图片进行编码
		out.flush();  //输出到客户端
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

}


2,在web.xml里添加


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name />
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>IdentityServlet</servlet-name>
    <servlet-class>com.myweb.servlet.IdentityServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
   <servlet-mapping>
    <servlet-name>IdentityServlet</servlet-name>
    <url-pattern>/servlet/IdentityServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


3,建立一个jsp或者html文件,怎样都行

我建的是MyJsp.jsp文件 

代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="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 'MyJsp.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>
	function reloadImage() {
		document.getElementById('btn'), disabled = true;
		document.getElementById('identity').src = 'servlet/IdentityServlet?ts='
				+ new Date().getTime();
	}
</script>
</head>
<body>

	<img src="servlet/IdentityServlet" id="identity"
		onload="btn.disabled=false;" />
	<input type="button" value="换个图片" onclick="reloadImage()" id="btn">
	<br>

</body>
</html>

然后成功了,截图如下:




版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2013-02-28 15:05  一直向北  阅读(201)  评论(0编辑  收藏  举报