1、自定义的拦截器的类:
package it.web.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor; @SuppressWarnings("serial")
public class PermissionInterceptor implements Interceptor { public void destroy() {
} public void init() {
}
//invoke调用的意思
/**
* invocation:action的调用者
*/
public String intercept(ActionInvocation invocation) throws Exception
{
Object user = ActionContext.getContext().getSession().get("user"); /*
* 如果user不为null,代表用户已经登录,允许执行action中的方法
*/
if(user!=null)
{
return invocation.invoke();
} /*
* 否则,不允许执行,并在上下文中放入一个提示信息
*/
ActionContext.getContext().put("message", "你没有权限执行该操作"); return "success";
} }
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类:
package it.web.action; public class PermissionAction { private String message; public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public String addUI(){
this.message = "addUI";
return "success";
} public String execute(){
this.message = "execute";
return "success";
}
}
4、jsp页面:
<1>、user.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
request.getSession().setAttribute("user", "user_load");
%>
用户登录
<2>、message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String user = (String)request.getSession().getAttribute("user");
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head> <body>
用户:${user}<br>
${message}
</body>
</html>