package com.struts.web.controller;
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.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
/**
* 输出一张随机图片验证码
* @author dzm
*/
public class SecurityCode extends BaseAction {
/**
*
*/
private static final long serialVersionUID = -2291854415981405662L;
public static final int WIDTH = 100; // 指定图片的宽度
public static final int HEIGHT = 35; // 指定图片高度
public String execute() {
// 在内存中构建一幅图像
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 1.设置背景色
setBackGround(g);
// 2.设置边框
setBorder(g);
// 3.画干扰线
drawRandomLine(g);
// 4.向图形上写随机数
String random = drawRandomNum((Graphics2D) g);
this.getSession().put("securityCode", random);
// 5.将图形写回给浏览器
HttpServletResponse response = this.getResponse();
response.setContentType("image/jpeg");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
try {
ImageIO.write(image, "jpg", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return NONE;
}
/**
* 设置图片背景色
*/
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 <= 5; i++) {
int x1 = new Random().nextInt(WIDTH);
int y1 = new Random().nextInt(HEIGHT);
int y2 = new Random().nextInt(HEIGHT);
int x2 = new Random().nextInt(WIDTH);
g.drawLine(x1, y1, x2, y2);
}
}
/**
* 生成随机验证码
*/
private String drawRandomNum(Graphics2D g) {
g.setColor(Color.RED);
g.setFont(new Font("宋体", Font.BOLD, 28));
String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuffer sb = new StringBuffer();
for (int i = 0, x = 10; i < 4; i++) {
int degree = new Random().nextInt(60) - 30;// 随机获取字体旋转多少度 (-30 到 +30)
double theta = degree * Math.PI / 180; // 将 度 转换为 弧度 单位
// 获取随机字符
String code = str.charAt(new Random().nextInt(str.length())) + "";
sb.append(code);
g.rotate(theta, x, 28); // 设置旋转的弧度
g.drawString(code, x, 28);
g.rotate(-theta, x, 28); // 还原旋转的角度
x += 20;
}
return sb.toString();
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="securityCode" class="com.struts.web.controller.SecurityCode"></action>
</package>
</struts>
在jsp中使用<img>标签访问action
<img id="code" src="securityCode.action" alt="看不清换一张" οnclick="this.src='securityCode.action?'+new Date().getTime()" />