web开发(十) struts2之图片验证码

时间:2022-12-30 18:01:09

1、配置前端页面

 

web开发(十) struts2之图片验证码web开发(十) struts2之图片验证码
1 <!-- 验证码-->
2           <div class="form-group " style="padding-left: 9%;" id="show"> 
3                   <span class="glyphicon glyphicon-picture pull-left input-group" style="padding-top: 8px;"></span>
4                 <input type="text" class="form-control col-md-7 pull-left" maxlength="4" id="user.user_code" name="user.user_code" placeholder="验证码" style="width:100px;margin-left: 2%">
5                   <img  alt="" src="Code.action" src="video/Crocodile.jpg" onclick="this.src='Code.action?'+ Math.random();" class="pull-left" style="width:65px;height: 35px;margin-left: 2%;"/>
6                   <small class="control-label pull-left" style="margin-top: 10px;margin-left: 5px;">(点击图片刷新)</small>
7                   <label class="control-label pull-left" id="msg_code" style="color: red;margin-top: 3px;margin-left: 5px;"></label>
8           </div>
login.jsp

 

其中  src="Code.action"  onclick="this.src='Code.action?'+ Math.random();",分别为action的name和每次点击图片都自动刷新一次

 

2、配置Action

 

web开发(十) struts2之图片验证码web开发(十) struts2之图片验证码
1 <action name="Code" class="Action.LoginOrRegisterAction" method="getCheckCodePic">
2                 <result name="success" type="stream"> 
3                       <param name="contentType">image/jpeg</param>
4                       <param name="input2">inputStream</param> 
5                       <param name="bufferSize">2048</param>    
6                 </result>
7            </action>
struts.xml

 

3、Action实例

web开发(十) struts2之图片验证码web开发(十) struts2之图片验证码
 1  //获取验码图片
 2     public String getCheckCodePic() {
 3           int WIDTH = 60;
 4           int HEIGHT = 20;
 5          HttpServletResponse response = ServletActionContext.getResponse();
 6    
 7          // 设置浏览器不要缓存此图片
 8          response.setHeader("Pragma", "no-cache");
 9    
10          response.setHeader("Cache-Control", "no-cache");
11    
12          response.setDateHeader("Expires", 0);
13    
14          String str = "0123456789qwertyuiopasdfghjklzxcvbnm";
15    
16          char[] rand = new char[4];
17    
18          Random random = new Random();
19    
20          for (int i = 0; i < 4; i++)
21          {
22              rand[i] = str.charAt(random.nextInt(36));
23          }
24    
25          String rands =new String(rand);
26    
27          BufferedImage image = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
28    
29          Graphics g = image.getGraphics();
30    
31          // 产生图像
32          // 画背景
33          g.setColor(new Color(0xDCDCDC));
34    
35          g.fillRect(0, 0, WIDTH, HEIGHT);
36    
37          // 随机产生 120 个干扰点
38    
39          for (int i = 0; i < 120; i++)
40          {
41              int x = (int) (Math.random() * WIDTH);
42    
43              int y = (int) (Math.random() * HEIGHT);
44    
45              int red = (int) (Math.random() * 255);
46    
47              int green = (int) (Math.random() * 255);
48    
49              int blue = (int) (Math.random() * 255);
50    
51              g.setColor(new Color(red, green, blue));
52    
53              g.drawOval(x, y, 1, 0);
54          }
55    
56          g.setColor(Color.BLACK);
57    
58          g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));
59    
60          // 在不同的高度上输出验证码的每个字符
61    
62          g.drawString("" + rands.charAt(0), 1, 17);
63    
64          g.drawString("" + rands.charAt(1), 16, 15);
65    
66          g.drawString("" + rands.charAt(2), 31, 18);
67    
68          g.drawString("" + rands.charAt(3), 46, 16);
69    
70          System.out.println(rands);
71    
72          // 结束图像 的绘制 过程, 完成图像
73          g.dispose();
74    
75          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
76    
77          try {
78              ImageIO.write(image, "jpeg", outputStream);
79        
80              ByteArrayInputStream input = new ByteArrayInputStream(outputStream.toByteArray());
81        
82              this.setInputStream(input);
83              Map<String, Object> session = ActionContext.getContext().getSession();
84              session.put("checkCode", rands);
85              input.close();
86              outputStream.close();
87          } catch (IOException e) {
88              // TODO Auto-generated catch block
89              e.printStackTrace();
90          }
91          return SUCCESS;    
92     } 
LoginOrRegisterAction

 

4、另一个Action(进行表单验证,通过获取之前保存Session的key)

 

web开发(十) struts2之图片验证码web开发(十) struts2之图片验证码
 1 //验证用户码是否正确
 2             Map<String, Object> session1=ActionContext.getContext().getSession();
 3             if(user.getUser_code()!=null && "".equals(user.getUser_code())==false) {
 4                 String code=(String) session1.get("checkCode");
 5                 if(code.equals(user.getUser_code())==false) {
 6                     //验证码错误,返回状态值
 7                     map2.put("LoginStatus", "303");
 8                     System.out.println("验证码错误");
 9                     String ReturnData=JSONObject.toJSONString(map2); //把Map集合封装成Json形式的字符串
10                     inputStream=new ByteArrayInputStream(ReturnData.getBytes("UTF-8"));
11                     return SUCCESS;
12                 }
13                 
14             }
LoginAction