您的位置:首页 > 编程语言 > Java开发

客户端输出验证码(SpringMVC,当然用其他框架也类似)

2017-01-02 16:06 417 查看
在pringMVC的Controller中,我们可以用一个产生验证码的Controller方法,客户端的img标签src属性为Controller方法的请求地址

代码如下:

客户端的请求

<body>
<!-- src是产生验证码的Controller方法的的RequestMapping值 -->
<img alt="" src="/springmvc_img/testImg.action">
</body> Controller
@Controller
public class GetRandomNum{
public int width = 120; //图片宽度
public int height = 25; //图片高度
@RequestMapping("/testImg")
public void testImg(HttpServletResponse response) throws Exception{
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) image.getGraphics();

//1、设置背景色
setBackGround(g);
//2、设置边框
setBorder(g);
//3、画干扰线
drawRandomLine(g);
//4、写随机数
drawRandomNum(g);
//设置浏览器以图片的方式打开
response.setContentType("image/jpeg");
//告诉浏览器不要缓存
response.setHeader("expries","-1");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
//5、写给浏览器
ImageIO.write(image,"jpg",response.getOutputStream());
//没有返回值
}

//设置背景颜色
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 x2 = new Random().nextInt(width);
int y2 = new Random().nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
}
//产生随机数
private void drawRandomNum(Graphics2D g){
//设置字体颜色
g.setColor(Color.RED);
//设置字体样式
g.setFont(new Font("宋体",Font.BOLD,20));
String base = "abcdefghijklmnopqrstuvwxyz123456789";//随机字符串
int x = 5;//字体的位置
for(int i = 0;i<4;i++){//产生4个随机字符
int degree = new Random().nextInt()%30;//旋转角度
int index = new Random().nextInt(base.length());

String ch = base.charAt(index)+"";
g.rotate(degree*Math.PI/180, x,20);
g.drawString(ch, x, 20);
g.rotate(-degree*Math.PI/180, x, 20);
x+= 30;//字体位置右移30px
}
}
}
值得注意的是:Controller方法不能返回String类型的逻辑视图名、ModelAndView或者request.getRequestDispatcher("").forward(request, response),否者会抛出IllegalStsteException异常,因为forward(request, response)会清空响应体的内容,而向浏览器写数据过多超出缓存区的大小会调用flushBuffer()清空缓存区强制将数据写到浏览器中,所以会抛异常
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: