用java代码编写jsp中的验证码
/*
需要的界面发出一个请求,编写一个action处理请求,处理完成后使用回应携带生成的图片给请求者。附上生成图片的代码
*/
//生成验证码
public void check() throws Exception{
int width=100;//设置生成的图片的宽度
int height=50;//设置生成的图片的高度
//使用bufferedImage类产生一个BufferedImage对象,BufferedIamge对象有多个构造函数,选择其中的一种
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//获得Graphics画笔用来画图
Graphics g=image.getGraphics();
g.setColor(Color.pink);//设置画笔的颜色
g.fillRect(0, 0, width, height);//画一个矩型
g.setColor(Color.blue);
g.drawRect(0,0,width-1,height-1);//画一个矩形边框
//这里画图部分不懂可以学习java.awt.*;下的方法
String s="ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwsyz0123456789";
StringBuilder sb=new StringBuilder();
Random r=new Random();//产生随机数
Map session=(Map)ActionContext.getContext().get("session");//获取session对象
//这里是产生随机的四位随机验证码
for(int i=1;i<=4;i++){
int j=r.nextInt(s.length());
char ch=s.charAt(j);
g.drawString(ch+"", i*20, height/2);//将产生的字符画到图片中
sb.append(ch);//将产生的字符添加到StringBuilder对象中,采用StringBuilder是因为字符串的添加会比较有效率,相对与String+的方式
}
//这里是画干扰线
for(int i=0;i<5;i++){
int x1=r.nextInt(width);
int x2=r.nextInt(width);
int y1=r.nextInt(height);
int y2=r.nextInt(height);
g.setColor(Color.green);
g.drawLine(x1, y1, x2, y2);//画干扰线的具体函数
}
session.put("check", sb.toString());//将验证码字符串放到session中
//获取response对象,用于发送到请求中去
HttpServletResponse res=(HttpServletResponse)ServletActionContext.getResponse();
/* 测试有没有获取到res实例
try{
if(res==null){
System.out.println("获取的请求为空");
}else{
System.out.println(res.hashCode());
}
}catch(Exception e){
}
System.out.println(image.hashCode());*/
try{
ImageIO.write(image, "jpg", res.getOutputStream());
}catch(Exception e){
e.printStackTrace();
}
/*Map session=(Map)ActionContext.getContext().get("session");
session.put("image",image);*/
}