拦截器

拦截器

  •            interceptor:拦截器,拦截Action的作用。 更细粒度化的拦截。(拦截Action中的具体的方法)
  •            Fillter:过滤器:过滤从客户端向服务器发送的请求。如html、jsp

作用:

Struts2框架的核心功能依赖拦截器,权限控制等

 

Struts2的执行流程:

        

搭建Struts2的环境

编写拦截器类:继承AbstractInterceptor类

 

对拦截器进行配置:

  • 自定义拦截器:使用自己的拦截器,默认栈拦截器不执行,需要手动引入,或者自定义拦截器栈,栈里包含默认栈,再引入
  • 在action中引入拦截器
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
 <!-- 配置struts常量的值 -->
  <constant name="struts.action.extension" value="action"></constant>
 <!-- 开启静态方法 -->
 <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>

 <package name="demo1" extends="struts-default" namespace="/">
 <!-- 定义拦截器 -->
 <interceptors>
 <interceptor name="InterceptorDemo1" 
 class="com.itheima.web.interceptor.InterceptorDemo1">
 </interceptor>
  <interceptor name="InterceptorDemo2" 
 class="com.itheima.web.interceptor.InterceptorDemo2">
 </interceptor>
 </interceptors>
 
 <!-- 引入拦截器(一旦引入自定义拦截器,struts2的默认拦截器不执行,需要手动引入默认栈拦截器) -->
 <action name="actionDemo1" class="com.itheima.web.action.ActionDemo1">
 <result>/demo1/demo1.jsp</result>
  <interceptor-ref name="defaultStack"></interceptor-ref>
 <interceptor-ref name="InterceptorDemo1"></interceptor-ref>
 <interceptor-ref name="InterceptorDemo2"></interceptor-ref>
 </action>
 </package>
</struts>

 

访问Action:

 

 另一种方式:也可以引入拦截器栈

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

<struts>
 <!-- 配置struts常量的值 -->
  <constant name="struts.action.extension" value="action"></constant>
 <!-- 开启静态方法 -->
 <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
 <package name="demo1" extends="struts-default" namespace="/">
 <!-- 定义拦截器 -->
 <interceptors>
 <interceptor name="InterceptorDemo1" 
 class="com.itheima.web.interceptor.InterceptorDemo1">
 </interceptor>
  <interceptor name="InterceptorDemo2" 
 class="com.itheima.web.interceptor.InterceptorDemo2">
 </interceptor>
 
  <!-- 定义拦截器栈 -->
 <interceptor-stack name="myStack">
 <interceptor-ref name="defaultStack"/>
 <interceptor-ref name="InterceptorDemo1"/>
 <interceptor-ref name="InterceptorDemo2"/>
 </interceptor-stack>
 </interceptors>
 
 <!-- 引入拦截器(一旦引入自定义拦截器,struts2的默认拦截器不执行,需要手动引入默认栈拦截器) -->
 <action name="actionDemo1" class="com.itheima.web.action.ActionDemo1">
 <result>/demo1/demo1.jsp</result>
 <interceptor-ref name="myStack"/>
<!--   <interceptor-ref name="defaultStack"></interceptor-ref> -->
 <interceptor-ref name="InterceptorDemo1"></interceptor-ref>
 <interceptor-ref name="InterceptorDemo2"></interceptor-ref>
 </action>
 </package>
</struts>

 

posted @ 2018-10-23 10:47  IslandZzzz  阅读(243)  评论(0编辑  收藏  举报