Struts2注解(旧&新)

旧版本使用注解:

开始使用注解使用的是  struts2-core-2.0.11.jar

这个时候的过滤器是org.apache.struts2.dispatcher.FilterDispatcher 

可以在web.xml里面指定action的祖包actionPackages

<init-param>
     	<param-name>actionPackages</param-name>
    	<param-value>manning</param-value>
  </init-param> 

被注解的内在如上manning的包下 ,类名字为 TestAction  或者 Test  extends ActionSupport  即可被注解为Struts的Action  

内容可以为空 ,空跳转。只需在类名上面加  Result(value="/test.jsp")即可,如下:

package manning.chapterTwo;
import org.apache.struts2.config.Result;
import org.apache.struts2.dispatcher.ServletDispatcherResult;
import com.opensymphony.xwork2.ActionSupport;

@Result( value="/chapterTwo/AnnotatedNameCollector.jsp" )

public class AnnotatedNameCollector extends ActionSupport {
	
}

或者

package manning.chapterTwo;

import org.apache.struts2.config.Result;
import org.apache.struts2.dispatcher.ServletDispatcherResult;

@Result(name="SUCCESS", value="/chapterTwo/HelloWorld.jsp" )

public class AnnotatedHelloWorldAction {	
    public String execute()  {  		
    	return "SUCCESS";
    }
}

如上,部分摘自《Struts2InAction》。

新版本使用注解:

但是,现在注解及过滤器已经更新了,高版本使用 struts2-core-2.3.8.jar

1.  StrutsPrepareAndExecuteFilter  在原过滤器包的ng包下面
2.  我们实现注解还需要 struts2-convention-plugin-2.1.8.1.jar
3. 可以在struts.xml或struts.properties里设置常量来设置Struts2框架读取哪些类为Action
4. struts.convention.action.packages:可以使用的Action的祖包,默认为没有, 可以读取这个包及其子包的所有头上标记了【 @Action 】 的类
5. struts.convention.package.locators:可以使用的Action的上级包,默认为【action,actions,struts,struts2】,这样就可以读取所有在包中的所有头上注册了【@Action】的类;注意设置的action应为这个包的最后一级包,如www.txidol.com.test.action.TestAction
6. struts.convention.action.suffixAction类类名的后缀,默认为Action   我们使用时砍掉后缀,如 TestAction  -->访问 test.action
7. @Result参数变化 为 @Result(name = "SUCCESS", location = "/main.jsp")    name 默认为SUCCESS
8. 多返回@Results( { @Result(name = "success", location = "/main.jsp"), @Result(name = "error", location = "/error.jsp") }) 
9. 可以加包 @ParentPackage("struts-default")   空间 @Namespace("/test")  默认为excute方法,在类名上定义@Action时
10.  其他可以定义@Action在方法上
    @Action(value = "add", results = { @Result(name = "success", location = "/index.jsp") })   
    public String add() throws Exception {   
        return SUCCESS;   
    } 


原文地址:https://www.cnblogs.com/xinyuyuanm/p/2993536.html