除了使用配置文件配置之外,还可以使用注解来配置
下面是一些常用的注解
@Action指定一个类为action,对应配置文件中的<action>....</action>标签,其中可以配置如下属性
@Action(value = "testAction",results = {@Result(name="success",location="/success.jsp")}) public class testAction extends ActionSupport { @Override public String execute() throws Exception { return SUCCESS; } }这就相当于如下的xml配置
<action name="testAction" class="struts2.action.testAction"> <result name="success">/success.jsp</result> </action>在xml配置中如果name不写,那么默认就是success,在注解中也是,如果results中的name不写,那么默认就是success
@Actions({ @Action(value = "testAction",results = {@Result(location="/success.jsp")}), @Action(value = "testAction2",results = {@Result(location="/success.jsp")}) }) public class testAction extends ActionSupport { @Override public String execute() throws Exception { return SUCCESS; } }这是使用/testAction或者/testAction2都可以跳转到success.jsp上,因为配置了两个action映射
<action name="*" class="struts2.action.testAction" method={1}> <result name="{1}">/{1}.jsp</result> </action>这是xml配置中的通配符方式,即当我们以add来访问action时,将会进到action的add方法进行处理,当返回add时会跳转到add.jsp页面
public class testAction extends ActionSupport { @Action(value = "add",results = {@Result(name="add",location="/add.jsp")}) public String add() throws Exception { return "add"; } @Action(value = "delete",results = {@Result(name="delete",location="/delete.jsp")}) public String delete() throws Exception { return "delete"; } }这样便实现了上面的效果,这说明@Action也是可以在方法上声明的(@Actions也可以在方法上声明)
@Result配置具体返回结果,在results中使用,也可以单独在类上使用,有如下属性
@Result(name="delete",location = "/delete.jsp") public class testAction extends ActionSupport { @Action(value = "add", results = { @Result(name = "add", location = "/add.jsp") }) public String add() throws Exception { return "add"; } @Action(value = "delete") public String delete() throws Exception { return "delete"; } }虽然delete方法没有指定返回delete时要跳转到哪个页面页面,但是在类上用@Result声明了,那么就会找到类上面的这个@Result,然后跳转到delete.jsp页面
struts2注解总结----@Action和@Result
原文地址:http://blog.csdn.net/u013160932/article/details/44422039