利用struts生成随机验证码(JAVA)

        大部分WEB项目都会用到登录功能,而登录功能大部分又会涉及到动态验证码的生成!那如何通过后台生成动态验证码并传到后台呢?这就是我今天所要写的:
         标题:动态验证码的生成
      开发语言:JAVA
      SSH使用情况:只用到Struts2
      开发工具:MyEclipse
      运行环境:Tomcat
      示例代码包括内容:后台action、后台Util工具类、Struts配置、前台显示JSP、struts所用到的Jar包、Jquery.js

      
      a、Struts.xml配置如下:
         
           "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  "http://struts.apache.org/dtds/struts-2.0.dtd">
         
   


captchaInput
image/jpeg




/WEB-INF/captcha/createCaptcha.jsp


   

         

      b、后台action代码:
        package com.tf.action;


        import java.awt.image.BufferedImage;
        import java.io.ByteArrayInputStream;
        import java.io.ByteArrayOutputStream;
        import java.util.Map;
        import javax.imageio.ImageIO;
        import javax.imageio.stream.ImageOutputStream;
        import org.apache.struts2.interceptor.SessionAware;
        import com.opensymphony.xwork2.ActionSupport;
        import com.tf.util.CommentUtil;


        public class CreateCaptchaAction extends ActionSupport implements SessionAware{


private static final long serialVersionUID = -3429709930752736694L;


/**
* 验证码
*/
private ByteArrayInputStream captchaInput;
private String str;
private Map session;

/**
* 获取验证码
* @return
*/
public String createCaptcha() {
try {
setCaptchaInput(createInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return "create";
}

public String create() {
return SUCCESS;
}

/**
* 将图片的以字节形式写到InputStream里

* @return
* @throws Exception
*/
private ByteArrayInputStream createInputStream() throws Exception {
// 生成4位的随机串
String str = CommentUtil.generateRandCode(4);
BufferedImage image = CommentUtil.createImage(str);
session.put("validateCode", str);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
ImageIO.write(image, "JPEG", imageOut);
imageOut.close();
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
output.close();
return input;
}


get()、set()方法....

       }

     c、后台Util工具类
       package com.tf.util;


       import java.awt.Color;
       import java.awt.Font;
       import java.awt.Graphics;
       import java.awt.image.BufferedImage;
       import java.util.Random;


       public class CommentUtil {


/**
* 生成指定位数的随机码

* @param codeLen (位数)
* @return
*/
public static String generateRandCode(int codeLen) {
int count = 0;
char str[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a','b','c','d','e','f','g',
'h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B',
'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
StringBuffer pwd = new StringBuffer();
Random random = new Random();
while (count < codeLen) {
int i = Math.abs(random.nextInt(62));
if ((i >= 0) && (i < str.length)) {
pwd.append(str[i]);
count++;
}
}
return pwd.toString();
}

/**
* 生成一个内存图片,将四个随机数写在图片上

* @param str 随机字符串
*/
public static BufferedImage createImage(String str) {
int width = 80;
int height = 25;


BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);


// 获取图形上下文
Graphics g = image.getGraphics();


// 设定验证码图片背景色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);


// 设定验证码图片边框颜色
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);


// 添加干扰点
Random random = new Random();
for (int i = 0; i < 30; i++) {
g.drawOval(random.nextInt(width), random.nextInt(height), 0, 0);
}

// 添加干扰线
g.setColor(Color.YELLOW);
for (int i = 0; i < 10; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width + 80);
int y2 = random.nextInt(height + 25);
g.drawLine(x1, y1, x2, y2);
}

// 设置验证码字体
g.setFont(new Font("Atlantic Inline", Font.PLAIN, 20));


g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.drawString(Character.toString(str.charAt(0)), 5, 20);
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.drawString(Character.toString(str.charAt(1)), 25, 20);
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.drawString(Character.toString(str.charAt(2)), 45, 20);
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.drawString(Character.toString(str.charAt(3)), 65, 20);


// 图象生效
g.dispose();
return image;
}


       }

      d、前台显示JSP:
       <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
       <%
         String path = request.getContextPath();
         String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
       %>


       
   
   
   
    
    My JSP 'createCaptcha.jsp' starting page
    


   







 
  
 
 

 
 
 
 
 
 
 
 
 
 
验证码:看不清,换一张

 

 
 

  e、WEB.XML配置:
     
  struts2
 
  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
 

     

     
  struts2
  /*
     

 
 中间所用的struts相关jar包,Jquery.js文件,网上多的是。当然JSP中用到的那段Jquery代码也可以用JS代码代替,根绝情况自己来写!

你可能感兴趣的:(综合,WEB开发(JAVA))