简体   繁体   English

Spring MVC - HTTP 状态 405 - 不支持请求方法“POST”

[英]Spring MVC - HTTP Status 405 - Request method 'POST' not supported

I've read all the questions related with this problem but no solution worked for me...我已阅读与此问题相关的所有问题,但没有解决方案对我有用...

I have a simple upload form.我有一个简单的上传表单。 The controller, i't a controller i've used a lot of times (never for a file upload though).控制器,我不是我使用过很多次的控制器(但从来没有用于文件上传)。

@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";

    }

}

Then I have the upload form, cleaned form all the css part:然后我有上传表单,清理表单所有的 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>

I don't know if it's useful, but this is UploadedFile.java, really simple不知道有没有用,不过这个是UploadedFile.java,真的很简单

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

public class UploadedFile{

    MultipartFile file;


    public MultipartFile getFile() {
        return file;
    }

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

}

The form in HTML has: HTML 中的表单具有:

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

Where is the problem?问题出在哪儿? I cannot even understand at which point che POST request goes wrong...我什至无法理解 che POST 请求在哪一点出错......

I'm adding the debug: Spring debug says:我正在添加调试:Spring debug 说:

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

Browser network logs don't say anything, just that the POST resource is not accomplished浏览器网络日志什么都没说,就是POST资源没有完成

Thanks谢谢

Things to Consider:需要考虑的事项:

Check your request header and see if it's submitting to floors/upload .检查您的请求标头,看看它是否提交到floors/upload if not try to add action="floors/upload" property in your form tag.如果不尝试在表单标签中添加 action="floors/upload" 属性。

Try to change your controller to (without the path )尝试将您的控制器更改为(没有path

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

I found the problem.我发现了问题。 Following this link I saw that multipart file upload with spring and CSRF must be handled with care.在此链接之后,我看到必须小心处理使用 spring 和 CSRF 的多部分文件上传。

So I first disabled the CSRF to see if everything went well.所以我首先禁用了CSRF,看看是否一切顺利。 After it, I added之后,我补充说

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

to my SecurityWebApplicationInitializer.java so to not need the authentication to upload file on the server, but only to move them to their final destination.到我的 SecurityWebApplicationInitializer.java 以便不需要身份验证来上传服务器上的文件,而只是将它们移动到它们的最终目的地。

Than I had to configure the filterMultipartResolver and everything went good.比我必须配置 filterMultipartResolver 并且一切顺利。

Thank you all谢谢你们

Look into spring's PathVariables.查看 spring 的 PathVariables。

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

IntelliJ suggested I use <form:form , which uses gave IntelliJ 建议我使用<form:form ,它使用了给

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

at the top of my .html file.在我的 .html 文件的顶部。 I changed to just <form in my body and then my POST request worked.我更改为<form在我的身体中,然后我的 POST 请求起作用了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HTTP状态405-Spring MVC不支持请求方法&#39;POST&#39; - HTTP Status 405 - Request method 'POST' not supported Spring MVC HTTP 状态 405 - 不支持请求方法“POST”(Spring MVC) - HTTP Status 405 - Request method 'POST' not supported (Spring MVC) Spring MVC HTTP状态405-不支持请求方法“ POST” - Spring MVC HTTP Status 405 - Request method 'POST' not supported 具有Spring Security的Spring-mvc获得HTTP状态405-请求方法&#39;POST&#39;不支持 - Spring-mvc with spring security getting HTTP Status 405 - Request method 'POST' not supported HTTP状态405 - 使用Spring Security的Spring MVC中不支持请求方法'POST' - HTTP Status 405 - Request method 'POST' not supported in Spring MVC with Spring Security Spring MVC 上传文件 - HTTP 状态 405 - 不支持请求方法“POST” - Spring MVC upload file - HTTP Status 405 - Request method 'POST' not supported Spring MVC 请求方法“POST”不支持-&gt; HTTP 405 - Spring MVC Request method 'POST' not supported -> HTTP 405 HTTP状态405-在Spring MVC中执行返回“重定向:*。*”时,不支持请求方法“ GET” - HTTP Status 405 - Request method 'GET' not supported when doing return “redirect:*.*” in spring mvc Spring MVC:HTTP 405-发出POST请求时不支持请求方法“ GET” - Spring MVC: HTTP 405 - Request method 'GET' not supported when making POST request HTTP状态405-请求方法&#39;POST&#39;不支持Spring Security Java Config - HTTP Status 405 - Request method 'POST' not supported Spring Security Java Config
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM