Struts2的Code-behind究竟是什么?ROR那样的COC配置风格吗?我在论坛里找不到关于Struts2的code-behind确切的实例,只有那个发布包中隐隐约约有一个关于person操作采用的就是code-behind风格,那么code-behind是否真的适合你?我们现在来看一个最简单的code-behind入门实例。
开发环境为:XP2下的Struts2.0.11版本, 先将所有的jar包都放入到classpath下,注意struts2-codebehind-plugin-2.0.11.jar 这个包不能少,否则code-behind无法正常使用。
打开web.xml文件,配置下:
- <web-app>
- <display-name>Struts Blank</display-name>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.FilterDispatcher
- </filter-class>
- <init-param>
- <param-name>actionPackages</param-name>
- <param-value>leo.first</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
这里需要注意的就是在配置Struts2的时候,多了一个actionPackages,表示code-behind会去搜索指定包下的Action类,(文档提到,struts.properties文件也可以设置,但我没有成功过。) 在我这里指定的是 leo.first包下的Action类。
然后来一个简单的Action,CoC风格:
- import org.apache.struts2.config.ParentPackage;
- import com.opensymphony.xwork2.ActionSupport;
- @ParentPackage("first")
- public class FirstAction extends ActionSupport {
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String execute() {
- name = "superleo";
- return SUCCESS;
- }
- }
package leo.first;
import org.apache.struts2.config.ParentPackage;
import com.opensymphony.xwork2.ActionSupport;
@ParentPackage("first")
public class FirstAction extends ActionSupport {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute() {
name = "superleo";
return SUCCESS;
}
}
还有它的配置文件:
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <package name="first" extends="struts-default" namespace="/first" />
- </struts>
FirstAction 里的@ParentPackage("first")对应的就是它配置文件里的package name="first", 也就是说想实现一个code-behind并不能真正“零配置”,与ROR的COC还是差距不小的。完成所有配置后,可以运行代码了,在你的地址栏里输入:http://localhost:8080/code_behind/first/first.action 相关的action就能正常执行了。从头到尾发现只有在配置文件里,配置那些action的url工作少了,其它的还是不变,而且Action还需要使用元数据,因此感觉是XML+Annotation勉强组合在一起。 不知道大家在使用code-behind是怎么简化开发的呢?
源程序在附件里,大家感兴趣的话,可以下载看看,直接导入到MyEclipse下运行即可。