Annotation是JDK5.0引入的新特性,以前学JAVA SE时没有感觉到有什么用,但是现在学到Struts2的Action配置时,才算真正体会到Annotation的用处。周所周知,要让URL映射到Action,必须在struts.xml中配置action标签,并制定result。其实这些完全可以在Action类的定义时就解决的,实现了零配置,当然这也是以维护难为代价的。
以下是我的一个实验过程,加深对Annotation的理解:
第一步、搭建环境,这里直接略过
第二步、编写页面(annotation.jsp index.jsp failure.jsp)
第三步、编写AnnotationAction
- package cn.guet.hj.action;
- import org.apache.struts2.convention.annotation.Namespace;
- import org.apache.struts2.convention.annotation.ParentPackage;
- import org.apache.struts2.convention.annotation.Result;
- import org.apache.struts2.convention.annotation.Results;
- import com.opensymphony.xwork2.Action;
- /**
- *
- * 使用注释配置Action
- *
- */
- <span style="color:#CC0000;">@ParentPackage("struts-default")
- @Namespace("/anno")
- @Result(name="success", location="/annotation.jsp")
- @Results({
- @Result(name="input",location="/index.jsp"),
- @Result(name="error",location="/failure.jsp")
- })</span>
- public class AnnotationAction implements Action {
- private String info;
- public String getInfo() {
- return info;
- }
- public void setInfo(String info) {
- this.info = info;
- }
- public String execute() throws Exception {
- info = "this action is configurate by Annotation!!";
- return "success";
- }
- public String input()throws Exception{
- return INPUT;
- }
- public String error()throws Exception{
- return ERROR;
- }
- }
第四步、配置web.xml,将actionPackages设置为Action的包名
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- <init-param>
- <span style="color:#FF0000;"><param-name>actionPackages</param-name>
- <param-value>cn.guet.hj.action</param-value></span>
- </init-param>
- </filter>