struts2 自定义拦截器 基础1案例 (登录权限)

struts2 自定义拦截器 基础一案例 (登录权限)

下拦截器的功能如下,限制没有登录的用户进入访问页面.

使用分以下几步骤:

1. 编写自定义拦截器类:

public class ManagerIntercept extends AbstractInterceptor {

//重写拦截方法

public String intercept(ActionInvocation invocation) throws Exception {
  ActionContext context = invocation.getInvocationContext();
  String user = (String) context.getSession().get("user");

 

    if (StringUtil.isNotNull(user)) {
       return invocation.invoke();
    }

    context.put("notLogin", "请先登录系统,再执行此操作.");
     return Action.ERROR;

    }

}

 

2. 于struts.xml文件中配置使用.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>


 <!-- 配制国际化资源文件-->
 <constant name="struts.custom.i18n.resources"
  value="messageResource">
 </constant>

 

 <!-- 配制请求编码(request) -->
 <constant name="struts.i18n.encoding" value="UTF-8"></constant>

 

 <!-- 配置每交启动重新读取文件 -->
 <constant name="struts.i18n.reload" value="true"></constant>

 

 <!-- 配置基本的登录请求 -->
 <package name="userManagerAction" extends="struts-default">

 

  <!-- 配制拦截器 -->
  <interceptors>
   <interceptor name="authority"
    class="com.test.intercept.ManagerIntercept">
   </interceptor>
   <interceptor-stack name="myAuthority">

   <!-- 配制默许的拦截器到拦截器栈 -->
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <interceptor-ref name="authority"></interceptor-ref>
   </interceptor-stack>
  </interceptors>

 

  <!-- 配置默认的拦截器 -->
  <default-interceptor-ref name="myAuthority" />

 

  <!-- 配制全局的result页面  -->
  <global-results>
   <result name="error">/error.jsp</result>
   <result name="login">/login.jsp</result>
  </global-results>

 

  <!-- 配制基本的请求处理action -->
  <action name="login" method="login"
   class="com.test.action.LoginAction">
   <result name="input">/login.jsp</result>
   <result name="success">/index.jsp</result>

 

   <!-- 配制拦截器 因为已定义为默认包拦截,所以此处可以不再定义,如针对单个ACTON.则于此配制
    <interceptor-ref name="myAuthority"></interceptor-ref> -->

 

   <!-- 配制异常信息处理 -->
   <exception-mapping result="error" exception="Exception">
   </exception-mapping>
  </action>
 </package>
</struts>

 

此包下的所有请求处理都将被拦截于action处理方法前.

 

----------------------------完,开发经验,以供后续开发使用与交流.-------------------------------

---------------------------------------------------尹当