Struts中实现验证码生成和验证

先看jsp页面:

	<td width="70" height="29" align="left">验证码:</td>
	<td width="20" height="29">
<span style="white-space:pre">		</span><input name="randomCode" type="text" class="input"><img id="randomCode" title="看不清楚请点击这里"
			width="70" height="29" alt="验证码" src="randomCode" οnclick="reloadcode(this,'${applicationScope.basePath}')"/>
<span style="white-space:pre">	</span></td>
<pre name="code" class="html"><script type="text/javascript">  

  function reloadcode(obj,base){  
  var rand=new Date().getTime(); //这里用当前时间作为参数加到url中,是为了使URL发生变化,这样验证码才会动态加载,  
            //只是一个干扰作用,无确实意义,但却又非常巧妙,呵呵  
  obj.src=base+"randomCode?abc="+rand; //其实服务器端是没有abc的字段的。  
  }  
</script>


 

再看实现类:

package ray.action;

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

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class RandomImageAction extends ActionSupport implements SessionAware,ServletResponseAware
{
    private Map<String, Object> session;
    private HttpServletResponse response;
    private static final long serialVersionUID = 1L;
    private String chknumber;
    @Override
    public String execute() throws Exception
    {
        response.setHeader("Cache-Control", "no-cache");
        int width=50; //图片宽度
        int height=20; //图片高度
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics=image.createGraphics();
        graphics.setColor(this.getBackColor());   //背景颜色
        graphics.fillRect(0, 0, width, height);
        graphics.setFont(new Font("Arial",Font.BOLD,18));
        graphics.setColor(this.getFontColor());   //字的颜色
        String number=String.valueOf(System.currentTimeMillis()%9000+1000);   //生成四位随机数
        session.put("randomCode", number);     //写入session中
        graphics.drawString(number, (int)(width*0.1), (int)(height*0.8));
        graphics.dispose();
        JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(response.getOutputStream());
        encoder.encode(image);
        response.getOutputStream().flush();    //刷新到页面生成图片
        response.getOutputStream().close();    //关闭writer
        return null;
    }
    private Color getFontColor(){
    	return Color.RED;
    }
    private Color getBackColor(){
    	return Color.GRAY;
 /*       int red=(int)(Math.random()*1000%256);
        int green=(int)(Math.random()*1000%256);
        int blue=(int)(Math.random()*1000%256);
        return new Color(red,green,blue);*/
     }
    public String getChknumber()
    {
        return chknumber;
    }
    public void setChknumber(String chknumber)
    {
        this.chknumber = chknumber;
    }
    @Override
    public void setSession(Map<String, Object> session)
    {
        // TODO Auto-generated method stub
        this.session = session;
    }
    @Override
    public void setServletResponse(HttpServletResponse response)
    {
        // TODO Auto-generated method stub
        this.response = response;
    }
    
}
最后看struts.xml

<action name="randomCode" class="randomImageAction">
	<!-- 其中不返回任何信息,这样就不会跳转页面 -->
</action>
验证:

	public String getRandomCode() {
		return randomCode;
	}

	public void setRandomCode(String randomCode) {
		this.randomCode = randomCode;
	}
<span style="font-family: Arial, Helvetica, sans-serif;">	</span><span style="font-family: Arial, Helvetica, sans-serif;">private boolean validRandomCode() {</span>
<span style="white-space:pre">		</span>Object chkNumber = session.getAttribute("randomCode");
<span style="white-space:pre">		</span>if (chkNumber == null) {
<span style="white-space:pre">			</span>return false;
<span style="white-space:pre">		</span>} else if ((randomCode).equalsIgnoreCase((String) chkNumber)) {
<span style="white-space:pre">			</span>return true;
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return false;
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>public String login() {
<span style="white-space:pre">		</span>if (user == null)
<span style="white-space:pre">			</span>return Action.LOGIN;
<span style="white-space:pre">		</span>// 验证验证码:
<span style="white-space:pre">		</span>if (!validRandomCode()) {
<span style="white-space:pre">			</span>return null;
<span style="white-space:pre">		</span>}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值