packagecom.sxt.mvcpro.util;importjava.awt.Color;importjava.awt.Font;importjava.awt.Graphics;importjava.awt.image.BufferedImage;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.util.Random;importjavax.imageio.ImageIO;importjavax.servlet.ServletException;importjavax.servlet.ServletOutputStream;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;
@WebServlet("/imgCode")public class RandomCode extendsHttpServlet {private static final long serialVersionUID = 1L;private static int WIDTH = 102;//定义验证图片的宽度
private static int HEIGHT = 50;//定义验证图片的高度
public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
HttpSession session=request.getSession();
response.setContentType("image/jpeg");
ServletOutputStream sos=response.getOutputStream();
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
BufferedImage image= newBufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();char[] rands =generateCheckCode();
drawBackground(g);
drawRands(g, rands);
g.dispose();
ByteArrayOutputStream bos= newByteArrayOutputStream();
ImageIO.write(image,"JPEG", bos);byte[] buf =bos.toByteArray();
response.setContentLength(buf.length);
sos.write(buf);//锟斤拷锟斤拷锟缴碉拷锟斤拷证锟斤拷图片写锟斤拷页锟斤拷
bos.close();
sos.close();//锟斤拷锟斤拷锟缴碉拷锟斤拷证锟诫保锟芥到session
session.setAttribute("rand", newString(rands));
}private voiddrawBackground(Graphics g) {
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, WIDTH, HEIGHT);for (int i = 0; i < 120; i++) {int x = (int) (Math.random() *WIDTH);int y = (int) (Math.random() *HEIGHT);int red = (int) (Math.random() * 255);int green = (int) (Math.random() * 255);int blue = (int) (Math.random() * 255);
g.setColor(newColor(red, green, blue));
g.drawOval(x, y,1, 0);
}
}private void drawRands(Graphics g, char[] rands) {//g.setColor(Color.BLUE);
Random random = newRandom();int red = random.nextInt(110);int green = random.nextInt(50);int blue = random.nextInt(50);
g.setColor(newColor(red, green, blue));
g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 30));
g.drawString("" + rands[0], 5, 35);
g.drawString("" + rands[1], 25, 34);
g.drawString("" + rands[2], 45, 36);
g.drawString("" + rands[3], 65, 33);
}private char[] generateCheckCode() {
String chars= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";char[] rands = new char[4];for (int i = 0; i < 4; i++) {int rand = (int) (Math.random() * 36);
rands[i]=chars.charAt(rand);
}returnrands;
}public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {this.doGet(request, response);
}
}