使用struts2-convention-plugin及注解注册action
新公司采用struts2,之前一直采用spring-mvc对struts快忘光了,重新学习下struts2的使用。
本文的环境已经集成了spring,集成的步骤参考这篇文章
1.引入struts2-convention-plugin包
在pom.xml中加入以下代码块
<!-- convention-plugin插件,使用了这个插件之后,就可以采用注解的方式配置Action -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
<!--config-browser-plugin插件,使用了这个插件之后,就可以很方便的浏览项目中的所有action及其与 jsp view的映射 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-config-browser-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
struts2-config-browser-plugin的作用是查看action是否被注册上,省去了访问action地址来查看是否成功的过程,访问
http://localhost:8080/web-war/config-browser/actionNames.action 即可查看action情况。
2.在struts.xml中配置struts2-convention-plugin
在配置文件中加入如下两句
<constant name="strutsnvention.package.locators" value="action" />
<constant name="struts.convention.action.includeJars" value=".*?/web-service.*?jar(!/)?,.*?/web-service*?jar(!/)?"></constant>
strutsnvention.package.locators 的作用是配置convention插件去扫描action包下面的action。默认也会扫描到这个路径,其实是多余配置,如果action在其他包下可以修改这个配置项。
struts.convention.action.includeJars 的作用是让convention插件去扫描特定的jar包,convention插件在默认的情况下是不会扫描jar中的action。另外jar的格式要规范才能被convention插件扫描到,如果没有被扫描到可以在pom文件(jar项目的)中加入如下配置
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
convention插件的其他配置项不在这里详细介绍,可以参考我的后续微博,也可以参考这篇博客。
3.编写action测试类
在package com.fyuhome.action包下创建TestSuAction
package com.fyuhome.action;
import org.apache.struts2.convention.annotation.Action;
@Action
public class TestSuAction { //extends ActionSupport 不使用注解的形式
public void test(){
System.out.println("进入TestAction");
}
}
到此为止这个action已经被注册上。
可以通过http://localhost:8080/web-war/test-su!test.action 这个地址进行访问,当然返回的是空白页。