java生成验证码 封装类

package com.cn.fuleehaofangjia.biz;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** 验证码类* @author AliasYa**/public class VerlifyCodeUtil {/*** 生成验证码并将产生的数据保存到session中*/public static void verlifyCode(HttpServletRequest request,HttpServletResponse response){//准备数据String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";//随机函数Random random = new Random();int width = 80; //宽int height = 40;//高//1 创建图片–服务器端内存BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//2编写内容// * 获得画板(图层)Graphics g = image.getGraphics();// * 画笔颜色–黑g.setColor(Color.BLACK);// * 画一个矩形g.fillRect(0, 0, width, height);// * 画笔颜色–白g.setColor(Color.gray);// * 画一个矩形g.fillRect(1, 1, width-2, height-2);// 设置字体g.setFont(new Font("粗体",Font.BOLD,20));/** 将随机生成文字保存到session *//** 1.准备缓存区 */StringBuilder builderCode = new StringBuilder();// 编写文字for(int i = 0 ; i < 4 ; i++){// 画笔颜色 — 随机g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));// 随机文字int index = random.nextInt(data.length());String str = data.substring(index, index + 1);/** 2.缓存数据 */builderCode.append(str);// 将文字写入到画板g.drawString(str, (i + 1)* (width / 6), 25);}/** 3.将缓存的数据保存到session 属性中*/request.getSession().setAttribute("verifyCode", builderCode.toString());// 干扰线for(int i = 0 ; i < 10 ; i++){// 画笔颜色 — 随机g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));// 划线–随机g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width),random.nextInt(height));}//3图片发送到浏览器// 1,图片 2 图片格式 3输出位置try {ImageIO.write(image, "jpeg", response.getOutputStream());} catch (Exception e) {throw new RuntimeException(e);}}}

调用如下:

package com.cn.fuleehaofangjia.web.controller;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.cn.fuleehaofangjia.biz.IUserBiz;import com.cn.fuleehaofangjia.biz.VerlifyCodeUtil;import com.cn.fuleehaofangjia.domain.User;/*** 验证码类** @author AliasYa**/@Controller@RequestMapping(value = "valiCode")public class ValiCodeController {@Resource(name = "userBiz")private IUserBiz userBiz;/*** 生成验证码*/@RequestMapping(value = "/createCode")public void createCode(HttpServletRequest request,HttpServletResponse response) {

//已经生成验证码,并返回一张图片,且session里已经保存生成的正确的验证码VerlifyCodeUtil.verlifyCode(request, response);}}

使用双手头脑与心灵的是艺术家,只有合作双手

java生成验证码 封装类

相关文章:

你感兴趣的文章:

标签云: