答案:package com.hbsoft;import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
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 CaptchaServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("pragma","no-cache");
response.setHeader("cache-control","no-cache");
response.setHeader("expires","0");
response.setContentType("image/jpeg");
BufferedImage image = new BufferedImage(100,20,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(Color.pink);
g.fillRect(0,0,100,80);
int[] m = new int[4];
String[] str = new String[4];
for(int i = 0; i < 4; i ++){
m[i] = random.nextInt(10);
System.out.println(m[i]);
}
for(int i = 0; i < 4; i ++){
int itemp = random.nextInt(26) + 65;
char temp = (char)itemp;
str[i] = String.valueOf(temp);
System.out.println(str[i]);
}
String strx = "";
for(int i = 0; i < 4;i++){
strx = strx + str[i] + m[i];
}
HashSet hs = new HashSet();
for(int i = 0;i < 8; i++){
hs.add(String.valueOf(strx.charAt(i)));
}
Iterator ite = hs.iterator();
String strmm = "";
while(ite.hasNext()){
strmm = strmm + ite.next();
}
System.out.println(strmm);
g.setColor(Color.white);
g.drawString(""+strmm, 10,10);
HttpSession session = request.getSession();
session.setAttribute("hand",strmm);
ImageIO.write(image, "JPEG",response.getOutputStream());
}
}