用struts2的拦截器实现登录验证,同时登录界面加上验证码

1、验证码实现:AuthorityAction

    

  1 package com.sram.action;
  2 
  3 import java.awt.Color;
  4 import java.awt.Font;
  5 import java.awt.Graphics;
  6 import java.awt.Graphics2D;
  7 import java.awt.image.BufferedImage;
  8 import java.io.ByteArrayInputStream;
  9 import java.io.ByteArrayOutputStream;
 10 import java.io.IOException;
 11 
 12 import java.util.Random;
 13 
 14 import javax.imageio.ImageIO;
 15 import javax.imageio.stream.ImageOutputStream;
 16 import javax.servlet.http.HttpServletRequest;
 17 import javax.servlet.http.HttpSession;
 18 
 19 import org.apache.struts2.ServletActionContext;
 20 
 21 import com.opensymphony.xwork2.ActionSupport;
 22 
 23 public class CheckCodeAction extends ActionSupport{
 24     
 25     private ByteArrayInputStream inputStream;//用于输出验证码
 26     
 27     private static final long serialVersionUID = 1L;
 28     private static final int HEIGHT =30;
 29     private static final int WIDTH = 80;
 30     
 31     private StringBuffer randomCode;
 32 
 33     
 34     
 35     public ByteArrayInputStream getInputStream() {
 36         return inputStream;
 37     }
 38 
 39     public void setInputStream(ByteArrayInputStream inputStream) {
 40         this.inputStream = inputStream;
 41     }
 42 
 43     public String createCheckCode() throws IOException{
 44         
 45         // 内存中的一副图片,指定宽 高,类型 实际开发就用REB
 46         BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
 47                 BufferedImage.TYPE_INT_RGB);
 48 
 49         // 往图片上写数据 代表图形 往图形对象上写数据,肯定要利用它的方法 很多draw
 50         Graphics g = image.getGraphics();
 51 
 52         // 1,设置背景色
 53         setBackGround(g);
 54         // 2,设置边框
 55         setBorder(g);
 56         // 3,画干扰线
 57         drawRandomLine(g);
 58     
 59         // 4,写随机数
 60         drawRandomNum((Graphics2D) g);
 61         
 62         HttpServletRequest request = ServletActionContext.getRequest();
 63         HttpSession session=request.getSession();
 64         session.setAttribute("randomCode", randomCode.toString());
 65         ByteArrayOutputStream output = new ByteArrayOutputStream();  
 66         ImageOutputStream imageOut=ImageIO.createImageOutputStream(output); ;
 67         ImageIO.write(image, "jpg", imageOut);
 68         imageOut.close();  
 69         ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());  
 70         this.setInputStream(input);  
 71         return SUCCESS;  
 72 
 73     }
 74     
 75     private void drawRandomNum(Graphics2D g) {
 76         g.setColor(Color.RED);
 77         g.setFont(new Font("宋体",Font.BOLD,20));
 78         
 79         int x=10;
 80         //String base = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0a";
 81         String base = "abceefjhijklmnopqrstABCEEFJHIJKLMNOPQRST1234567890";
 82         //写4个汉字 [u4e00-u9fa5] 匹配汉字
 83         randomCode = new StringBuffer();
 84         for(int i=0;i<4;i++){
 85             
 86             //30*3.14/180 代表30度 
 87             int degree = new Random().nextInt()%25;//-30到30
 88             
 89             String ch = base.charAt(new Random().nextInt(base.length()))+"";
 90             g.rotate(degree*Math.PI/180,x,20);//设置旋转弧度
 91             g.drawString(ch, x, 20);
 92             g.rotate(-degree*Math.PI/180,x,20);//不要影响下一次旋转
 93             x+=18;//设置相邻的字符之间的间距
 94             randomCode.append(ch);
 95         }
 96         
 97     }
 98 
 99     private void drawRandomLine(Graphics g) {
100         g.setColor(Color.GREEN);
101 
102         for (int i = 0; i < 5; i++) {
103             int x1 = new Random().nextInt(WIDTH);
104             int y1 = new Random().nextInt(HEIGHT);
105 
106             int x2 = new Random().nextInt(WIDTH);
107             int y2 = new Random().nextInt(HEIGHT);
108 
109             g.drawLine(x1, y1, x2, y2);
110         }
111 
112     }
113 
114     private void setBorder(Graphics g) {
115         g.setColor(Color.BLUE);
116         g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
117 
118     }
119 
120     private void setBackGround(Graphics g) {
121         g.setColor(Color.WHITE);
122         g.fillRect(0, 0, WIDTH, HEIGHT);
123     }
124 
125 }

2、拦截器实现:AuthorityInterceptor

 1 package com.sram.interceptor;
 2 
 3 import javax.servlet.ServletContext;
 4 
 5 import org.apache.struts2.ServletActionContext;
 6 
 7 import com.opensymphony.xwork2.ActionInvocation;
 8 import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
 9 
10 public class AuthorityInterceptor extends MethodFilterInterceptor{
11     
12     @Override
13     protected String doIntercept(ActionInvocation actioninvocation) throws Exception {
14         // TODO Auto-generated method stub
15         Object user=ServletActionContext.getRequest().getSession().getAttribute("adminUser");
16         if(user!=null){
17             System.out.println("(2)");
18             return actioninvocation.invoke();//递归调用拦截器
19         }else{
20             
21             //返回到登陆页面
22             return "login";
23         }
24     }
25 
26 }

3、登录:AdminAction

 1 package com.sram.action;
 2 
 3 import javax.servlet.RequestDispatcher;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpSession;
 6 
 7 import org.apache.struts2.ServletActionContext;
 8 
 9 import com.opensymphony.xwork2.ActionSupport;
10 import com.sram.entity.AdminUser;
11 import com.sram.service.AdminService;
12 
13 public class AdminAction extends ActionSupport{
14     
15     private AdminUser user;
16     private String checkcode;
17     private String url;
18     private String message;
19     
20     public AdminUser getUser() {
21         return user;
22     }
23     public void setUser(AdminUser user) {
24         this.user = user;
25     }
26     
27     public String getCheckcode() {
28         return checkcode;
29     }
30     public void setCheckcode(String checkcode) {
31         this.checkcode = checkcode;
32     }
33     
34     
35     public String getUrl() {
36         return url;
37     }
38     public void setUrl(String url) {
39         this.url = url;
40     }
41     public String getMessage() {
42         return message;
43     }
44     public void setMessage(String message) {
45         this.message = message;
46     }
47     /**
48      * 跳转到登陆页面
49      * */
50     public String loginInput(){
51         
52         return SUCCESS;
53     }
54     /**
55      * 进行登录操作
56      * */
57     public String admin(){
58     
59         //判断验证码输入是否正确
60         HttpServletRequest request=ServletActionContext.getRequest();
61         HttpSession session=request.getSession();
62         String rightcheckCode=session.getAttribute("randomCode").toString();
63         //验证码不区分大小写
64          url="Admin_loginInput";//登录页面
65         if(checkcode.toLowerCase().equals(rightcheckCode.toLowerCase())){
66 
67             AdminUser adminUser=AdminService.getUserByNameAndPwd(user);
68            
69             
70             if(adminUser!=null){
71                 session.setAttribute("adminUser", adminUser);
72                 return "loginSuccess";
73                 
74             }else{
75                 
76                 message="用户名或者密码错误!";
77             
78             }
79         }else{
80             
81             message="验证码错误!";
82         }
83         return "message";
84     }
85     
86 
87 }

4、struts.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 
 6 <struts>
 7 
 8     <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 9    <constant name="struts.devMode" value="true" />
10      <constant name="struts.configuration.xml.reload" value="true" />
11      
12 
13     
14     <package name="default" namespace="/admin" extends="struts-default">
15 
16        
17          <interceptors>
18              <interceptor name="authority" class="com.sram.interceptor.AuthorityInterceptor"></interceptor>
19          </interceptors>
20          
21          <default-action-ref name="index" />
22 
23         <global-results>
24             <result name="login">/jump.jsp</result>
25         </global-results>
26         <global-exception-mappings>
27             <exception-mapping exception="java.lang.Exception" result="error"/>
28         </global-exception-mappings>
29         
30         <action name="index">
31             <result>/index.jsp</result>
32         </action>
33         
34         <action name="*_*" class="com.sram.action.{1}Action" method="{2}">
35             <interceptor-ref name="defaultStack"></interceptor-ref><!--  -->
36              <interceptor-ref name="authority"/>
37             <result >/admin/{1}_{2}.jsp</result>
38             <result name="message">/admin/message.jsp</result>  
39         </action>
40         
41    </package>
42    <package name="" namespace="/" extends="struts-default">
43        <action name="checkCode" class="com.sram.action.CheckCodeAction" method="createCheckCode">  
44           <result type="stream">  
45               <param name="contentType">image/jpeg</param>  
46               <param name="inputName">inputStream</param>  
47           </result>  
48       </action> 
49         
50         <action name="*_*" class="com.sram.action.{1}Action" method="{2}">
51             <result>/{1}_{2}.jsp</result>
52             <result name="loginSuccess" type="redirect">/admin/index.html</result>
53             <result name="message">/admin/message.jsp</result>  
54         </action>
55    </package>
56 
57     
58 
59     <!-- Add packages here -->
60 
61 </struts>

5、登陆界面

  1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2 <%
  3     String path = request.getContextPath();
  4     String basePath = request.getScheme() + "://"
  5             + request.getServerName() + ":" + request.getServerPort()
  6             + path + "/";
  7 %>
  8 
  9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 10 <html>
 11     <head>
 12         <base href="<%=basePath%>">
 13 
 14         <title>My JSP 'AdminLogin.jsp' starting page</title>
 15         <meta http-equiv="X-UA-Compatible" content="IE=edge"></meta>
 16         <meta http-equiv="pragma" content="no-cache">
 17         <meta http-equiv="cache-control" content="no-cache">
 18         <meta http-equiv="expires" content="0">
 19         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 20         <meta http-equiv="description" content="This is my page">
 21         <link rel="stylesheet" href="styles/admin.css" type="text/css"></link>
 22     <script type="text/javascript"><!--
 23             window.onload=function(){
 24                 var userName = document.getElementById("userName");
 25                 var pwd = document.getElementById("pwd");
 26                 
 27                 var checkcode=document.loginForm.checkcode;
 28                 var btnSubmit = document.getElementById("btnSubmit");
 29                 //验证用户名
 30                 function validateName() {
 31                     if (userName.value == "") {
 32                         document.getElementById("checkalert").innerHTML = "用户名不能为空!";
 33                         return false;
 34                     } else {
 35                         document.getElementById("checkalert").innerHTML = "";
 36                         return true;
 37                     }
 38 
 39                 }
 40                 //用户名输入框失去焦点时验证用户名
 41                 userName.onblur = function() {
 42                 
 43                     validateName();
 44                 }
 45                 //验证密码
 46                 function validatePwd() {
 47                     if (pwd.value == "") {
 48                         document.getElementById("checkalert").innerHTML = "密码不能为空!";
 49                         return false;
 50                     } else {
 51                         document.getElementById("checkalert").innerHTML = "";
 52                         return true;
 53                     }
 54                 }
 55                 //密码输入框失去焦点时验证密码
 56                 pwd.onblur = function() {
 57                     validatePwd();
 58                 }
 59                 
 60                 function validateCheckCode() {
 61                     if (checkcode.value == "") {
 62                         document.getElementById("checkalert").innerHTML = "验证码不能为空!";
 63                         return false;
 64                     } else {
 65                         document.getElementById("checkalert").innerHTML = "";
 66                         return true;
 67                     }
 68 
 69                 }
 70                 //用户名输入框失去焦点时验证用户名
 71                 checkcode.onblur = function() {
 72                 
 73                     validateCheckCode();
 74                 }
 75                 var checkcode=document.loginForm.checkcode;
 76                 var capcatoImg = document.getElementById("capcatoImg");
 77                 capcatoImg.onclick = function() {
 78                     this.src = this.src + "?" + new Date().getTime();
 79                 }
 80             
 81                 //点击按钮,提交表当
 82                 btnSubmit.onclick=function(){
 83                     if(validateName()&&validatePwd()&&validateCheckCode()){
 84                         document.loginForm.submit();    
 85                     }else{
 86                         document.getElementById("checkalert").innerHTML = "请填写完整的登录信息!";
 87                         return false;    
 88                     }
 89                 }
 90                 
 91             }
 92         
 93     --></script>
 94     </head>
 95 
 96     <body>
 97         <form name="loginForm" method="post" action="Admin_admin">
 98 
 99             <div class="login_panel">
100                 <div class="top">
101                     <img src="images/admin/login/login_top.jpg"></img>
102                 </div>
103                 <div class="account">
104                     <label>
105                         用户名
106                     </label>
107                     <input type="text" name="user.userName" id="userName"/>
108                 </div>
109                 <div class="pwd">
110                     <label>
111                         密码
112                     </label>
113                     <input type="password" name="user.pwd" id="pwd"/>
114                 </div>
115                 <div class="checkcode">
116                     <label>
117                         验证码
118                     </label>
119                     <input type="text" name="checkcode" />
120                     <img src="checkCode" alt="验证码" id="capcatoImg" />
121                 </div>
122             
123                 <div class="login_button">
124                     <input type="submit" value="登录"/>
125                     <a href="javascript:void(0)" id="btnSubmit"><img src="images/admin/login/submit.jpg" />
126                     </a>
127                     <a href="javascript:void(0)" id="btnReset"><img src="images/admin/login/reset.jpg" />
128                     </a>
129                     
130                 </div>
131             </div>
132         </form>
133 
134         <div class="foot">
135             Copyright (C) 易购网 2013-2020, All Rights Reserved
136         </div>
137     </body>
138 </html>


二、代码说明

      注意:1、拦截器的<interceptor-ref name="defaultStack"></interceptor-ref>这句话不能少,而且位置要正确,不然老报空指针异常。

      2、登录未成功时要先跳转到一个页面,在从那个页面跳转到登录页面。尤其是有frame框架时 。如先跳转到jump.jsp,

        <global-results>
            <result name="login">/jump.jsp</result>
        </global-results>

再从jump.jsp跳转到登陆界面

jump.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>   <head>     <base href="<%=basePath%>">         <title>My JSP 'jump.jsp' starting page</title>      <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="keyword1,keyword2,keyword3">  <meta http-equiv="description" content="This is my page">  <script type="text/javascript">   top.location.href="${pageContext.request.contextPath}/Admin_loginInput";  </script>     </head>     <body>     This is my JSP page. <br>   </body> </html>

原文地址:https://www.cnblogs.com/polo-longsan/p/3395349.html