RESTful架构,就是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。RESTful(即Representational State Transfer的缩写)其实是一个开发理念,是对http的一个很好的诠释。
1、对url进行规范,写成RESTful格式的url
非REST的url:http://.../queryItems.action?Id=001&type=T01
REST的url风格:http://.../items/001
特点:url非常简洁,将参数通过url传到服务器
2、对http方法进行规范
不管是删除、添加、更新....使用的url是一致的,如果进行删除,需要设置http的方法为delete,同理添加....
后台controller方法:判断http方法,如果是delete要执行删除,如果是post要执行添加
3、对http的contentType进行规范
请求时指定contentType,要json数据,设置成json格式的type
下面写一个简单的RESTful的例子
需求:查询商品信息,返回json数据格式
controller方法的定义:
//查询商品信息,输出json
//@RequestMapping("/itemsView/{id}")里面的{id}表示将这个位置的参数传到@PathVariable指定名称中
@RequestMapping("/itemsView/{id}")
public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id) throws Exception{
//调用service查询商品信息
ItemsCustom itemsCustom = itemsService.findItemsById(id);
return itemsCustom;
}
配置REST的前端控制器,在web.xml中配置
<!-- 配置REST 前端控制器 -->
<servlet>
<servlet-name>springmvc_rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc_rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
由于在配置前端控制器的url-partten中指定“/”时,对静态资源的解析就会出现问题。因此需要在springmvc.xml中添加对静态资源解析的方法
<!--对 静态资源解析
包括:js、css、img....
-->
<!-- 访问js开头的,映射到js路径下的所有文件 img等同理 -->
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/img/" mapping="/img/**"/>
注:url模板模式映射
@RequestMapping(value=”/viewItems/{id}):{XXX}占位符,请求的URL可以是”viewItems/1”或者”viewItems/2”,通过在方法中使用@PathVariable 注解获取{XXX}中的XXX变量。
@PathVariable:用于将请求URL中的模板变量映射到功能处理方法的参数上。
//@RequestMapping("/itemsView/{id}")里面的{id}表示将这个位置的参数传到@PathVariable指定名称中
@RequestMapping("/itemsView/{id}/{type}")
public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id,@PathVariable("type") String type) throws Exception{}