Struts2 拦截器注解(二十七)

编程入门 行业动态 更新时间:2024-10-28 16:16:43

Struts2  拦截器<a href=https://www.elefans.com/category/jswz/34/1768912.html style=注解(二十七)"/>

Struts2 拦截器注解(二十七)

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"
".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 就不说了

更多推荐

Struts2 拦截器注解(二十七)

本文发布于:2024-02-12 03:15:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1685554.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注解   二十七   拦截器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!