1、自定义的拦截器的类:
1 package it.web.interceptor;
2 import com.opensymphony.xwork2.ActionContext;
3 import com.opensymphony.xwork2.ActionInvocation;
4 import com.opensymphony.xwork2.interceptor.Interceptor;
5
6 @SuppressWarnings("serial")
7 public class PermissionInterceptor implements Interceptor {
8
9 public void destroy() {
10 }
11
12 public void init() {
13 }
14 //invoke调用的意思
15 /**
16 * invocation:action的调用者
17 */
18 public String intercept(ActionInvocation invocation) throws Exception
19 {
20 Object user = ActionContext.getContext().getSession().get("user");
21
22 /*
23 * 如果user不为null,代表用户已经登录,允许执行action中的方法
24 */
25 if(user!=null)
26 {
27 return invocation.invoke();
28 }
29
30 /*
31 * 否则,不允许执行,并在上下文中放入一个提示信息
32 */
33 ActionContext.getContext().put("message", "你没有权限执行该操作");
34
35 return "success";
36 }
37
38 }
2、在struts-xml配置文件中用到拦截器:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.action.extendsion" value="do,action"/>
<package name="interceptor" namespace="/interceptor" extends="struts-default">
<interceptors>
<interceptor name="permission" class="it.web.interceptor.PermissionInterceptor"/> <!-- 自定义的拦截器 -->
<interceptor-stack name="permissionStack">
<interceptor-ref name="defaultStack"/> <!--Struts2自带的默认的拦截栈-->
<interceptor-ref name="permission"/>
</interceptor-stack>
</interceptors>
<global-results>
<result name="success">/WEB-INF/demo/message.jsp</result>
</global-results>
<action name="permission_*" class="it.web.action.PermissionAction" method="{1}">
<interceptor-ref name="permissionStack"/> <!--使用拦截器-->
</action>
</package>
</struts>
3、permissionAction类:
1 package it.web.action;
2
3 public class PermissionAction {
4
5 private String message;
6
7 public String getMessage() {
8 return message;
9 }
10
11 public void setMessage(String message) {
12 this.message = message;
13 }
14
15 public String addUI(){
16 this.message = "addUI";
17 return "success";
18 }
19
20 public String execute(){
21 this.message = "execute";
22 return "success";
23 }
24 }
4、jsp页面:
<1>、user.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% request.getSession().setAttribute("user", "user_load"); %> 用户登录
<2>、message.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2 <%
3 String user = (String)request.getSession().getAttribute("user");
4 %>
5
6 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
7 <html>
8 <head>
9 </head>
10
11 <body>
12 用户:${user}<br>
13 ${message}
14 </body>
15 </html>