Struts2 拦截器注解(二十七)

本文介绍Struts2框架中拦截器注解的应用方法,包括@Before、@After及@BeforeResult三个注解的具体作用和使用场景。通过示例代码详细展示了如何在Action类中运用这些注解,并配置Struts2拦截器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.拦截器注解
Struts2在com.opensymphony,xwork2.interceptor,annotations 包中定义了3个拦截器注解类型。从而可以直接通过注解的方式,来指定action执行之前和之后需要调用的方法。
Struts2提供的3个拦截器注解类型如下:

Before:
标注一个Action方法,该方法在执行Action处理(例如:execute())执行之前调用。如果标注的方法有返回值,并且不为 null 那么这个返回值将作为Action的结果代码。

After:
标注一个Action方法,该方法将Action的处理方法执行之后被调用,如果标注的方法有返回值,那么个返回值将被忽略。

BeforeResult:
标注一个Action方法,该方法将在Action的处理方法执行之后,在result执行之前被调用。如果标注的方法有返回值,那么这个返回值将被忽略。



action.java


package com.sh.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.annotations.After;
import com.opensymphony.xwork2.interceptor.annotations.Before;
import com.opensymphony.xwork2.interceptor.annotations.BeforeResult;

public class AnnotationAction extends ActionSupport {
	@Before
	public String before(){
		System.out.println("执行before方法!");
		//如果before 有返回值将作为action的返回结果
		return "error";
	}
	@After
	public void after(){
		System.out.println("执行after方法!");
	}
	@BeforeResult
	public void beforeResult(){
		System.out.println("执行beforeresult方法!");
	}
	
	public String execute(){
		System.out.println("执行execute方法");
		return SUCCESS;
	}
}


struts.xml
<?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> 
	<!-- 如果 注解的action配置改变时候不需要重新启动tomcate -->
	<constant name="struts.devMode" value="false"/>  
    <constant name="struts.convention.classes.reload" value="true" /> 
	
	<package name="default" extends="struts-default">
		<!-- 使用拦截器注解必须配置 AnnotationWorkflowInterceptor这个拦截器 -->
		<interceptors>
			<interceptor name="annotationInterceptor" 
			class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/>
			<interceptor-stack name="annotationStack">
				<interceptor-ref name="defaultStack"/>
				<interceptor-ref name="annotationInterceptor"/>
			</interceptor-stack>
		</interceptors>
		
		<!-- 然后在使用到了拦截器注解的action中使用上面的 拦截器  -->
		<action name="annotationAction" class="com.sh.action.AnnotationAction">
			<result>/index.jsp</result>
			<result name="error">/error.jsp</result>
			<interceptor-ref name="annotationStack"/>
		</action>
		
	</package>
    
</struts>


error.jsp

 <body>
    before方法 出现异常!
 </body>


index.jsp 就不说了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值