SpringBoot2---对rest风格的支持,阿里技术专家深入讲解

本文介绍了SpringBoot2中对REST风格的支持,包括GET、POST、PUT、DELETE等操作的实现。通过WebMvcAutoConfiguration核心配置类分析,解释了如何开启隐藏HTTP方法过滤器以支持RESTful URL。同时,文章讨论了REST原理,当表单提交时如何处理_method参数,并提供了解决方案。此外,还提到了使用PostMan等客户端工具直接发送PUT、DELETE请求的情况。
摘要由CSDN通过智能技术生成

@RequestMapping(value = “/user”,method = RequestMethod.GET)

public String getUser(){

return “GET-张三”;

}

@RequestMapping(value = “/user”,method = RequestMethod.POST)

public String saveUser(){

return “POST-张三”;

}

@RequestMapping(value = “/user”,method = RequestMethod.PUT)

public String putUser(){

return “PUT-张三”;

}

@RequestMapping(value = “/user”,method = RequestMethod.DELETE)

public String deleteUser(){

return “DELETE-张三”;


源码分析

===================================================================

WebMvcAutoConfiguration的springmvc的核心配置类中,默认关闭了hiddenHttpMethodFilter,即默认不支持Rest风格的URL

@Bean

@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)

@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.fil

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

ter", name = “enabled”, matchIfMissing = false)

public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {

return new OrderedHiddenHttpMethodFilter();

}


在springboot的主配置文件中开启对rest风格的URL的支持


spring:

mvc:

hiddenmethod:

filter:

enabled: true #开启页面表单的Rest功能


原理


Rest原理(表单提交要使用REST的时候)

表单提交会带上_method=PUT

请求过来被HiddenHttpMethodFilter拦截

请求是否正常,并且是POST

获取到_method的值。

兼容以下请求;PUT.DELETE.PATCH

原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。

过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。

源码如下:

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

HttpServletRequest requestToUse = request;

if (“POST”.equals(request.getMethod()) && request.getAttribute(“javax.servlet.error.exception”) == null) {

String paramValue = request.getParameter(this.methodParam);

if (StringUtils.hasLength(paramValue)) {

String method = paramValue.toUpperCase(Locale.ENGLISH);

if (ALLOWED_METHODS.contains(method)) {

requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);

}

}

}

filterChain.doFilter((ServletRequest)requestToUse, response);

}


Rest使用客户端工具,如PostMan直接发送Put、delete等方式请求,无需Filter。



如何默认表单中_method 这个名字换成我们自己喜欢的,即自定义filter


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值