在JavaWeb开发中常会用到生成验证码的代码,采用Struts2开发框架,验证码的实现如下:
1 controller层代码
public String pic() throws Exception{
HttpServletResponse response=ServletActionContext.getResponse();
HttpServletRequest request=ServletActionContext.getRequest();
response.setContentType("image/png");
BufferedImage image=new BufferedImage(108, 40, BufferedImage.TYPE_INT_RGB);
Graphics2D g=image.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, 108, 40);
Random r=new Random();
for (int i = 0; i < 50; i++) {
g.setColor(getColor());
int x=r.nextInt(108);
int y=r.nextInt(40);
int x1=x+r.nextInt(10);
int y1=y+r.nextInt(10);
g.drawLine(x, y, x1, y1);
}
for (int i = 0; i <100; i++) {
int x=r.nextInt(108);
int y=r.nextInt(40);
g.setColor(getColor());
g.drawOval(x, y, 1, 1);
}
g.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuffer buff=new StringBuffer();
for (int i = 0; i < 5; i++) {
String ch=String.valueOf(str.charAt(r.nextInt(str.length())));
buff.append(ch);
g.setColor(getColor());
g.drawString(ch, i*22+2, 20+r.nextInt(12));
}
HttpSession session=request.getSession();
session.setAttribute("checkcode", buff.toString());
OutputStream out=response.getOutputStream();
ImageIO.write(image, "PNG", out);
return "pic";
}
public Color getColor(){
Random r=new Random();
return new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
}
2 在 Struts.xml 的配置
<result name="pic" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>