2016-02-06 107 views
2

我正在學習Spring Boot,現在我寫了一個小應用程序。該應用程序有此控制器:Spring Boot - POST請求方法不起作用,但GET做了

@Controller 
@RequestMapping("/") 
public class ApplicationController { 

    @RequestMapping(value="/account", method = RequestMethod.POST) 
    public String getAccountVo(ModelMap model) { 
     AccountVO vo = new AccountVO(); 
     vo.setAccountNo("0102356"); 
     vo.setAccountHolderName("Dinesh"); 

     model.addAttribute("acc", vo); 

     return "account"; 
    } 
} 

...並在頁面(視圖)是:

<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Account Details</title> 
</head> 
<body> 
    <form> 
     Account number <input type="text" name="acctNo" value="${acc.getAccountNo()}"><br> 
     Account Holder Name <input type="text" name="name" value="${acc.getAccountHolderName()}"><br> 
    </form> 
</body> 
</html> 

當我運行應用程序,我得到了HTTP Status 405與消息Request method 'GET' not supported。但是當我將@RequestMapping註釋中的方法更改爲method=RequestMethod.GET時,我得到了預期的頁面。

爲什麼會發生這種情況?

回答

4
@RequestMapping(value="/account", method = RequestMethod.POST) 

這意味着getAccountVo方法處理程序負責對/account端點POST請求。因此,當您向/account端點發出GET請求時,由於您尚未定義任何方法處理程序來處理該問題,因此Spring會投訴405 Method Not Supported

如果你的目的是爲了有一個表格處理工作流程,典型的做法是在/account端點定義兩種方法處理:用於顯示處理提交的表單形式和其他一,有點兒像這樣:

@Controller 
@RequestMapping("/") 
public class ApplicationController { 

    @RequestMapping(value="/account", method = RequestMethod.GET) 
    public String displayAccountForm(...) { 
     // do whatever suits your requirements 

     return "account"; 
    } 

    @RequestMapping(value="/account", method = RequestMethod.POST) 
    public String handleSubmittedForm(...) { 
     // do whatever suits your requirements 

     return "successPage"; 
    } 
} 
相關問題