Struts2.1笔记(八):Struts2的拦截器

7.1拦截器实现原理
7.2拦截器配置初步
7.2.1 struts.xml文件中定义拦截器
格式:
<interceptor name="拦截器名"class="拦截器实现类"></interceptor>
拦截器栈:多个拦截器连在一起组成拦截器栈。
格式:
<!-- 拦截器栈 -->
   <interceptor-stack name="拦截器栈名">
    <interceptor-ref name="拦截器1"></interceptor-ref>
    <interceptor-ref name="拦截器2"></interceptor-ref>
    <interceptor-ref name="拦截器3"></interceptor-ref>
   </interceptor-stack>
7.2.2 使用拦截器 通过<interceptor-ref .../>元素可以在Action内使用拦截器。
7.2.3 配置默认拦截器
默认拦截器何时起作用?
没有显示指定拦截器时,则默认的拦截器会起作用
配置默认拦截器:<default-interceptor-ref.../>元素,该元素作为<package.../>
元素的子元素使用。
格式:<default-interceptor-ref name="拦截器名或拦截器栈名"/>
7.2.4 Struts2内建的拦截器
关于内建的拦截器可查看struts-default.xml文件

7.2.5 与拦截器相关的配置元素
<interceptors.../>
<interceptor.../>
<interceptor-stack.../>
<interceptor-ref.../>
<param.../> 
<default-interceptor-ref.../>:
7.3 开发自己的拦截器
开发自己的拦截器类要实现com.opensymphony.xwork2.interceptor.Interceptor接口。
实现类代码如下:
package com.test.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyInterceptor implements Interceptor {

 @Override
 public void destroy() {
   System.out.println("destroy");

 }

 @Override
 public void init() {
  System.out.println("init");

 }

 @Override
 public String intercept(ActionInvocation invo) throws Exception {
  System.out.println("myInterceptor");
  String result = invo.invoke();
  return result;
 }

}
7.3.1使用拦截器
配置文件如下:
<?xml version="1.0" encoding="GBK"?>
<!-- 指定Struts 2配置文件的DTD信息 -->
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
 "http://struts.apache.org/dtds/struts-2.1.dtd">
<!-- struts是Struts 2配置文件的根元素 -->
<struts>
 <constant name="struts.custom.i18n.resources" value="message"></constant>
 <package name="Struts2" extends="struts-default">
  <!-- 定义 -->
    <interceptors>
   <interceptor name="myInterceptor"
    class="com.test.interceptor.MyInterceptor">
   </interceptor>
  <!-- 拦截器栈 -->
   <interceptor-stack name="myStack">
    <interceptor-ref name="myInterceptor"></interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
   </interceptor-stack>
  </interceptors>
  <!-- 配置默认拦截器-->
  <default-interceptor-ref name="myStack"></default-interceptor-ref>
 
  <action name="Register"
   class="com.test.action.RegisterAction">

   <result name="success">/Success.jsp</result>
   <result name="input">/s_Register.jsp</result>
   <!--  <interceptor-ref name="myInterceptor"></interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
   -->
   <!-- <interceptor-ref name="myStack"></interceptor-ref> -->
   <!--使用默认拦截器 -->
  </action>
 </package>
</struts>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值