【问题标题】:Spring MVC - HTTP Status 405 - Request method 'POST' not supportedSpring MVC - HTTP 状态 405 - 不支持请求方法“POST”
【发布时间】:2016-03-29 00:30:06
【问题描述】:

我已阅读与此问题相关的所有问题,但没有适合我的解决方案...

我有一个简单的上传表单。 控制器,我不是我用过很多次的控制器(虽然从不用于文件上传)。

@Controller
public class FileUploadController {
    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value={"/upload"}, method=  RequestMethod.GET)
    public String getUploadForm() {

        return "/upload";

    }

    @RequestMapping(value={"/upload"}, method=RequestMethod.POST)
    public @ResponseBody String uploadedFile(@RequestParam("uploadedFile") UploadedFile uploadedFile, BindingResult result, ModelMap model,
                                RedirectAttributes redirectAttributes) {

        if (result.hasErrors()) {
            return "/upload";

        } 
            InputStream is = null;
            OutputStream os = null;
            MultipartFile file = uploadedFile.getFile();
            String fileName = file.getOriginalFilename();
            String imagepath = request.getSession().getServletContext().getRealPath("/resources/images");
            try {
                is = file.getInputStream();
                File newFile = new File(imagepath+"/"+fileName);

                if(!newFile.exists()){
                    newFile.createNewFile();
                }
                os = new FileOutputStream(newFile);
                int read=0;
                byte[] bytes = new byte[1024];
                while((read = is.read(bytes)) != -1){
                    os.write(bytes, 0, read);
                }
                redirectAttributes.addFlashAttribute("css", "success");
                redirectAttributes.addFlashAttribute("msg", "File "+fileName+ "aggiunto correttamente");
                model.addAttribute("fileName", fileName);


            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return "redirect:/floors";

    }

}

然后我有上传表单,清理表单所有 css 部分:

<form:form method="POST" enctype="multipart/form-data" modelAttribute="uploadedFile">

         <input type="hidden"
             name="${_csrf.parameterName}"
             value="${_csrf.token}" />
        <form:errors path="*" cssClass="alert alert-danger alert-dismissible"
            element="div" />


            <label class="control-label col-sm-2">Carica
                immagine</label>

                <input type="file" name="file">
                <form:errors path="file" class="control-label" />


        <button id="singlebutton" name="singlebutton"
                        class="btn btn-primary" type="submit">Carica</button>

        </div>
    </form:form>

不知道有没有用,不过这是UploadedFile.java,很简单

导入 org.springframework.web.multipart.MultipartFile;

public class UploadedFile{

    MultipartFile file;


    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

}

HTML 中的表单有:

<form id="uploadedFile" class="form-horizontal" action="/smartpark/upload" method="POST" enctype="multipart/form-data">

问题出在哪里?我什至无法理解 POST 请求在什么时候出错...

我正在添加调试:Spring 调试说:

2015-12-22 18:52:13 DEBUG FilterChainProxy:324 - /upload at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2015-12-22 18:52:13 DEBUG FilterChainProxy:324 - /upload at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2015-12-22 18:52:13 DEBUG HttpSessionSecurityContextRepository:192 - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@468e6d7e: Authentication: org.springframework.security.authentication.RememberMeAuthenticationToken@468e6d7e: Principal: org.springframework.security.core.userdetails.User@62dd304: Username: mario; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@7798: RemoteIpAddress: 192.168.3.38; SessionId: null; Granted Authorities: ROLE_ADMIN'
2015-12-22 18:52:13 DEBUG FilterChainProxy:324 - /upload at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2015-12-22 18:52:13 DEBUG HstsHeaderWriter:128 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@26ee04e5
2015-12-22 18:52:13 DEBUG FilterChainProxy:324 - /upload at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
2015-12-22 18:52:13 DEBUG CsrfFilter:106 - Invalid CSRF token found for http://192.168.3.240:8080/smartpark/upload
2015-12-22 18:52:13 DEBUG DispatcherServlet:861 - DispatcherServlet with name 'dispatcher' processing POST request for [/smartpark/Access_Denied]
2015-12-22 18:52:13 DEBUG RequestMappingHandlerMapping:306 - Looking up handler method for path /Access_Denied
2015-12-22 18:52:13 DEBUG ExceptionHandlerExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
2015-12-22 18:52:13 DEBUG ResponseStatusExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
2015-12-22 18:52:13 DEBUG DefaultHandlerExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
2015-12-22 18:52:13 WARN  PageNotFound:208 - Request method 'POST' not supported
2015-12-22 18:52:13 DEBUG DispatcherServlet:1034 - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling
2015-12-22 18:52:13 DEBUG DispatcherServlet:1000 - Successfully completed request
2015-12-22 18:52:13 DEBUG HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper:211 - Skip invoking on
2015-12-22 18:52:13 DEBUG SecurityContextPersistenceFilter:105 - SecurityContextHolder now cleared, as request processing completed

浏览器网络日志什么也没说,只是POST资源没有完成

谢谢

【问题讨论】:

  • 附注。你可以在你的类@Controller @RequestMapping("floors") public class上使用requestmapping注解...这样你就不必在每个方法上都有一个冗余常量
  • 打开调试日志,检查 Spring 注册为处理程序方法的内容。打开浏览器的网络日志并检查请求中发送的内容。发布所有这些。
  • 您的安全堆栈中的某些东西正在将请求转发到/smartpark/Access_Denied
  • mmmm...也许是因为DEBUG CsrfFilter:106 - Invalid CSRF token found 即使我用表格传递它...
  • 我建议使用指南从头开始重新编码:spring.io/guides/gs/uploading-files。可能比试图找出哪里出错更快。从超级简单的东西开始,然后在不破坏它的情况下扩展它。

标签: java spring spring-mvc


【解决方案1】:

IntelliJ 建议我使用 &lt;form:form,它使用给了

<html xmlns:form="http://www.w3.org/1999/xhtml">

在我的 .html 文件的顶部。我在正文中更改为 &lt;form,然后我的 POST 请求成功了。

【讨论】:

    【解决方案2】:

    我发现了问题。 在这个link之后,我看到使用spring和CSRF的分段文件上传必须小心处理。

    所以我首先禁用了 CSRF 以查看是否一切顺利。在它之后,我添加了

    @Override protected void beforeSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(servletContext, new MultipartFilter()); }

    到我的 SecurityWebApplicationInitializer.java 以便不需要身份验证在服务器上上传文件,而只需将它们移动到最终目的地。

    比我必须配置 filterMultipartResolver 并且一切顺利。

    谢谢大家

    【讨论】:

      【解决方案3】:

      查看 spring 的 PathVariables。

      @RequestMapping(value = " /upload/{pathName}", method=RequestMethod.POST)
      public String getOrder(@PathVariable String pathName){
       // do what you need
      }
      

      【讨论】:

        【解决方案4】:

        需要考虑的事项:

        检查您的请求标头,看看它是否提交到floors/upload。如果不尝试在表单标签中添加 action="floors/upload" 属性。

        尝试将您的控制器更改为(不带path

         @RequestMapping(value="upload", method=RequestMethod.POST)
        

        【讨论】:

        • 我使用了来自@shinjw 的建议,但我得到了同样的错误,表单的 HTML 转到 &lt;form id="uploadedFile" class="form-horizontal" action="/smartpark/floors/upload/" method="POST" enctype="multipart/form-data"&gt;so 它看起来它去了正确的位置...
        • 是的,我更新了问题以反映他的建议
        • 我已经做到了,谢谢。我将所有内容都放在根级别,现在它直接指向 /upload 的映射
        • 如果 (result.hasErrors()) 的行是什么?也许这会导致方法跳过上传的东西
        • 你的意思是这是问题所在?
        猜你喜欢
        • 2012-06-24
        • 2015-04-09
        • 2014-09-24
        • 2013-04-09
        • 2012-04-20
        • 2013-11-25
        • 2015-05-01
        • 2020-07-24
        • 2015-01-31
        相关资源
        最近更新 更多