Struts2.2 Annotation 注解配置也叫Zero Configuration(零配置),它省去了写xml文件的麻烦,可以直接在类叫进行配置,不用在java文件和xml文件中来回切换。
annotation所需要的包,在Struts2.2中是 struts2-convention-plugin-2.2.1.jar 这个包
第一步在web.xml里面写上这样的配置
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
- </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类。
struts2 annotation所建action命名规则:去掉类名的Action部分。然后将将每个分部的首字母转为小写,用’-’分割。
a) 举例:TestAction,那么访问的时候就是test.action,或者test.do或者test(这个根据你的后缀配置来定);
b) 举例:StudentListAction,那么访问的时候就是student-list.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>