struts2采用convention-plugin实现零配置
最近开始关注struts2的新特性,从这个版本开始,Struts开始使用convention-plugin代替codebehind-plugin来实现struts的零配置。
配置文件精简了,的确是简便了开发过程,但是,我们熟悉的配置突然disappear了,真是一下很不适应。跟着潮流走吧,看看该怎样来搞定convention-plugin。
使用Convention插件,你需要将其JAR文件放到你应用的WEB-INF/lib目录中,你也可以在你Maven项目的POM文件中添加下面包依赖
则将路径配置到了WEB-INF/page 下。
2. 默认包路径包含action,actions,struts,struts2的所有包都会被struts作为含有Action类的路径来搜索。你可以通过设置struts.convention.package.locators属性来修改这个配置。如:
则定义了在项目中,包路径包含web和action的将被视为Action存在的路径来进行搜索。
Com.ustb.web.*/com.ustb.action.*都将被视为含有Action的包路径而被搜索。
3. 接着,Convention从前一步找到的package以及其子package中寻找 com.opensymphony.xwork2.Action 的实现以及以Action结尾的类:
还是举个例子:
UserAction->user UserDetailAction ->user-detail。结合上面的。对于com.ustb.web.user.detail.UserDetailAction,映射的url就是/WEB-INF/content/user/detail/user-detail.jsp
6. struts支持.jsp .html .htm .vm格式的文件。
下面是actiong和结果模版的映射关系:
File that could match Result Type /hellosuccess/WEB-INF/content/hello.jspDispatcher/hellosuccess/WEB-INF/content/hello-success.htm Dispatcher/hellosuccess/WEB-INF/content/hello.ftl FreeMarker/hello-worldinput/WEB-INF/content/hello-world-input.vmVelocity/test1/test2/helloerror/WEB-INF/content/test/test2/hello-error.htmlDispatcher
?
?
?
?
?
?
?
?
?
?
?
以上的内容来自struts2的文档http://struts.apache.org/2.1.6/docs/convention-plugin.html
?
当然,简单的通过默认的方式来进行配置不能完全满足实际项目的需要。所幸,convention的零配置是非常灵活的。
通过@Action注释
对如下例子:
- packagecom.example.actions; importcom.opensymphony.xwork2.ActionSupport; importorg.apache.struts2.convention.annotation.Action; importorg.apache.struts2.convention.annotation.Actions; importorg.apache.struts2.convention.annotation.Result; importorg.apache.struts2.convention.annotation.Results; publicclassHelloWorldextendsActionSupport{ @Action(value="/other/bar",results={@Result(name="error",location="www.baidu.com",type="redirect")}) publicStringmethod1(){ return“error”; } }
package com.example.actions;import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.Actions;import org.apache.struts2.convention.annotation.Result;import org.apache.struts2.convention.annotation.Results;public class HelloWorld extends ActionSupport {@Action(value="/other/bar",results={@Result(name = "error", location = "www.baidu.com",type="redirect")}) public String method1() { return “error”; }}
当我们调用 /hello -world !method1.action 时,返回 /WEB-INF/content/hello-error.jsp
当我们调用 /other/bar!method1.action 时,返回 www.baidu.com
转自:http://javeye.javaeye.com/blog/358744