struts2学习4:利用自定义拦截器实现登录权限验证
通过例子可以很好理解struts2中的自定义拦截器,如果用户登录成功可以访问action中的所有方法,如果用户没有登录则不可以访问action中的方法,并且提示“没有权限执行该操作”。
本例子重点说明自定义拦截器的使用方法,对于登录等界面不做过多的代码编写。
user.jsp,用来实现用户登录功能,代码如下:1
2
3
4
5<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
   request,getSession().setAttribute("user","zju");
%>
用户已经登录
quit.jsp,用来实现用户退出功能,代码如下:1
2
3
4
5<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
   request,getSession().removeAttribute("user");
%>
用户已经退出登录
message.jsp,用于显示当前用户的登录状态,代码如下:1
2
3
4
5<html>
  <body>
     ${message}
  </body>
</html>
loginAction.java代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class loginAction{
  private String message;
  public void setMessage(String message){ 
    this.message = message;
  }
  public String getMessage(){
    return message;
  }
  public String addUI(){
    this.message = "addUI";
    return "success";
  }
  public String execute() throws Exception{
    this.message = "execute";
    return "success";
  }
}
定义拦截器,要实现Interceptor接口,重写intercept()方法:在此方法中编写自己的拦截器,例如判断用户是否登录:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29package cn.zju.struts;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class PermissionInterceptor implements Interceptor {
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	public void init() {
		// TODO Auto-generated method stub
		
	}
	public String intercept(ActionInvocation invocation) throws Exception {
        Object user = ActionContext.getContext().getSession().get("user");
        if(user!=null){//代表用户已经登录,允许执行Action
          return invocation.invoke();	//执行被拦截的方法
        }
        else{
          ActionContext.getContext().put("message", "没有权限执行该操作");
     	  return "message";
        } 
	}
}
接下来就是最重要的配置文件struts.xml:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<package name="zjustruts" namespace="/test" extends="struts-default">
   <interceptors>
     <interceptor name="permission" class="cn.zju.struts.PermissionInterceptor"/>
     <interceptor-stack name="permissionStack">  <!--注: 拦截器栈,作用是为了避免Struts中默认的拦截器失效-->
         <interceptor-ref name="defaultStack"/>
         <interceptor-ref name="permission"/>
     </interceptor-stack>
   </interceptors>
   <global-results>
     <result name="success">/WEB-INF/page/message.jsp</result> <!--注: 定义全局资源,作用是让所有的success都跳转到message.jsp-->
   </global-results>
   <action name="loginAction" class="cn.zju.struts.loginAction" method="execute">
     <interceptor-ref name="permission"/> 
   </action>
</package >

