@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