struts2验证码代码

来源:互联网 发布:java list集合去重 编辑:程序博客网 时间:2024/06/05 11:14
public class ValidateCodeAction extends BaseAction{private static final long serialVersionUID = 1L;private static final Logger log = Logger.getLogger(ValidateCodeAction.class);public ByteArrayInputStream imageStream;// 验证码图片的宽度。private int width = 60;// 验证码图片的高度。private int height = 20;// 验证码字符个数private int codeCount = 4;private int x = 0;// 字体高度private int fontHeight;private int codeY;char[] codeSequence = { '1','2','3', '4', '5', '6', '7', '8', '9' };//从配置文件中获取初始化条件private String strWidth;//80private String strHeight;//30private String strCodeCount;//4public String getStrWidth() {return strWidth;}public void setStrWidth(String strWidth) {this.strWidth = strWidth;}public String getStrHeight() {return strHeight;}public void setStrHeight(String strHeight) {this.strHeight = strHeight;}public String getStrCodeCount() {return strCodeCount;}public void setStrCodeCount(String strCodeCount) {this.strCodeCount = strCodeCount;}/** * Desc 获取验证码 * @author:dongliyuan * @date:2014-11-4 上午10:08:52 */public void getValidateCode(){HttpServletRequest req = ServletActionContext.getRequest();HttpServletResponse resp = ServletActionContext.getResponse();HttpSession session = req.getSession();resp.setContentType("text/html;charset=utf-8");PrintWriter pw = null;try {pw = resp.getWriter();String code = null != session.getAttribute("validateCode") ? session.getAttribute("validateCode").toString() : "";pw.write(code);} catch (IOException e) {log.error("ValidateCodeAction.getValidateCode 获取验证码失败",e);}finally{if(null != pw){pw.close();}}}//初始化private void init(){// 将配置的信息转换成数值try {if (strWidth != null && strWidth.length() != 0) {width = Integer.parseInt(strWidth);}if (strHeight != null && strHeight.length() != 0) {height = Integer.parseInt(strHeight);}if (strCodeCount != null && strCodeCount.length() != 0) {codeCount = Integer.parseInt(strCodeCount);}} catch (NumberFormatException e) {}x = width / (codeCount + 1);fontHeight = height - 4;codeY = height - 4;}public String vality(){init();// 定义图像bufferBufferedImage buffImg = new BufferedImage(100, height,BufferedImage.TYPE_INT_RGB);Graphics2D g = buffImg.createGraphics();// 创建一个随机数生成器类Random random = new Random();// 将图像填充为白色g.setColor(Color.WHITE);g.fillRect(0, 0, 100, height);// 创建字体,字体的大小应该根据图片的高度来定。Font font = new Font("Fixedsys", Font.ITALIC, fontHeight);// 设置字体。g.setFont(font);// 画边框。g.setColor(Color.BLACK);g.drawRect(0, 0, width +18, height - 1);// 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。g.setColor(Color.BLACK);for (int i = 0; i < 10; i++) {int x = random.nextInt(width);int y = random.nextInt(height);int xl = random.nextInt(12);int yl = random.nextInt(12);g.drawLine(x, y, x + xl, y + yl);}// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。StringBuffer randomCode = new StringBuffer();int red = 0, green = 0, blue = 0;// 随机产生codeCount数字的验证码。for (int i = 0; i < codeCount; i++) {// 得到随机产生的验证码数字。String strRand = String.valueOf(codeSequence[random.nextInt(9)]);// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。red = random.nextInt(255);green = random.nextInt(255);blue = random.nextInt(255);// 用随机产生的颜色将验证码绘制到图像中。g.setColor(new Color(red, green, blue));g.drawString(strRand, (i + 1) * x, codeY);// 将产生的四个随机数组合在一起。randomCode.append(strRand);}// 将四位数字的验证码保存到Session中。HttpSession session = ServletActionContext.getRequest().getSession();HttpServletResponse resp = ServletActionContext.getResponse();session.setAttribute("validateCode", randomCode.toString());// 禁止图像缓存。resp.setHeader("Pragma", "no-cache");resp.setHeader("Cache-Control", "no-cache");resp.setDateHeader("Expires", 0);resp.setContentType("image/jpeg");ByteArrayOutputStream output = new ByteArrayOutputStream();ImageOutputStream imageOut = null;try {imageOut = ImageIO.createImageOutputStream(output);ImageIO.write(buffImg, "JPEG", imageOut);ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());this.setImageStream(input);} catch (IOException e) {log.error("ValidateCodeAction.execute 验证码创建失败", e);}finally{if(null != imageOut){try {imageOut.close();} catch (IOException e) {log.error("ValidateCodeAction.execute 流关闭失败", e);}}}return SUCCESS;}public ByteArrayInputStream getImageStream() {return imageStream;}public void setImageStream(ByteArrayInputStream imageStream) {this.imageStream = imageStream;}}


<action name="validate" class="com.***.commons.app.system.action.ValidateCodeAction" method="vality"><!-- 验证码图片宽 --><param name="strWidth">80</param><!-- 验证码图片高 --><param name="strHeight">20</param><!-- 验证码图片数字数量 --><param name="strCodeCount">4</param><result name="success" type="stream"><param name="contentType">image/jpeg</param>            <param name="inputName">imageStream</param></result></action>

虽然配置文件指定了图片的大小,但是在页面还是可以通过设置width和height改变图片的大小的



0 0