一个Servlet验证码
转来自http://jspwind.com.cn
.首先在web.xml的配置:
<servlet>
<servlet-name> CodeServlet </servlet-name> <!-- 设定servlet名 -->
<servlet-class> com.bbs.logic.CodeGenServlet </servlet-class> <!-- 指定servlet的class路径 -->
<!-- <load-on-startup> 5 </load-on-startup> -->
</servlet>
<servlet-mapping>
<servlet-name> CodeServlet </servlet-name> <!-- 指定servlet名 -->
<url-pattern> /check/UrlTest.jsp </url-pattern> <!-- 指定servlet路径 放在WebRoot/check目录下-->
</servlet-mapping>
2.新建class名字为CodeServlet,代码如下:
/**
*
*/
package com.bbs.logic;
/**
* @author jake
*
*/
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.imageio.*;
import javax.servlet.http.*;
import java.io.*;
public class CodeGenServlet extends HttpServlet {
private static int I_WIDTH = 60;
private static int I_HEIGHT = 18;
private static Font VALIDATECODE_FONT = new Font( "Times New Roman ", Font.PLAIN, 18);
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws
javax.servlet.ServletException,
IOException {
//在内存中创建图象
BufferedImage image = new BufferedImage(I_WIDTH, I_HEIGHT,
BufferedImage.TYPE_INT_RGB);
//获取图形上下文
Graphics g = image.getGraphics();
//设定背景色
g.setColor(Color.white);
g.fillRect(0, 0, I_WIDTH, I_HEIGHT);
//画边框
g.setColor(Color.blue);
g.drawRect(0, 0, I_WIDTH - 1, I_HEIGHT - 1);
Long validate =