SpringMVC method屬性與http請求方法一致


在springMVC中,@requestMapping注解有method屬性,在沒有指定method的值時,默認映射所有http請求方法,如果僅想接收一種請求方法,需用method=RequestMethod.GET

或其他 請求方法指定,如果提交表單時form標簽中method的請求方法與requestMapping中指定的不同,則會報錯。如:

表單如下:

  1. <form id="frLogin" name="frLogin" method="post"  action="./loginmvc/login">  
  2.     <table>  
  3.     <tr>  
  4.     <td>姓名</td>  
  5.     <td><input type="text" name="txtName" id="txtName"/></td>  
  6.     </tr>  
  7.      <tr>  
  8.     <td>姓名</td>  
  9.     <td><input type="password" name="pwd" id="pwd"/></td>  
  10.     </tr>  
  11.      <tr>  
  12.     <td align="right"><input type="submit" value="登錄"/></td>  
  13.     <td><input type="reset" value="重填"/></td>  
  14.     </tr>  
  15.     </table>  
  16.   </form>  
springmvc requestMapping 注解如下:

  1.   
  1. @RequestMapping(value="/login",method=RequestMethod.GET)  
  2.     public String login(HttpServletRequest request,HttpServletResponse response){  
  3.         String strName=request.getParameter("txtName");  
  4.         String strPassword=request.getParameter("pwd");  
  5.         String sResult="loginError";  
  6.           
  7.         if(StringUtils.isBlank(strName)&&StringUtils.isBlank(strPassword)){  
  8.             sResult="loginOK";  
  9.         }  


 
          
瀏覽器報錯為:

HTTP Status 405 - Request method 'POST' not supported


type Status report

message Request method 'POST' not supported

description The specified HTTP method is not allowed for the requested resource.


查network,請求體說明:


因此在建立映射時,應當注意http請求方法與requestMapping注解一致,或者在注解中不再指定method,而是默認通過枚舉自動映射所有http請求方法

  1. public enum RequestMethod {  
  2.   
  3.     GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE  
  4.   
  5. }  
  1. RequestMethod[] method() default {};  





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM