spring mvc rest风格的CRUD
程序员文章站
2022-04-23 15:57:07
...
DELETE:删除 PUT:更新POST:新增 GET:查询
Rest风格的URL 如何发送PUT请求和DELETE请求?
1.需要在web.xml中配置HidenHttpMethodFilter
<!--配置 org.springframework.web.filter.HiddenHttpMethodFilter :可以把post转换为delete和put请求 -->
<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.需要发送POST请求,需要在发送POST请求时携带一个name=“_method”的隐藏域,值为DELETE或者PUT
<!-- get请求 -->
<a href="testRest/122">test Rest get</a>
<!-- DELETE请求 -->
<form action="testRest/1" method="post">
<input type="hidden" value="DELETE" name="_method"> <input
type="submit" value="Test Rest DELETE">
</form>
<!-- post请求 -->
<form action="testRest" method="post">
<input type="submit" value="Test Rest post">
</form>
<!-- PUT请求 -->
<form action="testRest/1" method="post">
<input type="hidden" value="PUT" name="_method"> <input
type="submit" value="Test Rest put">
</form>
通过相同的路径名springmvc/testRest 调用不同方法。
//在springMVC中如何获取id呢? 使用@PathVariable注解
@RequestMapping(value = "/testRest", method = RequestMethod.POST)
public String testRest() {
System.out.println("test Rest post");
return "success";
}
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
public String testRestDelete(@PathVariable("id") Integer id) {
System.out.println("test Rest delete" + id);
return "success";
}
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
public String testRest(@PathVariable("id") Integer id) {
System.out.println("test Rest GET" + id);
return "success";
}
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
public String testRestPut(@PathVariable("id") Integer id) {
System.out.println("test Rest GET" + id);
return "success";
}
推荐阅读
-
你知道@RequestMapping的name属性有什么用吗?【享学Spring MVC】
-
关于Spring MVC在Controller层中注入request的坑详解
-
干货分享:ASP.NET CORE(C#)与Spring Boot MVC(JAVA)异曲同工的编程方式总结
-
基于Maven 的 Spring MVC
-
详解Spring mvc ant path的使用方法
-
Spring MVC的常用注解
-
Spring mvc 分步式session的实例详解
-
从原理层面掌握@SessionAttribute的使用【一起学Spring MVC】
-
Spring MVC 实现文件的上传和下载
-
从原理层面掌握@RequestAttribute、@SessionAttribute的使用【一起学Spring MVC】