用struts做一个带有随机数字的图片验证登录模块

在我们平常的工作中,登录模块有一个小的功能,就是图片验证模块,今天我就把步骤一步一步写出来。

1.新建一个web service,然后再WebRoot写,一个contentType="image/jpeg"格式的image.jsp页面,最后一句代码是将页面以图片输出。

 1 <%@ page language="java" pageEncoding="UTF-8"%>
 2 <%@ page contentType="image/jpeg"  
 3 
 4 import="java.awt.*,java.awt.image.*,java.util.*,javax.image
 5 
 6 io.*" %>
 7 <%!
 8         //产生随机色
 9     public Color getColor(){
10         Random random = new Random();
11         int r = random.nextInt(256);//0-255
12         int g = random.nextInt(256);
13         int b = random.nextInt(256);
14         return new Color(r,g,b);
15     }
16         //获得四个随机的四个数字,用字符串进行拼接
17     public String getNum(){
18         String str = "";
19         Random random = new Random();
20         for(int i=0;i<4;i++){
21             str += random.nextInt(10);//0-9
22         }
23         return str;
24     }
25 %>
26 <%      //下面三行代码将浏览器缓存清掉
27     response.setHeader("pragma", "mo-cache");
28     response.setHeader("cache-control", "no-cache");
29     response.setDateHeader("expires", 0);
30         //产生一个矩形框
31     BufferedImage image = new BufferedImage
32 
33 (80,30,BufferedImage.TYPE_INT_RGB);
34     //产生一个画笔
35     Graphics g = image.getGraphics();
36         //设置产生的数字的颜色
37     g.setColor(new Color(200,200,200));
38         //产生一个矩形框
39     g.fillRect(0,0,80,30);
40     
41     //产生30条长度 颜色不变的线段
42     for (int i = 0; i < 30; i++) {
43         Random random = new Random();
44         int x = random.nextInt(80);
45         int y = random.nextInt(30);
46         int xl = random.nextInt(x+10);
47         int yl = random.nextInt(y+10);
48         g.setColor(getColor());
49         g.drawLine(x, y, x + xl, y + yl);
50     }
51     
52     //产生字体的样式 大小 颜色 和获得随机数字
53     g.setFont(new Font("serif", Font.BOLD,16));
54     g.setColor(Color.BLACK);
55     String checkNum = getNum();//"2525"
56     //给产生的字符串间隔变大
57     StringBuffer sb = new StringBuffer();
58     for(int i=0;i<checkNum.length();i++){
59         sb.append(checkNum.charAt(i)+" ");//"2 5 2 
60 
61 5"
62     }
63         //将数字写入矩形框
64     g.drawString(sb.toString(),15,20);
65     //将数字保存到session中
66     session.setAttribute("CHECKNUM",checkNum);//2525
67     //将图片以字节流输出
68     ImageIO.write
69 
70 (image,"jpeg",response.getOutputStream());
71         //清楚缓存
72     out.clear();
73     out = pageContext.pushBody();
74 %>
View Code

2.在/js-day03/WebRoot/WEB-INF/lib下添加struts2-2.3.1.1的jar包,至于jar包版本好像没有什么要求

2.在web.xml文件中配置struts2的核心过滤器

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3  xmlns="http://java.sun.com/xml/ns/javaee" 
 4  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 5  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 6  
 7  
 8  
 9     <!-- 核心过滤器 -->
10     <filter>
11         <filter-name>StrutsPrepareAndExecuteFilter</filter-name>
12         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
13     </filter>
14     <filter-mapping>
15         <filter-name>StrutsPrepareAndExecuteFilter</filter-name>
16         <url-pattern>/*</url-pattern>
17     </filter-mapping>
18     
19     
20 </web-app>
View Code

3.在src目录下配置struts.xml文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4     "http://struts.apache.org/dtds/struts-2.0.dtd">
 5 
 6 <struts>
 7 
 8     <package name="checkcodePackage" extends="struts-default" namespace="/">    
 9         <action 
10             name="checkRequest" 
11             class="cn.itcast.javaee.js.checkcode.CheckcodeAction" 
12             method="check">
13         </action>
14     </package>
15 
16 </struts>
View Code

4.在WebRoot下建立image和js两个文件夹

 1 //创建AJAX异步对象,即XMLHttpRequest
 2 function createAJAX(){
 3     var ajax = null;
 4     try{
 5         ajax = new ActiveXObject("microsoft.xmlhttp");
 6     }catch(e1){
 7         try{
 8             ajax = new XMLHttpRequest();
 9         }catch(e2){
10             alert("你的浏览器不支持ajax,请更换浏览器");
11         }
12     }
13     return ajax;
14 }
ajax.js

5.写action页面CheckcodeAction.java

 1 package cn.itcast.javaee.js.checkcode;
 2 
 3 import java.io.PrintWriter;
 4 import javax.servlet.http.HttpServletResponse;
 5 import org.apache.struts2.ServletActionContext;
 6 import com.opensymphony.xwork2.ActionContext;
 7 import com.opensymphony.xwork2.ActionSupport;
 8 
 9 /**
10  * 验证码检查
11  * @author AdminTC
12  */
13 public class CheckcodeAction extends ActionSupport{
14     //客户端验证码
15     private String checkcode;//2525
16     //注入客户端验证码
17     public void setCheckcode(String checkcode) {
18         this.checkcode = checkcode;
19     }
20     /**
21      * 验证
22      */    
23     public String check() throws Exception {
24         //图片路径
25         String tip = "images/MsgError.gif";
26         //从服务器获取session中的验证码
27         String checkcodeServer = (String) ActionContext.getContext().getSession().get("CHECKNUM");
28         //将客户端的验证码与服务端的验证码进行比较
29         if(checkcode.equals(checkcodeServer)){
30             tip = "images/MsgSent.gif";
31         }
32         //以IO流的方式将tip变量的值输出到AJAX异步对象中
33         HttpServletResponse response = ServletActionContext.getResponse();
34         response.setContentType("text/html;charset=UTF-8");
35         PrintWriter pw = response.getWriter();
36         pw.write(tip);
37         pw.flush();
38         pw.close();
39         //以下方式不是最好的,但可以完成AJAX异步交互
40         return null;
41     }
42 }
View Code

6.在WebRoot下写02_checkcode.jsp页面

 1 <%@ page language="java" pageEncoding="UTF-8"%>
 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 3 <html>
 4   <head>
 5     <title>验证码检查</title>
 6     <script type="text/javascript" src="js/ajax.js"></script>
 7   </head>
 8   <body>
 9     
10     <form>
11         <table border="0" align="center">
12             <tr>
13                 <th>验证码:</th>
14                 <td><input size="2" type="text" name="checkcode" id="checkcodeID" maxlength="4"/></td>
15                 <td><img src="01_image.jsp"/>
16                 <td id="res"></td>
17             </tr>
18         </table>
19     </form>
20     
21     <script type="text/javascript">
22         //去掉二边的空格
23         function trim(str){"  zhaojun  "
24             str = str.replace(/^\s*/,"");//"zhaojun  "     
25             str = str.replace(/\s*$/,"");//"zhaojun"
26             return str;     
27         }
28     </script>
29     
30     <script type="text/javascript">
31         document.getElementById("checkcodeID").onkeyup = function(){
32             var checkcode = this.value;
33             checkcode = trim(checkcode);//2525
34             if(checkcode.length == 4){
35                 //NO1)
36                 var ajax = createAJAX();
37                 //NO2)
38                 var method = "POST";
39                 var url = "${pageContext.request.contextPath}/checkRequest?time="+new Date().getTime();
40                 ajax.open(method,url);
41                 //NO3)
42                 ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
43                 //NO4)
44                 var content = "checkcode=" + checkcode;
45                 ajax.send(content);
46             
47                 //--------------------------------------------------------等待
48                 
49                 //NO5)
50                 ajax.onreadystatechange = function(){
51                     if(ajax.readyState == 4){
52                         if(ajax.status == 200){
53                             //NO6)
54                             var tip = ajax.responseText;
55                             
56                             //NO7)
57                             var img = document.createElement("img");
58                             img.src = tip;
59                             img.style.width = "14px";
60                             img.style.height = "14px";
61                             var td = document.getElementById("res");
62                             td.innerHTML = "";
63                             td.appendChild(img);
64                         }
65                     }
66                 }
67             }else{
68                 //清空图片
69                 var td = document.getElementById("res");
70                 td.innerHTML = "";
71             }
72         }
73     </script>    
74 
75   </body>
76 </html>
View Code

7.总结

最后结果

一步一步,边做边思考下一步,加油

posted @ 2016-12-03 20:14  daniel-lij  阅读(148)  评论(0编辑  收藏  举报