RESTful风格 将请求信息与状态关联
- /order/1 HTTP GET :得到id = 1 的 order
- /order/1 HTTP DELETE: 删除 id=1 的order
- /order/1 HTTP PUT : 更新id = 1的 order
- /order/1 HTTP POST : 新增 order
通过修改http的状态值来标记请求的目的
Spring中实现RESTful风格
HiddenHttpMethodFilter:浏览器form表单只支持GET和POST,不支持DELETE和PUT请求,
Spring添加了一个过滤器,可以将这些请求转换为标准的http方法,支持GET,POST,DELETE,PUT请求!
web.xml添加HiddenHttpMethodFilter配置
HiddenHttpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter HiddenHttpMethodFilter /*需要注意: 由于doFilterInternal方法只对method为post的表单进行过滤,所以在页面中必须如下设置:
<form action="..." method="post">
<input type="hidden" name="_method" value="put" />
</form>
代表post请求,但是HiddenHttpMethodFilter将把本次请求转化成标准的put请求方式! name="_method"固定写法!
<html>
<body>
<h2>Hello World!</h2>
<script type="text/javascript">
function a(){
//设置表单的action值
document.forms[0].action="test";
// document.getElementById("txt").value("post");
document.forms[0].submit();
}
function b() {
//设置表单的action值
document.forms[0].action = "test/1";
document.getElementById("txt").value="put";
document.forms[0].submit();
}
function c(){
//设置表单的action值
document.forms[0].action="test/1";
document.getElementById("txt").value="delete";
document.forms[0].submit();
}
function d(){
//设置表单的action值
location.href="test/1";
// document.forms[0].action="test/1";
// document.getElementById("txt").value("get");
// document.forms[0].submit;
}
</script>
<span onclick="a()">insert</span><br> <%--test--%>
<span onclick="b()">update</span><br> <%--test/1--%>
<span onclick="c()">delete</span>
<span onclick="d()">select</span>
<form method="post">
<input type="hidden" id= "txt" name="_method" value="POST"/>
</form>
</body>
</html>
Test
@Controller
public class TestRestful {
@RequestMapping(value = "test", method = RequestMethod.POST)
public String test1(){
System.out.println("insert --");
return "insert";
}
@RequestMapping( value = "test/{id}", method = RequestMethod.PUT)
public String test2(@PathVariable("id") int uid ){
System.out.println("update --");
return "update";
}
@RequestMapping(value = "test/{id}", method = RequestMethod.DELETE)
public String test3(@PathVariable("id") int uid ){
System.out.println("delete --");
return "delete";
}
@RequestMapping(value = "test/{id}",method = RequestMethod.GET)
public String test4(@PathVariable("id") int uid ){
System.out.println("select");
return "select";
}
}