SpringMVC:RESTFul风格
By: Date: 2017年2月7日 Categories: 程序 标签:

我们都知道,客户端想要操作服务器,那么只能是HTTP协议中的四种操作方式,四个方式分别是:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET用来获取资源,POST用来新建资源(或者更新资源),PUT用来更新资源,DELETE用来删除资源。那下面就实践下SpringMvc下的RESTFul风格。

1. 首先我们新建一个测试页面,其中增加四种操作的Form,代码如下:

<form action="resource/1" method="get">
	<input type="submit" value="get">
</form>
<form action="resource/1" method="post">
	<input type="submit" value="post">
</form>
<form action="resource/1" method="post">
	<input type="hidden" name="_method" value="PUT">
	<input type="submit" value="put">
</form>
<form action="resource/1" method="post">
	<input type="hidden" name="_method" value="DELETE">
	<input type="submit" value="delete">
</form>

注:Form只支持GET或者POST,因此PUT以及DELETE操作的Form是通过POST实现的,其中包含了两个隐藏的input来告诉服务器端是PUT或者DELETE。

2. 相应的在我们的控制器中有对应的四个方法,分别匹配四种请求方式:

@Controller
@RequestMapping("rest")
public class RestController {
    @RequestMapping(value="resource/{id}",method=RequestMethod.GET)
    public String get(@PathVariable("id") Integer id){
        System.out.println("GET "+id);
        return "success";
    }

    @RequestMapping(value="resource/{id}",method=RequestMethod.POST)
    public String post(@PathVariable("id") Integer id){
        System.out.println("POST "+id);
        return "success";
    }

    @RequestMapping(value="resource/{id}",method=RequestMethod.PUT)
    public String put(@PathVariable("id") Integer id){
        System.out.println("PUT "+id);
        return "success";
    }

    @RequestMapping(value="resource/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        System.out.println("DELETE "+id);
        return "success";
    }
}


注:这里的PUT和DELETE不是POST是因为在SpringMVC的配置中做了一个转换。

3. 这个POST到PUT和DELETE的转换的配置,需要我们在SpringMvc的web.xml文件中根目录下增加如下配置:

<filter>
	<filter-name>hiddenHttpMethodFilter</filter-name>
	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>hiddenHttpMethodFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

注:配置hiddenHttpMethodFilter类中有一个方法doFilterInternal。在请求是的操作是POST,并且取name是“_method”的参数不为空的情况下会将“_method”参数的值创建为当前请求的操作。那么我们上面的“_method”是PUT或DELETE,在访问action时就变成了PUT或者DELETE。

这样在SpringMVC下实现了RESTFul风格架构,那么自己实践CRUD也就不难了。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注