SpringMVC中REST介绍以及如何实现REST请求
1、Springmvc提供了一个filter,可以把delete请求和put请求转化成post请求。
在web.xml中配置过滤器:org.springframework.web.filter.HiddenHttpMethodFilter:
<!-- 可以把POST请求转为为DELETE或者POST请求 -->
<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>
2、发送一个get请求:
<h2>
<a href="springmvc/helloworld/1">Test Rest GET</a>
</h2>
3、发送一个post请求:
<form action="springmvc/helloworld/1" method="post">
<input type="submit" value="Test REST POST"/>
</form>
4、发送一个put请求,发送put请求的时候,我们需求添加一个隐藏域。
<form action="springmvc/helloworld/1" method="post">
<input type="hidden" name="_method" value="PUT" />
<input type="submit" value="Test REST PUT"/>
</form>
5、发送一个DELETE请求,发送DELETE请求的时候,我们需求添加一个隐藏域。
<input type="hidden" name="_method" value="DELETE" />
<form action="springmvc/helloworld/1" method="post">
<input type="hidden" name="_method" value="DELETE" />
<input type="submit" value="Test REST DELETE"/>
</form>
6、springmvc控制层的代码如下如下:
package com.gwolf.springmvc.handlers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/springmvc")
public class HelloWorldController {
@RequestMapping(value="/helloworld/{id}",method=RequestMethod.GET)
public String hello(@PathVariable Integer id) {
System.out.println("test rest get:" + id);
return "success";
}
@RequestMapping(value="/helloworld",method=RequestMethod.POST)
public String hello() {
System.out.println("test POST:" );
return "success";
}
@RequestMapping(value="/helloworld/{id}",method=RequestMethod.DELETE)
public String helloDelete(@PathVariable Integer id) {
System.out.println("test rest delete:" + id);
return "success";
}
@RequestMapping(value="/helloworld/{id}",method=RequestMethod.PUT)
public String helloPUt(@PathVariable Integer id) {
System.out.println("test rest put:" + id);
return "success";
}
}
7、运行tomcat,查看各个请求是否正确相应: