上代码 seccodeServlet.java
package com.zheng;
import java.awt.Color;
import java.awt.Font;
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;
import javax.servlet.http.HttpSession;
public class seccodeServlet extends HttpServlet {
private static final int width=200;
private static final int height=50;
private static final String code ="abcdefghijklmnopqrstuvwxyz";
private Random random= new Random();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
Graphics g = image.getGraphics();
g.setColor(getColor(200,40));
g.fillRect(0,0,width,height);
//随机画线
for(int i= 0;i<20;i++){
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g.setColor(getColor(160,40));
g.drawLine(x1,y1,x2,y2);
}
//输出字符
String seccode="";
Font font = new Font("宋体",Font.ITALIC,width/4);
g.setFont(font);
for(int i= 0;i<4;i++){
char c= code.charAt(random.nextInt(code.length()));
seccode +=c;
g.drawString(c+"",i* width/4+5 , 40);
}
HttpSession session = request.getSession();
session.setAttribute("seccode",seccode);
ImageIO.write(image,"JPEG",response.getOutputStream());
g.dispose();
}
private Color getColor(int base,int inc){
int r=base+random.nextInt(inc);
int g=base+random.nextInt(inc);
int b=base+random.nextInt(inc);
return new Color(r,g,b);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
web.xml中servlet的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>seccodeServlet</servlet-name>
<servlet-class>com.zheng.seccodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>seccodeServlet</servlet-name>
<url-pattern>/servlet/seccodeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行结果上图