九、SpringMVC的RESTFul
9、1什么是RESTFul
RESTful(REST 风格)是一种当前比较流行的互联网软件架构模式,它充分并正确地利用 HTTP 协议的特性,为我们规定了一套统一的资源获取方式,以实现不同终端之间(客户端与服务端)的数据访问与交互。在传统的项目开发中,我们通常都会将操作资源的动词写进 URL 中,而这些动词通常都是我们自行定义的,并没有一个统一的规范。RESTFul 提倡我们使用统一的风格来设计 URL。通俗来讲,就是为我们的请求路径设计整套的统一风格,摒弃传统?+&符号传参,通过“/”分割参数,实现标准化统一的访问路径。
传统访问路径
http://localhost:8080/update?id=1
RESTFul风格访问路径
http://localhost:8080/update/1
9、2实现RESTFul
通过 @RequestMapping +@PathVariable 注解的方式,来实现 RESTful 风格的请求。
设置@RequestMapping请求格式
@RequestMapping(value = "/update/{chargingId}")
在Controller控制器方法的形式参数中加入@PathVarable注解,为请求路径中的占位赋值
@RequestMapping(value = "/update/{chargingId}")
public ModelAndView update(@PathVariable("chargingId") String chargingId){
ModelAndView modelAndView=new ModelAndView();
Charging charging=chargingService.findById(chargingId);
modelAndView.addObject("charging",charging);
modelAndView.setViewName("update");
return modelAndView;
}
因浏览器只能发送GET和POST请求,在使用RESTFul发送PUT和DELETE请求时,要在web.xml中加入过滤器,实现请求方式的过滤
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<servlet-name>dispatcherServlet</servlet-name>
</filter-mapping>