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

时间:2015-12-22 17:05:31

标签: java spring spring-mvc

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

我有一个简单的上传表单。 控制器,我是一个控制器,我已经使用了很多次(但从来没有用于文件上传)。

@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,非常简单

import 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 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资源没有完成

由于

4 个答案:

答案 0 :(得分:1)

需要考虑的事项:

检查您的请求标头,看看它是否正在提交给floors/upload。如果没有尝试在表单标记中添加action =“floors / upload”属性。

尝试将控制器更改为(不包含path

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

答案 1 :(得分:0)

查看spring的PathVariables。

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

答案 2 :(得分:0)

我发现了问题。 在http://xdebug.org/download.php之后,我看到必须小心处理带有spring和CSRF的多部分文件上传。

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

'Macro to query Delinquency Status Search for DFB Counties 'Run Monday to pull data from Friday Sub queryActivityDailyMforF() Dim nextrow As Integer, i As Long Dim dates dates = Date - 1 Dim x, county1, county2, county3, county4, county5, county6, county7, county8, county9, county10, county11, county12 county1 = "county_1=16" county2 = "county_1=21" county3 = "county_1=23" county4 = "county_1=32" county5 = "county_1=36" county6 = "county_1=41" county7 = "county_1=46" county8 = "county_1=53" county9 = "county_1=54" county10 = "county_1=57" county11 = "county_1=60" county12 = "county_1=66" 'Dim myString 'myString = "No Activity Information Found" 'Dim lastRow As Long 'Dim county 'Dim site As String 'Dim rng As Range 'Dim firstCell As String 'lastRow = Sheets("sheet1").Range("A" & Rows.Count).End(xlUp).Row Application.ScreenUpdating = False Application.DisplayStatusBar = True 'If Not rng Is Nothing Then firstCell = rng.Address 'Do Until myString <> lastRow And InStr("&county_1=66", "St. Lucie") Do 'Do While i < 4 'For i = 1 To lastRow 'Set rng = Sheets("sheet2").Range("A:A").find(What:=Cells(i, 1), LookIn:=xlValues, lookAt:=xlPart, SearchOrder:=xlByRows) 'Do While lastRow <> myString Application.StatusBar = "Processing Page " & i nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1 'With ActiveSheet.QueryTables.Add(Connection:= _ ' "URL;https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & "&county_1=16&county_1=21&county_1=23&county_1=32&county_1=36&county_1=41&county_1=46&county_1=53&county_1=54&county_1=57&county_1=60&county_1=66&status=NS&send_date=" & dates & "&search_1.x=1", _ ' Destination:=Range("A" & nextrow)) With ActiveSheet.QueryTables.Add(Connection:= _ "URL;https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & county & x & "&status=NS&send_date=" & dates & "&search_1.x=1", _ Destination:=Range("A" & nextrow)) '.Name = _ "2015&search_1.x=40&search_1.y=11&date=on&county_1=AL&lic_num_del=&lic_num_rep=&status=NS&biz_name=&owner_name=" .FieldNames = False .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .WebSelectionType = xlSpecifiedTables .WebFormatting = xlWebFormattingNone .WebTables = "10" .WebPreFormattedTextToColumns = True .WebConsecutiveDelimitersAsOne = True .WebSingleBlockTextImport = False .WebDisableDateRecognition = False .WebDisableRedirections = False .Refresh BackgroundQuery:=False 'autofit columns Columns("A:G").Select Selection.EntireColumn.AutoFit 'check for filter, if not then turn on filter ActiveSheet.AutoFilterMode = False If Not ActiveSheet.AutoFilterMode Then ActiveSheet.Range("A:G").AutoFilter End If 'If Not rng Is Nothing Then ' If rng.Address = firstCell Then Exit Do ' End If 'site = "https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & "&county_1=16&county_1=21&county_1=23&county_1=32&county_1=36&county_1=41&county_1=46&county_1=53&county_1=54&county_1=57&county_1=60&county_1=66&status=NS&send_date=" & dates & "&search_1.x=1" 'county = "&coutny_1=66" End With 'Next i = i + 1 Loop Until x = 12 x = x + 1 'Loop Until InStr(site, county) And ActiveCell.Value = myString 'Wend Application.StatusBar = False 'Align text left Cells.Select With Selection .HorizontalAlignment = xlLeft .VerticalAlignment = xlBottom .WrapText = False .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With 'Next 'Loop End Sub

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

我必须配置filterMultipartResolver,一切都很顺利。

谢谢大家

答案 3 :(得分:0)

IntelliJ建议我使用<form:form,它使用了

<html xmlns:form="http://www.w3.org/1999/xhtml">
.p文件顶部的

。我的身体变成<form,然后我的POST请求起作用了。

相关问题