Struts2.1 Annotation 注解配置也叫ZeroConfiguration(零配置),它省去了写xml文件的麻烦,可以直接在类叫进行配置,不用在java文件和xml文件中来回切换。
annotation所需要的包,在Struts2.1中是struts2-codebehind-plugin.jar 这个包
第一步在web.xml里面写上这样的配置
- <filter>
-
<filter-name>struts2</filter-name> -
<filter-class> -
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteF ilter -
</filter-class> -
<!-- 这里配置struts的action扫描路径 --> -
<init-param> -
<param-name>actionPackages</param-name> -
<param-value>你的action的包位置</param-value> -
</init-param> -
<init-param> -
<param-name>encoding</param-name> -
<param-value>UTF-8</param-value> -
</init-param> - </filter>
第二步建立你的Action
- <param-value>你的action的包位置</param-value>
根据你上面的配置,把所有的action类放在“你的action的包位置”.action这个包下面,并建立你的Action类。
struts2annotation所建action命名规则:去掉类名的Action部分。然后将将每个分部的首字母转为小写,用’-’分割。
注:比如像StudentListAction类,如果你在地址栏输入StudentList是访问不到的,必须输入student-list
第三步,写上Action类的Annotation
下面举一个简单的例子
- @Namespace("/test")
- @Result(name="success",
location = "/test/role.jsp", type="redirect") - public
class RoleAction extends ActionSupport{ -
@Override -
public String execute() throws Exception { -
-
return SUCCESS; -
} - }
或者:
- @Namespace("/test")
- @Result(name
= "success", location = "/test/role.jsp") - public
class RoleAction extends ActionSupport { -
@Override -
@Action(value = "/different/url", -
results = { -
@Result(name = "success", location = "/test/role.jsp", type = "redirect") -
} -
) -
public String execute() throws Exception { -
-
return SUCCESS; -
} - }
下面是没用annotation的xml配置,相信大家可以猜到上面注解的具体含义了吧
- <package
name="default" extends="struts-default" namespace="test"> -
<action name="Role" class="xxx.action.RoleAction"> -
<result type="redirect">/test/function.jsp</result> -
</action> - </package>
还有很多注解,以及路径配置问题,大家可以看Struts2文档中的Anotation部分了解。
-------------------------
另外,关于web.xml中<filter-class>应该引用哪个类
<filter>
</filter>
因为有bug,所以官方不建议使用。
推荐使用
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteF