Title

HTTP Status 405 - Request method 'GET' not supported?(尚硅谷Restful案例练习关于Delete方法出现的错误)

哈罗大家好,最近在如火如荼的学习java开发----Spring系列框架,当学习到SpringMVC,动手实践RESTFUL案例时,发现了以上报错405,get请求方法没有被支持。

  1. 首先第一步,我查看自己写的示例代码有无写错。在反复对比了尚硅谷发出来的示例代码后,发现并无错误;
  2. 然后我就根据错误在百度中畅游了不知多少春夏秋冬,然后并没有用,且部分解决办法并不适用我的问题情况。
  3. 由于浏览器只支持get和post,即使在form表单中设置method为put或delete,最后它们还是被当成get处理。
    为了发送put请求和delete请求,Spring提供HiddenHttpMethodFilter。
  4. 如何使用HiddenHttpMethodFilter来发送put和delete请求?需要做到以下两点:

    1. 当前的请求方式必须为post。
    2. 当前请求必须传输参数_mothod,参数值为put或delete。

     (以上第四点为什么必须是这样可以看源码,源码部分如下:)

 1 public class HiddenHttpMethodFilter extends OncePerRequestFilter {
 2     private static final List<String> ALLOWED_METHODS;
 3     public static final String DEFAULT_METHOD_PARAM = "_method";
 4     private String methodParam = "_method";
 5 
 6     public HiddenHttpMethodFilter() {
 7     }
 8 
 9     public void setMethodParam(String methodParam) {
10         Assert.hasText(methodParam, "'methodParam' must not be empty");
11         this.methodParam = methodParam;
12     }
13 
14     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
15         HttpServletRequest requestToUse = request;
16         if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
17             String paramValue = request.getParameter(this.methodParam);
18             if (StringUtils.hasLength(paramValue)) {
19                 String method = paramValue.toUpperCase(Locale.ENGLISH);
20                 if (ALLOWED_METHODS.contains(method)) {
21                     requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
22                 }
23             }
24         }
25 
26         filterChain.doFilter((ServletRequest)requestToUse, response);
27     }
28 
29     static {
30         ALLOWED_METHODS = Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
31     }
32 
33     private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
34         private final String method;
35 
36         public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
37             super(request);
38             this.method = method;
39         }
40 
41         public String getMethod() {
42             return this.method;
43         }
44     }
45 }

  

  

  文章如有不足之处,请留言评论或私信,希望我踩过的坑,满头泥泞,能帮助你们少踩坑,帮助到你java的学习!

 

posted @ 2022-07-06 10:30  赖金明的大爹  阅读(440)  评论(0编辑  收藏  举报