struts2 中的验证码_第1页
struts2 中的验证码_第2页
struts2 中的验证码_第3页
struts2 中的验证码_第4页
struts2 中的验证码_第5页
已阅读5页,还剩11页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、struts2中的验证码  2009-08-04 15:28:52|  分类: commm |  标签: |字号大中小 订阅 package com.nongzi.util;       import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;    import java.awt.

2、*;    import java.awt.image.*;    import java.util.*;    import javax.imageio.*;        public class AuthImg extends HttpServlet           /定义图形验证码中绘制字符的字体    &

3、#160;   private final Font mFont =            new Font("Arial Black", Font.PLAIN, 16);        /定义图形验证码的大小        private 

4、;final int IMG_WIDTH = 100;        private final int IMG_HEIGTH = 18;        /定义一个获取随机颜色的方法        private Color getRandColor(int fc,int bc) 

5、0;                  Random random = new Random();            if(fc > 255) fc = 255;         

6、   if(bc > 255) bc = 255;            int r = fc + random.nextInt(bc - fc);            int g = fc +

7、0;random.nextInt(bc - fc);            int b = fc + random.nextInt(bc - fc);            /得到随机颜色            

8、;return new Color(r , g , b);                /重写service方法,生成对客户端的响应        public void service(HttpServletRequest request,         

9、;   HttpServletResponse response)             throws ServletException, IOException                    /设置禁止缓存      

10、      response.setHeader("Pragma","No-cache");            response.setHeader("Cache-Control","no-cache");            response.setD

11、ateHeader("Expires", 0);            response.setContentType("image/jpeg");            BufferedImage image = new BufferedImage      

12、0;         (IMG_WIDTH , IMG_HEIGTH , BufferedImage.TYPE_INT_RGB);            Graphics g = image.getGraphics();           

13、0;Random random = new Random();            g.setColor(getRandColor(200 , 250);            /填充背景色            g.fillRect(1

14、, 1, IMG_WIDTH - 1, IMG_HEIGTH - 1);            /为图形验证码绘制边框            g.setColor(new Color(102 , 102 , 102);       

15、;     g.drawRect(0, 0, IMG_WIDTH - 1, IMG_HEIGTH - 1);            g.setColor(getRandColor(160,200);            /生成随机干扰线     &

16、#160;      for (int i = 0  i < 80  i+)                            int x = random.n

17、extInt(IMG_WIDTH - 1);                int y = random.nextInt(IMG_HEIGTH - 1);                int xl = random.n

18、extInt(6) + 1;                int yl = random.nextInt(12) + 1;                g.drawLine(x , y , x +

19、 xl , y + yl);                        g.setColor(getRandColor(160,200);            /生成随机干扰线       &#

20、160;    for (int i = 0  i < 80  i+)                            int x = random.nextInt(IMG_WI

21、DTH - 1);                int y = random.nextInt(IMG_HEIGTH - 1);                int xl = random.nextInt(12)

22、60;+ 1;                int yl = random.nextInt(6) + 1;                g.drawLine(x , y , x - xl 

23、;, y - yl);                        /设置绘制字符的字体            g.setFont(mFont);            

24、;/用于保存系统生成的随机字符串            String sRand = ""            for (int i = 0  i < 6  i+)        &

25、#160;                   String tmp = getRandomChar();                sRand += tmp;        

26、        /获取随机颜色                g.setColor(new Color(20 + random.nextInt(110)                  &

27、#160; ,20 + random.nextInt(110)                    ,20 + random.nextInt(110);                /在图片上绘制系统生成的随机字符  

28、;              g.drawString(tmp , 15 * i + 10,15);                        /获取HttpSesssion对象   

29、        HttpSession session = request.getSession(true);            /将随机字符串放入HttpSesssion对象中 -            session.setAttribute("rand&quo

30、t; , sRand);            g.dispose();            /向输出流中输出图片            ImageIO.write(image, "JPEG", response.getOutputStr

31、eam();                /定义获取随机字符串方法        private String getRandomChar()                    /生成一个0、1、2的随机数字   

32、         int rand = (int)Math.round(Math.random() * 2);            long itmp = 0;            char ctmp = 

33、''            switch (rand)                            /生成大写字母           

34、;     case 1:                    itmp = Math.round(Math.random() * 25 + 65);              

35、      ctmp = (char)itmp;                    return String.valueOf(ctmp);                /生成小写字母

36、                case 2:                    itmp = Math.round(Math.random() * 25 + 97);     

37、;               ctmp = (char)itmp;                    return String.valueOf(ctmp);        

38、        /生成数字                default :                    itmp = Math.round(Math.rand

39、om() * 9);                    return  itmp + ""                         

40、60;package com.nongzi.util; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.awt.*; import java.awt.image.*; import java.util.*; import javax.imageio.*; public class AuthImg extends HttpServlet /定义图形验证码中绘制字符的字体 private final Font mFont = new Font("Arial Black&q

41、uot;, Font.PLAIN, 16); /定义图形验证码的大小 private final int IMG_WIDTH = 100; private final int IMG_HEIGTH = 18; /定义一个获取随机颜色的方法 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 + rando

42、m.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); /得到随机颜色 return new Color(r , g , b); /重写service方法,生成对客户端的响应 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException /设置禁止缓存 response.setHeader("Pragma","No-cache")

43、; response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); BufferedImage image = new BufferedImage (IMG_WIDTH , IMG_HEIGTH , BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Rand

44、om random = new Random(); g.setColor(getRandColor(200 , 250); /填充背景色 g.fillRect(1, 1, IMG_WIDTH - 1, IMG_HEIGTH - 1); /为图形验证码绘制边框 g.setColor(new Color(102 , 102 , 102); g.drawRect(0, 0, IMG_WIDTH - 1, IMG_HEIGTH - 1); g.setColor(getRandColor(160,200); /生成随机干扰线 for (int i = 0 ; i < 80 ; i+) int x

45、= random.nextInt(IMG_WIDTH - 1); int y = random.nextInt(IMG_HEIGTH - 1); int xl = random.nextInt(6) + 1; int yl = random.nextInt(12) + 1; g.drawLine(x , y , x + xl , y + yl); g.setColor(getRandColor(160,200); /生成随机干扰线 for (int i = 0 ; i < 80 ; i+) int x = random.nextInt(IMG_WIDTH - 1); int y = ra

46、ndom.nextInt(IMG_HEIGTH - 1); int xl = random.nextInt(12) + 1; int yl = random.nextInt(6) + 1; g.drawLine(x , y , x - xl , y - yl); /设置绘制字符的字体 g.setFont(mFont); /用于保存系统生成的随机字符串 String sRand = "" for (int i = 0 ; i < 6 ; i+) String tmp = getRandomChar(); sRand += tmp; /获取随机颜色 g.setColor(

47、new Color(20 + random.nextInt(110) ,20 + random.nextInt(110) ,20 + random.nextInt(110); /在图片上绘制系统生成的随机字符 g.drawString(tmp , 15 * i + 10,15); /获取HttpSesssion对象 HttpSession session = request.getSession(true); /将随机字符串放入HttpSesssion对象中 - session.setAttribute("rand" , sRand); g.dispose(); /向输出流

48、中输出图片 ImageIO.write(image, "JPEG", response.getOutputStream(); /定义获取随机字符串方法 private String getRandomChar() /生成一个0、1、2的随机数字 int rand = (int)Math.round(Math.random() * 2); long itmp = 0; char ctmp = '' switch (rand) /生成大写字母 case 1: itmp = Math.round(Math.random() * 25 + 65); ctmp = (

49、char)itmp; return String.valueOf(ctmp); /生成小写字母 case 2: itmp = Math.round(Math.random() * 25 + 97); ctmp = (char)itmp; return String.valueOf(ctmp); /生成数字 default : itmp = Math.round(Math.random() * 9); return itmp + "" web.xml中的配置: <!- 配置图形验证码Servlet ->     &

50、#160;  <servlet>            <servlet-name>img</servlet-name>            <servlet-class>com.nongzi.util.AuthImg</servlet-class>       &#

51、160;</servlet>        <!- 为图形验证码Servlet指定URL ->        <servlet-mapping>            <servlet-name>img</servlet-name>       &#

52、160;    <url-pattern>/admin/authImg.jpg</url-pattern>        </servlet-mapping>  <!- 配置图形验证码Servlet -> <servlet> <servlet-name>img</servlet-name> <servlet-class>com.nongzi.util.AuthImg</ser

53、vlet-class> </servlet> <!- 为图形验证码Servlet指定URL -> <servlet-mapping> <servlet-name>img</servlet-name> <url-pattern>/admin/authImg.jpg</url-pattern> </servlet-mapping>登陆页面代码:     <% page language="java" import="java.uti

54、l.*" pageEncoding="utf-8"%><% taglib prefix="s" uri="/struts-tags" %><%String path = request.getContextPath();String basePath = request.getScheme()+":/"+request.getServerName()+":"+request.getServerPort()+path+"/"%><!

55、DOCTYPE HTML PUBLIC "-/W3C/DTD HTML 4.01 Transitional/EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'login.jsp' starting page</title>     

56、<meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0">     <meta http-equiv="keywords" content=

57、"keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!- <link rel="stylesheet" type="text/css" href="styles.css"> ->     <script type="

58、text/javascript">       function reloadImg()       var i = Math.random();       document.getElementById("imgCode").src="authImg.jpg?"+i;      </script>  </head>

59、    <body>    <s:form name="inform" action="loginAction" namespace="/">    <table>    <tr>    <td>      <s:textfield label="用户名:" na

60、me="user.username"></s:textfield>     </td>     </tr>     <tr><td><s:password label="密码:" name="user.userpass"></s:password></td> </tr>   

61、  <tr><td><s:submit value="ok" /><s:fielderror></s:fielderror> </td> </tr>      <tr><td><s:textfield label="验证码:" name="vercode" /></td> </tr>    &#

62、160;      </table>    </s:form>        验证码:       <img name="d" id="imgCode" src="authImg.jpg"><a href="javascript:reloadImg();">看不清?</a&g

63、t; <font color="red">区分大小写!</font>    </body></html>Action的代码: private Adminuser adminuser;        private String vercode;        Resource AdminuserService adminuserS

64、ervice;                        /省略setter和getter方法           Override       public String execute() throws Exception 

65、;                        Map session = ActionContext.getContext().getSession();            String ver2 = (String )s

66、ession.get("rand");            /清空用户Session的随机验证码字符串。            session.put("rand" , null);            if (!vercod

67、e.equals(ver2)                this.addFieldError("vercode", "验证码不对,请重新输入!");                return INPUT;                        &

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论