struts2注解总结 -- @Action 和 @Result

除了使用配置文件配置之外,还能够使用注解来配置

以下是一些经常使用的注解

介绍:

@Action/@Actions:

@Action指定一个类为action,相应配置文件里的<action>....</action>标签,当中能够配置例如以下属性

  1. results:配置返回的结果集属性,相当于struts2中的<result>列表,能够在{}中配置属性,详细例如以下
  2. value:配置action的名字,相当于<action>中的name属性
  3. interceptorRefs:配置拦截器

@Action能够定义在类上,也能够定义在方法上

例如以下(@Result的作用后面讲,也能够和后面的配合着看)

@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映射,这样能够做到一个类相应多个地址映射。例如以下

@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映射

在xml配置中,我们有例如以下的配置方法

<action name="*" class="struts2.action.testAction" method={1}>
	<result name="{1}">/{1}.jsp</result>
</action>

这是xml配置中的通配符方式,即当我们以add来訪问action时。将会进到action的add方法进行处理。当返回add时会跳转到add.jsp页面

在注解中没有通配符能够使用,可是也能够实现类似的效果,这时@Action就要写在方法上了,就像以下这样

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配置详细返回结果。在results中使用,也能够单独在类上使用,有例如以下属性

  1. name:相应<result>中的name属性
  2. location:相应<result></result>间的地址
  3. type:相应<result>的type属性

@Result能够在类上声明。也能够和Action配置声明,假设在类上声明,那么就是全局的结果,例如以下

@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页面
 

@Results是用来声明多个结果集。使用方法和@Actions类似,这里就不再详述

猜你喜欢

转载自blog.csdn.net/qq_32352565/article/details/83692773