生成验证码
package cn.itcast.response;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
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; public class ResponseDemo5 extends HttpServlet { public static final int width=120;
public static final int height=25;
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.写随机数
drawRandomNum((Graphics2D)g);
//5.图形写给浏览器
response.setContentType("image/jpeg");
//发头控制浏览器不要缓存
response.setDateHeader("expries", -1);
response.setHeader("Cache-control", "no-cache");
response.setHeader("Pragma", "no-cache");
ImageIO.write(image,"jpg",
response.getOutputStream());
}
private void drawRandomNum(Graphics2D g) {
g.setColor(Color.RED);
g.setFont(new Font("宋体",Font.BOLD,20));
String base="阿斯顿飞规划局快乐周星重要的是,开头就要习惯于在不好的地方也能睡觉,这是以后不怕遇到坏床的办法。一般地说,艰苦的生活一经变成了习惯,就会使愉快的感觉大为增加,而舒适的生活将是会带来无限的烦恼的。 —— 卢梭:" +
"《爱弥儿》爱情如果没有婚姻作为坟墓,那么爱情就是死无葬身之地——俞敏洪你的脸上云淡风轻,谁也不知道你的牙咬得有多紧。你走路带着风,谁也不知道你膝盖上仍有曾摔伤的淤青。你笑得没心没肺,没人知道你哭起来只能无声落泪。要让人觉得毫不费力,只能背后极其努力。我们没有改变不了的未来,只有不想改变的过去。——刘同你写了成百上千条微博、朋友圈或日志,有些是写给专门的人看的。但往往这个人看不到,不会看,也不想看。直到有一天,另一个不相关的人突然跟你说:你写的所有东西我都看完了,好心疼你呀,啊哈,你看,真正在乎你的人读的不是你的某条心情,他们想读的,是你的整个人生——刘同驰别那么欧赔成大分段刹现在沙发地方一百
前额前额玩大大陈";
int x=5;
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;
}
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.GREEN);
for(int i=0;i<5;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 setBorder(Graphics g) {
g.setColor(Color.BLUE);
g.drawRect(1, 1, width-2, height-2);
}
private void setBackGround(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response );
}
}