Rest风格的URL
Rest风格的URL
以CRUD为例
新增:/order/ POST
修改:/order/1 PUT 非Rest风格的URL为 update?id=1
获取:/order/1 GET 非Rest风格的URL为 get?id=1
删除:/order/1 DELETE 非Rest风格的URL为 delete?id=1
如何发送PUT请求和DELETE请求:
1、需要配置HiddenHttpMethodFilter
2、需要发送POST请求
3、需要在发送POST请求时带一个name="_method"的隐藏域,值为DELETE或PUT
在springMVC的目标方法中得到id:
使用@PathVariable
代码示例
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
public static String SUCCESS = "success";
/**
* Rest风格的URL
* 以CRUD为例
* 新增:/order/ POST
* 修改:/order/1 PUT 非Rest风格的URL为 update?id=1
* 获取:/order/1 GET 非Rest风格的URL为 get?id=1
* 删除:/order/1 DELETE 非Rest风格的URL为 delete?id=1
*
* 如何发送PUT请求和DELETE请求:
* 1、需要配置HiddenHttpMethodFilter
* 2、需要发送POST请求
* 3、需要在发送POST请求时带一个name="_method"的隐藏域,值为DELETE或PUT
*
* 在springMVC的目标方法中得到id:
* 使用@PathVariable
*
*/
@ResponseBody
@RequestMapping(value="/restPutTest/{id}",method=RequestMethod.PUT)
public String restPutTest(@PathVariable("id") Integer id){
System.out.println("restPutTest:"+id);
return SUCCESS;
}
@ResponseBody
@RequestMapping(value="/restDeleteTest/{id}",method=RequestMethod.DELETE)
public String restDeleteTest(@PathVariable("id") Integer id){
System.out.println("restDeleteTest:"+id);
return SUCCESS;
}
@RequestMapping(value="/restPostTest",method=RequestMethod.POST)
public String restPostTest(){
System.out.println("restTestPost");
return SUCCESS;
}
@RequestMapping(value="/restGetTest/{id}",method=RequestMethod.GET)
public String restGetTest(@PathVariable Integer id){
System.out.println("restTest GET:"+id);
return SUCCESS;
}
}
Jsp代码
<form action="springmvc/restPutTest/1" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="restTest PUT">
</form>
<form action="springmvc/restDeleteTest/1" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="restTest DELETE">
</form>
<form action="springmvc/restPostTest" method="POST">
<input type="submit" value="restTest POST">
</form>
<a href="springmvc/restGetTest/1">restTest Get</a>