下面是居于struts2实现的验证码
1.产生验证码的类
package com.ceetop.action.comman;
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;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;
@Controller
public class RandowImage {
private final int WIDTH = 100;
private final int HEIGHT = 25;
private String randowCode;
public String execute() {
HttpServletResponse response = ServletActionContext.getResponse();
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.setHeader("pragma", "no-cache");
response.addHeader("cache-control", "no-cache");
response.addHeader("expires", "0");
try {
ImageIO.write(image, "jpg", response.getOutputStream());
ServletActionContext.getRequest().getSession().setAttribute("randowCode", randowCode);
//response.getWriter().flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private void drawRandomNum(Graphics2D g) {
g.setColor(Color.RED);
g.setFont(new Font("受体", Font.BOLD, HEIGHT-5));
int x = 10;
randowCode = "";
for (int i = 0; i < 4; i++) {
int num = new Random().nextInt(9);
randowCode += num;
int degree = new Random().nextInt(60) - 30;
g.rotate(degree * Math.PI / 180, x, HEIGHT-5);
g.drawString(String.valueOf(num), x, HEIGHT-5);
g.rotate(-degree * Math.PI / 180, x, HEIGHT-5);
x += HEIGHT;
}
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.GREEN);
for (int i = 0; i < 4; i++) {
int x1 = new Random().nextInt(WIDTH - 2) + 1;
int y1 = new Random().nextInt(HEIGHT - 2) + 1;
int x2 = new Random().nextInt(WIDTH - 2) + 1;
int y2 = new Random().nextInt(HEIGHT - 2) + 1;
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);
}
}
2.struts2配置
<!-- 验证码 -->
<action name="randowImage" class="randowImage">
</action>
3. 使用验证码:
<IMG id="img" src="${pageContext.request.contextPath}/randowImage" border="0px"/>
<A id=LinkButton1 href="#" οnclick="getImg('${pageContext.request.contextPath}/randowImage')">不清楚,再来一张</A>
4.刷新验证码
/**
* 验证码刷新
* @param url
*/
function getImg(url)
{
url = url + "?time=" + (new Date()).valueOf();
$("#img").attr("src",url);
}
随机图片验证码实现
最新推荐文章于 2021-05-23 05:48:21 发布