Struts2实现动态验证码的生成和验证

来源:互联网 发布:寻找网络兼职 编辑:程序博客网 时间:2024/05/16 00:42

一、基本流程:

产生一个验证码页面(很小)→嵌入到表单中→点击可以刷新页面→表单提交时验证。

二、方法:

1、定义TestAction,实现画图方法

[java] view plain copy
  1. package com.zhuguang.action;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics;  
  6. import java.awt.image.BufferedImage;  
  7. import java.util.Map;  
  8.   
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.apache.struts2.interceptor.ServletResponseAware;  
  12. import org.apache.struts2.interceptor.SessionAware;  
  13.   
  14. import com.opensymphony.xwork2.ActionSupport;  
  15. import com.sun.image.codec.jpeg.JPEGCodec;  
  16. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  17.   
  18. public class TestAction extends ActionSupport implements SessionAware,ServletResponseAware  
  19. {  
  20.     private Map<String, Object> session;  
  21.     private HttpServletResponse response;  
  22.     private static final long serialVersionUID = 1L;  
  23.     private String chknumber;  
  24.     @Override  
  25.     public String execute() throws Exception  
  26.     {  
  27.         response.setHeader("Cache-Control""no-cache");  
  28.         int width=50//图片宽度  
  29.         int height=20//图片高度  
  30.         BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);  
  31.         Graphics graphics=image.createGraphics();  
  32.         graphics.setColor(this.getColor());   //背景颜色  
  33.         graphics.fillRect(00, width, height);  
  34.         graphics.setFont(new Font("Arial",Font.BOLD,18));  
  35.         graphics.setColor(this.getColor());   //字的颜色  
  36.         String number=String.valueOf(System.currentTimeMillis()%9000+1000);   //生成四位随机数  
  37.         session.put("randomCode", number);     //写入session中  
  38.         graphics.drawString(number, (int)(width*0.1), (int)(height*0.8));  
  39.         graphics.dispose();  
  40.         JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(response.getOutputStream());  
  41.         encoder.encode(image);  
  42.         response.getOutputStream().flush();    //刷新到页面生成图片  
  43.         response.getOutputStream().close();    //关闭writer  
  44.         return null;  
  45.     }  
  46.     private Color getColor(){  
  47.         int red=(int)(Math.random()*1000%256);  
  48.         int green=(int)(Math.random()*1000%256);  
  49.         int blue=(int)(Math.random()*1000%256);  
  50.         return new Color(red,green,blue);  
  51.      }  
  52.     public String getChknumber()  
  53.     {  
  54.         return chknumber;  
  55.     }  
  56.     public void setChknumber(String chknumber)  
  57.     {  
  58.         this.chknumber = chknumber;  
  59.     }  
  60.     @Override  
  61.     public void setSession(Map<String, Object> session)  
  62.     {  
  63.         // TODO Auto-generated method stub  
  64.         this.session = session;  
  65.     }  
  66.     @Override  
  67.     public void setServletResponse(HttpServletResponse response)  
  68.     {  
  69.         // TODO Auto-generated method stub  
  70.         this.response = response;  
  71.     }  
  72.       
  73. }  
注意用到session和response

2、在struts.xml文件中注册:

[html] view plain copy
  1. <action name="randomCode" class="com.zhuguang.action.TestAction">  
  2.         </action>  
其中不返回任何信息,这样就不会跳转页面

3、jsp页面编写

[html] view plain copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@taglib uri="/struts-tags" prefix="s" %>  
  4. <%  
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  7. %>  
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  9. <html>  
  10. <head>  
  11. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  12. <script type="text/javascript">  
  13. <!--  
  14.   function reloadcode(obj,base){  
  15.   var rand=new Date().getTime(); //这里用当前时间作为参数加到url中,是为了使URL发生变化,这样验证码才会动态加载,  
  16.             //只是一个干扰作用,无确实意义,但却又非常巧妙,呵呵  
  17.   obj.src=base+"randomCode.action?abc="+rand; //其实服务器端是没有abc的字段的。  
  18.   }  
  19. //-->  
  20. </script>  
  21. <title>测试页面</title>  
  22. </head>  
  23. <body>  
  24. <form action="testLogin" method="post">  
  25.   Username<input type="text" name="name"><br>  
  26.   Password<input type="text" name="password"><br>  
  27.   验证码:<input type="text" name="chknumber" id="chknumber" maxlength="4" class="chknumber_input">  
  28.   <img title="看不清楚请点击这里" width="50" height="20" src="<%=basePath%>randomCode.action" id="safecode" onclick="reloadcode(this,'<%=basePath%>')" /><br>  
  29.   <input type="submit" value="Loginin">  
  30. </form>  
  31. </body>  
  32. </html>  
4、验证

(1)在Action中添加一个验证方法

[java] view plain copy
  1. public String testLogin()  
  2.     {  
  3.         if(session.get("randomCode").equals(chknumber))  
  4.         {  
  5.             return SUCCESS;  
  6.         }  
  7.         else  
  8.         {  
  9.             return ERROR;  
  10.         }  
  11.     }  
(2)在struts.xml中进行注册

<action name="testLogin" class="com.zhuguang.action.TestAction" method="testLogin">
            <result name="success">success.jsp</result>
            <result name="error">error.jsp</result>
        </action>

0 0