struts2的验证码及利用jquery发送ajax请求并利用json做数据交换

本文介绍了一种使用Struts2框架实现验证码功能的方法。通过ImageUtil生成带噪点的验证码图片,并利用Struts2的Action处理验证码验证逻辑。具体包括image.jsp页面交互、struts.xml配置、ImageUtil生成图片逻辑、ImageAction处理图片输出及ValidImageAction进行验证。

image.jsp :

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.4.min.js"></script>
<script type="text/javascript">
$(function(){
    $("#valiCode").blur(function(){
        $.post(
            "valid",//请求url
            {"valiCode":$(this).val()},//请求参数
            function(data){//回调函数
                if(data.ok){
                    $("#msg").html("<font style='color:red'>验证码填写正确</font>");
                }else{
                    $("#msg").html("<font style='color:red'>验证码填写错误</font>");
                    $("#image").attr("src","image?date="+new Date().getTime());
                }
            },
            "json"//返回数据data的格式为json
        );
    });
});
</script>
</head>
<body>
<img id="image" src="image"><br>
<input type="text" name="valiCode" id="valiCode"><span id="msg"></span>
</body>
</html>
struts.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">

<struts>
    <package name="demo" extends="json-default">
    
        <action name="image" class="action.ImageAction">
            <result name="success" type="stream">
                <param name="inputName">image</param>
            </result>
        </action>
        
        <action name="valid" class="action.ValidImageAction">
            <result name="success" type="json"></result>
        </action>
    </package>
</struts>
ImageUtil.java :

public class ImageUtil {
	
	private static final String[] chars={"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"};
	
	private static final int WIDTH=200;
	private static final int HEIGHT=100;
	private static final int SIZE=5;
	private static final int LINES=15;
	private static final int FONT_SIZE=45;
	
	public static Map<String,BufferedImage> getImage(){
		StringBuffer sb=new StringBuffer();
		BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
		Graphics g=image.getGraphics();
		g.setColor(Color.LIGHT_GRAY);
		g.fillRect(0,0,WIDTH,HEIGHT);
		Random random=new Random();
		for(int i=1;i<=SIZE;i++){
			g.setColor(getRandomColor());
			int j=random.nextInt(chars.length);
			g.setFont(new Font(null,Font.BOLD,FONT_SIZE));
			g.drawString(chars[j],(i-1)*WIDTH/SIZE,HEIGHT/2);
			sb.append(chars[j]);
		}
		for(int i=0;i<LINES;i++){
			g.setColor(getRandomColor());
			g.drawLine(random.nextInt(WIDTH),random.nextInt(HEIGHT),
					random.nextInt(WIDTH),random.nextInt(HEIGHT));
		}
		Map<String,BufferedImage> map=new HashMap<String,BufferedImage>();
		map.put(sb.toString(),image);
		return map;
	}
	
	private static Color getRandomColor(){
		Random random=new Random();
		return new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
	}
}
ImageAction.java :

public class ImageAction extends ActionSupport {
	
	private InputStream image;

	public InputStream getImage() {
		return image;
	}
	public void setImage(InputStream image) {
		this.image = image;
	}
	
	public String execute() throws ImageFormatException, IOException{
		Map<String,BufferedImage> map=ImageUtil.getImage();
		String str=map.keySet().iterator().next();
		ActionContext.getContext().getSession().put("str",str);
		BufferedImage bi=map.get(str);
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(baos);
		encoder.encode(bi);
		image=new ByteArrayInputStream(baos.toByteArray());
		return "success";
	}
}
ValidImageAction.java :

public class ValidImageAction extends ActionSupport {
	
	private String valiCode;
	private boolean ok;
	
	@JSON(serialize=false)
	public String getValiCode() {
		return valiCode;
	}
	public void setValiCode(String valiCode) {
		this.valiCode = valiCode;
	}
	public boolean isOk() {
		return ok;
	}
	public void setOk(boolean ok) {
		this.ok = ok;
	}
	
	public String execute(){
		String str=(String)ActionContext.getContext().getSession().get("str");
		if(str.equals(getValiCode())){
			ok=true;
		}else{
			ok=false;
		}
		return "success";
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值