public class ResponseDemo extends HttpServlet {
public static final int WIDTH=120;
public static final int HEIGHT=30;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
//1.设置背景色
setBackGround(g);
//2.设置边框
setBorder(g);
//3.画干扰线
drawRandomLine(g);
//4.写随机数
drewRandomNum((Graphics2D) g);
//5.图形写给浏览器
response.setContentType("image/jpeg");
//6.头控制浏览器不要缓存,不然在“地址栏”回车,将不会更新
r
esponse.setDateHeader("expires", -1);
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
ImageIO.write(image, "jpg", response.getOutputStream());
}
private void setBackGround(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
private void setBorder(Graphics g) {
g.setColor(Color.BLUE);
g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.green);
for(int i=0;i<4;i++){
int x1=new Random().nextInt(WIDTH);
int y1=new Random().nextInt(HEIGHT);
int x2=new Random().nextInt(WIDTH);
int y2=new Random().nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
}
private void drewRandomNum(Graphics2D g) {
g.setColor(Color.RED);
g.setFont(new Font("宋体",Font.BOLD,18));
String
base="\u7684\u4e00\u662f\u4e86\u6211\u4e0d\u4eba\u5728\u4ed6\u6709\u8fd9\u4e2a\u4e0a\u4eec\u6765\u5230\u65f6\u5927\u5730\u4e3a\u5b50\u4e2d\u4f60\u8bf4\u751f\u56fd\u5e74\u7740\u5c31\u90a3";//如何用配置文件的方式来加载这些?这只是一少部分
int x=10;
for(int i=0;i<4;i++){
int degree=new Random().nextInt()%30;
String ch=
base.charAt(new Random().nextInt(base.length()))+"";
g.rotate(degree*Math.PI/180, x, 20);
g.drawString(ch, x, 20);
g.rotate(-degree*Math.PI/180, x, 20);
x+=30;
}
}
<html>
<head>
<title>register.html</title>
<script type="text/javascript">
function chageImage(img){
img.src=img.src + "?" + new Date().getTime();//注意,要这样写,不然后取缓存数据
}
</script>
</head>
<body>
<form action="">
认证码:<input type="text" name="checkoc">
<img src="/day06/servlet/ResponseDemo" οnclick="chageImage(this)"
alt="换一张" style="cursor:hand"><br/>
</form>
</body>
</html>