struts2中的随机验证码实现

struts2实现验证码还是很方便的。struts确实给我们带来了很多的方便之处。

1:AuthCode.java是用来生成验证码图片的:

public class AuthCode {
	private ByteArrayInputStream input;  
    private ByteArrayOutputStream output;  
    private String code;// 验证码  
    private int codeNum;// 验证码字符数量  
  
    private int width;  
    private int height;  
  
    // 构造器  
    private AuthCode(int width, int height, int codeNum) {  
        this.width = width;  
        this.height = height;  
        this.codeNum = codeNum;  
  
        if (width < 15 * codeNum + 6) {  
            this.width = 13 * codeNum + 6;  
        }  
        if (height < 20) {  
            this.height = 20;  
        }  
  
        buildImage();  
    }  
  
    // 以字符串形式返回验证码  
    public String getCode() {  
        return code;  
    }  
  
    // 以输入流的形式返回验证图片  
    public ByteArrayInputStream getIamgeAsInputStream() {  
        return input;  
    }  
  
    // 以输出流的形式返回验证图片  
    public ByteArrayOutputStream getImageAsOuputStream() {  
        return output;  
    }  
  
    // 创建默认大小的验证码  
    public static AuthCode createInstance() {  
        return new AuthCode(85, 20, 4);  
    }  
  
    // 创建指定大小的验证码  
    public static AuthCode createInstance(int width, int height, int codeNum) {  
        return new AuthCode(width, height, codeNum);  
    }  
  
    // 生成验证码图片  
    private void buildImage() {  
  
        BufferedImage image = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);  
        // 获取图形上下文  
        Graphics g = image.getGraphics();  
        // 生成随机类  
        Random random = new Random();  
        // 设定背景色  
        g.setColor(getRandColor(200, 250));  
        g.fillRect(0, 0, width, height);  
        // 设定字体  
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));  
          
        // 随机产生150条干扰线,使图象中的认证码不易被其它程序探测到  
        g.setColor(getRandColor(160, 200));  
        for (int i = 0; i < 150; 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);  
        }  
  
        // 取随机产生的认证码  
        String codes = "ABCDEFGHJKLMNOPQRSTUVWXYZ23456789";  
        String sRand = "";  
        for (int i = 0; i < codeNum; i++) {  
            String rand = codes.charAt(random.nextInt(codes.length())) + "";  
            sRand += rand;  
              
            // 将认证码显示到图象中  
            g.setColor(new Color(20 + random.nextInt(110), 20 + random  
                    .nextInt(110), 20 + random.nextInt(110)));  
              
            // 将字符串绘制到图片上  
            g.drawString(rand, i * (width / codeNum) + 6, (int)((height+12)/2));  
        }  
  
        /* 验证码赋值 */  
        this.code = sRand;  
          
        // 图象生效  
        g.dispose();  
  
        try {  
            output = new ByteArrayOutputStream();  
            ImageOutputStream imageOut = ImageIO  
                    .createImageOutputStream(output);  
            ImageIO.write(image, "JPEG", imageOut);  
            imageOut.close();  
            input = new ByteArrayInputStream(output.toByteArray());  
        } catch (Exception e) {  
            System.out.println("验证码图片产生出现错误:" + e.toString());  
        }  
  
    }  
  
    // 获取随机颜色  
    private Color getRandColor(int fc, int bc) {  
        Random random = new Random();  
        if (fc > 255)  
            fc = 255;  
        if (bc > 255)  
            bc = 255;  
  
        int r = fc + random.nextInt(bc - fc);  
        int g = fc + random.nextInt(bc - fc);  
        int b = fc + random.nextInt(bc - fc);  
  
        return new Color(r, g, b);  
    }  
}

下面的是action中的调用方法:

public InputStream getInputStream(){
		AuthCode code = AuthCode.createInstance();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession seesion = request.getSession();
//		session.put("authCode", code.getCode());
		seesion.setAttribute("authcode", code.getCode());
		return code.getIamgeAsInputStream();
	}
	
	public String execute(){
		return "success";
	}

 上面代码将生成的code放入session中了,这样在验证的时候就可以进行equals了。在action对应的.xml文件中得设置struts提供的stream模式来处理result

<action name="authcode" class="project.action.ImageAction" method="execute">
   <result name="success" type="stream">
	<param name="contentType">image/jpeg</param>
   </result>
</action>

 然后还要在使用验证码图片的页面上添加链接:

<tr>
    <td width="13%" height="35" ><span class="login_txt">验证码</span></td>
    <td height="35" colspan="2" class="top_hui_text">
    <input class="wenbenkuang" name="authCode" type="text" value="" maxLength="4" size="10">
    <img src="authcode.action" alt="验证码" style="cursor:hand" title="看不清楚?换一张" οnclick="changeImage(this)"/>
 &nbsp;&nbsp;<label class="login_txt_bt">${authcode_msg }</label>
    </td>
</tr>

 这样就可以显示随机验证码图片了。

当然在做登录的时候需要验证码图片,这个用struts2真是so easy啊:下面的是登录的action,因为写的比较赶,就很随便了:

public String login(){
		String flag = "";
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String code = (String) session.getAttribute("authcode");
		if(authCode != null & authCode.toUpperCase().equals(code)){
			if(pd.queryLogin(power.getUserName(), power.getPassword()) == true){
//				session.put("power",power);
				power = pd.queryByName(power.getUserName());
				session.setAttribute("power", power);
				System.out.println(pd.queryByName(power.getUserName()).getPowerset());
				if((pd.queryByName(power.getUserName()).getPowerset()).equals("1111")){
					flag = "admin";
					System.out.println(flag);
				}else{
					flag = "adminlimit";
					System.out.println(flag);
				}
			}else{
				flag = "fail";
			}
		}else{
			authcode_msg = "验证码错误";
			flag = "error";
		}
		
		return flag;
	}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值