论坛首页 Java企业应用论坛

struts2 convention + rest, 真的是零配置

浏览 6898 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-06-03  

最近研究struts2的rest,看了convertion官方的教程,觉得只是列明了功能,很多配置都派不上用场,坑爹啊~~

今天发现不用配置文件(struts.xml)就能让convertion和rest跑起来,很开心,实际上很简单,下面来看看方法:

 

convertion plugin

 

开始之前,我们先加入struts2基本的包,然后加入struts2-convention-plugin这个包,因为struts-rest-plugin的URL映射跟convention冲突,这里先不加入struts-rest-plugin。

 

1.在web.xml里加入struts2拦截器,这里就不多说了。

 

2.新建一个HelloAction类,继承ActionSupport,放在以action结尾的package里。

 

package com.kalobear.sc.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {
	
	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
	
}

 

 

这里要注意下,convention默认会扫描以action结尾的package里的包来作映射,如果不放在action package里就无效了。

 

3.新建hello.jsp放在WEB-INF/content(这是convention默认访问页面的路径)下,内容如下:

 

<html>
<body>
	<h1>hello</h1>
</body>
</html>

 

 

4.启动容器,打开浏览器输入http://localhost:8080/sc-test/hello

可以看到一个很大的hello,说明成功了。struts.xml,struts.properties神马的都不用配置就可以访问action。

需要注意下,如果http://localhost:8080/sc-test/hello是访问HelloAction.execute(),然后再跳转到hello.jsp,没有HelloAction或者execute()方法用这个url访问也能看到一个很大的hello,为什么?原来convention默认会把jsp文件映射成没有.jsp后缀的url,所以如果你不肯定是否访问到execute(),可以在他里面打印下看有没信息输出。

 

不要execute()方法行不行?当然可以,比如在HelloAction里加个show(),返回"show"

 

……


public class HelloAction extends ActionSupport {

	……
	
	public String showPage() {
		return "show";
	}
	
}

 

 然后新建个hello-show.jsp到WEB-INF/content里,文件的内容我改为"hello-show"。

可以看到jsp文件是<actionName>-<methodReturn>.jsp这种格式的。

浏览器打开http://localhost:8080/sc-test/hello!showPage

叹号后面是方法名,可以看到一个很大的hello-show。我,讨厌叹号。

 

 

struts-rest-plugin

看到上面的叹号就知道,convention不够完美,这时候该上rest了。给项目加上struts-rest-plugin吧。

这时候什么都不改,直接访问ttp://localhost:8080/sc-test/hello看看

爆出了下面的错误

 

java.lang.NoSuchMethodException: com.kalobear.sc.action.HelloAction.index()

 

原来rest默认访问action的方法名是index,没关系,加个index()到HelloAction里

 

 

public class HelloAction extends ActionSupport {

	……
	
	public String index() {
		return SUCCESS;
	}
	
}
 

 

再开一次可以看到那个很大的hello了。

然后用叹号一样可以访问action的方法,不用叹号,就要遵守以下规则:

 

HTTP method URI Class.method parameters
GET /movie Movie.index  
POST /movie Movie.create  
PUT /movie/Thrillers Movie.update id="Thrillers"
DELETE /movie/Thrillers Movie.destroy id="Thrillers"
GET /movie/Thrillers Movie.show id="Thrillers"
GET /movie/Thrillers/edit Movie.edit id="Thrillers"
GET /movie/new Movie.editNew  

 

中间那个ID真是让人高兴不起来,明明用/hello/list这样访问HelloAction.list()更直观,中间还要插个XX,/hello//list这样也能访问到HelloAction.list(),更多的说明请参考官网http://struts.apache.org/2.x/docs/rest-plugin.html

 

另外,config-browser是个不错的plugin,可以看到action的详细url。

 

这篇文章只说明了零配置最简单的方法,struts convention + rest目前来说觉得还不实用,可能也是我研究不深的原因,如果各位有更实用的方法请指教。

 

附上这个例子吧,maven跑你懂的

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics