注解的作用就是代替传统的xml配置文件,struts2提供了注解功能,这样我们就不需要再配置struts.xml文件。与Action相关的注解有:
ParentPackage:指定action所在包要继承的包
Namespace:所属action的命名空间
Result:定义一个result映射
Results:定义一组result映射
下面看一个注解配置Action的实例:
@Namespace("/test")
@Result("success.jsp")
@Results({
@Result(name="input",value="/input.jsp"),
@Result("name="error",value="/error.jsp",type=ServletDispatcherResult.class)
})
public class AnnotationAction implements Action{
public String exceute() throws Exception{
return SUCCESS;
}
public String input throws Exception{
return INPUT;
}
public String error() throws Exception{
return ERROR;
}
}
在Web.xml文件添加FilterDispatcher过滤器配置,为FilterDispatcher过滤器添加actionPackages参数,如下:
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>org.struts.action</param-value>
</init-param>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</filter>
测试url:
http://localhost:8080/test/annotation.action
http://localhost:8080/test/annotation.action!input.action
http://localhost:8080/test/annotation.action!error.action