struts2自定义拦截器

自定义拦截器1

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

public class MyInterceptor1 implements Interceptor {

@Override
public void destroy() {
}

@Override
public void init() {
}

@Override
public String intercept(ActionInvocation invocation) throws Exception {
	System.out.println("1 执行interceptor1的action前面的代码!");
	String result = invocation.invoke();
	System.out.println("5 执行interceptor1的action后面的代码!");
	return result;
}
}

自定义拦截器2

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

public class MyInterceptor2 implements Interceptor {

@Override
public void destroy() {
}

@Override
public void init() {
}

@Override
public String intercept(ActionInvocation invocation) throws Exception {
	System.out.println("2 执行interceptor2的action前面的代码!");
	String result = invocation.invoke();
	System.out.println("4 执行interceptor2的action后面的代码!");
	return result;
}
}

action类

import com.opensymphony.xwork2.ActionSupport;
//图书操作类
public class BookAction extends ActionSupport {
//接收页面参数
private String name;
public void setName(String name) {
	this.name = name;
}

private String password;
public void setPassword(String password) {
	this.password = password;
}

   public String list(){
	System.out.println("3 执行了图书的list方法!");
	System.out.println(name);
	System.out.println(password);
	return SUCCESS;
}
}

在struts.xml文件中配置拦截器,并定义拦截器栈。

注意:在配置action时,引用了自定义的拦截器栈后,默认的拦截器栈(defaultStack)也要引用,并且放在配置的第一位置。否则,struts2的很多核心功能将失效。例如不能接收页面传过来的参数。

<?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>
<package name="interceptor" extends="struts-default" namespace="/interceptor">
	<!-- 配置自定义拦截器 -->
	<interceptors>
		<!-- 定义拦截器 -->
		<interceptor name="interceptor1" class="edu.scut.d_Interceptor.MyInterceptor1"/>
		<interceptor name="interceptor2" class="edu.scut.d_Interceptor.MyInterceptor2"/>
		<!-- 定义拦截器栈 -->
		<interceptor-stack name="myStack">
			<!-- 一个拦截器栈包含多个拦截器 -->
			<!-- 注意:struts2的默认拦截器一定要配置在第一位!否则会被覆盖! -->
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<interceptor-ref name="interceptor1"></interceptor-ref>
			<interceptor-ref name="interceptor2"></interceptor-ref>
		</interceptor-stack>
	</interceptors>

	<action name="book_*" class="edu.scut.d_Interceptor.BookAction" method="{1}" >
		<!-- 引入拦截器 -->
		<interceptor-ref name="myStack"></interceptor-ref>
		<result >/succ.jsp</result>
	</action>
</package>

struts2的执行过程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值