1. 先写servlet
package com.web.servlet;
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.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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 ImageServlet extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public ImageServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpeg");
response.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
response.setHeader("Cache-Control", "no-cache, must-revalidate");
StringBuilder sb = new StringBuilder(5);
for(int i = 0; i < 5; i++) {
int n = (int)(Math.random() * 10);
sb.append(n);
}
String validateCode = sb.toString();
request.getSession().setAttribute("validateCode", validateCode);
BufferedImage image = new BufferedImage(60,20,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, 60, 20);
g.setColor(Color.BLACK);
g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
g.drawString(validateCode, 8, 17);
Random random = new Random();
for(int i = 0; i < 45; i++) {
int x = random.nextInt(80);
int y = random.nextInt(25);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
g.drawLine(x, y, x + x1, y + y1);
}
for(int i = 0; i < 100; i++) {
int x = random.nextInt(80);
int y = random.nextInt(25);
g.drawOval(x, y, 0, 0);
}
g.dispose();
ServletOutputStream out = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}
}
2. 配置web.xml
<servlet>
<description></description>
<display-name>ImageServlet</display-name>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.web.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/ImageServlet.c</url-pattern>
</servlet-mapping>
3.页面上调用
<img src="<%=contextPath%>/ImageServlet.c" alt="看不清楚吗?点击这里试试!" οnclick="this.src='<%=contextPath%>/ImageServlet.c?temp='+(new Date().getTime().toString(36));return false;"/>