直接上干货:
我们知道在我们之前的Spring 中若 想要开启我们的REST风格,使用表单PUT和DELETE请求,我们就必须配置过滤,很是麻烦。
但是我们在SpringBoot中如果想要开启,只需要在我们yaml或者properties配置文件中开启:
spring:
mvc:
hiddenmethod:
filter:
enabled: true
即可开启我们SpringBoot请求
紧接着我们在我们的表单中需要添加一个隐藏域来表示我们的请求方式,其中name必须为_method,(我们也可以后期修改)而value即为我们想要的操作
修改name的默认值

我们默认在SpringBoot中是不开启的,因为我们通常在开发中只有用到表单的时候才会需要开启。因为表单中是没有POST和DELETE请求。所以就需要开启。
例如:
(代码实现)
前端代码:
<form action="/user" method="get">
<input value="REST-GET 提交" type="submit">
</form>
<form action="/user" method="post">
<input value="REST-POST 提交" type="submit">
</form>
<form action="/user" method="post">
<input name="_method" type="hidden" value="delete">
<input value="REST-DELETE 提交" type="submit">
</form>
<form action="/user" method="post">method必须为POST,才可以被SpringBoot识别
<input name="_method" value="put" type="hidden">
<input value="REST-PUT 提交" type="submit">
</form>
后端:
@RestController
public class helloController {
@RequestMapping("scenery.jpg")
public String test01(){
return "tupian";
}
@GetMapping("/user")
//我们可以使用注解XXXMapping(“value”)来代替我们的@RequestMapping(value= “XX”,method = RequestMethod.XXX)
public String test02(){
return "GET_ebdbbd";
}
@PostMapping("/user")
public String test03(){
return "POST_ebdbbd";
}
@RequestMapping(value = "/user",method = RequestMethod.DELETE)
public String test04(){
return "DELETE_ebdbbd";
}
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String test05(){
return "PUT_ebdbbd";
}
}
yml配置文件:
spring:
mvc:
hiddenmethod:
filter:
enabled: true
而在开发中,我们通常是与我们前端进行分离的,前端给我们一个接口,我们只需要给前端返回一个JSON数据即可。
REST原理的实现:

本文介绍了在SpringBoot中如何简单快捷地启用RESTful风格的PUT和DELETE请求,只需在配置文件中开启一项设置,并在表单中添加隐藏字段指定请求类型。通过示例代码展示了前后端交互的实现方式,使得在不使用过滤器的情况下也能处理PUT和DELETE操作。
273

被折叠的 条评论
为什么被折叠?



