struts2 Convention插件的使用

  我们需要使用到的jar包: 

Java代码   收藏代码
  1. struts2-convention-plugin-2.1.8.jar  
  2. struts2-core-2.1.8.jar  
  3. xwork-core-2.1.6.jar  
  4. commons-fileupload-1.2.1.jar  
  5. freemarker2.3.16.jar  

struts.xml中Convention配置 
1.1. 设置结果页面路径 
默认所有的结果页面都存储在WEB-INF/content下,你可以通过设置struts.convention.result.path这个属性的值来改变到其他路径。如: 

Xml代码   收藏代码
  1. <constant name="struts.convention.result.path" value="="/WEB-INF/template/" />  



这样你在就必须将你需要跳转的页面放在template下面 
struts2支持.jsp .html .htm .vm格式的文件。 

下面是actiong和结果模版的映射关系: 


URL  Result  File that could match  Result Type 
/hello  success /WEB-INF/content/hello.jsp Dispatcher 
/hello  success /WEB-INF/content/hello-success.htm Dispatcher 
/hello  success /WEB-INF/content/hello.ftl FreeMarker 
/hello  input /WEB-INF/content/hello-world-input.vm Velocity 
/hello  error /WEB-INF/content/test/test2/hello-error.html Dispatcher 



以上的内容来自struts2的文档 
[url]http://struts.apache.org/2.1.6/docs/convention-plugin.html [/url] 

当然,简单的通过默认的方式来进行配置不能完全满足实际项目的需要。所幸,convention的零配置是非常灵活的。 

1.2. 设置Convention搜索包 
默认包路径包含action,actions,struts,struts2的所有包都会被struts作为含有Action类的路径来搜索。你可以通过设置struts.convention.package.locators属性来修改这个配置。如: 

Xml代码   收藏代码
  1. <constant name="struts.convention.package.locators" value="web,action" />   




则定义了在项目中,包路径包含web和action的将被视为Action存在的路径来进行搜索。 

Com.ustb.web.*/com.ustb.action.*都将被视为含有Action的包路径而被搜索。 

接着,Convention从前一步找到的package以及其子package中寻找 com.opensymphony.xwork2.Action 的实现以及以Action结尾的类: 

com.example.actions.MainAction 

com.example.actions.products.Display (implements com.opensymphony.xwork2.Action) 

com.example.struts.company.details.ShowCompanyDetailsAction 

1.3. 命名空间 
命名空间。从定义的.package.locators标示开始到包结束的部分,就是命名空间。举个例子: 

xxx.xxx.action.shop.helloAction的命名空间是:”/shop”。 

xxx.xxx.action.shop.detail.UserAction的命名空间是:”/shop/detail” 





1.4. Actin类名路径分割 
Convention通过如下规则确定URL的具体资源部分:去掉类名的Action部分。然后将将每个分部的首字母转为小写,用’-’分割,你可以设置struts.convention.action.name.separator 如 

Xml代码   收藏代码
  1. <contant name="struts.convention.action.name.separator" value="_" />  



还是举个例子: 

HelloAction->hello HelloWorldAction ->hello-world。 

结合上面的。 

对于action.shop.HelloAction,映射的url就是/WEB-INF/template/shop/hello_test.jsp 

猜你喜欢

转载自sirong-chan.iteye.com/blog/1966517
今日推荐