天天看點

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

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

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

表單如下:

<b>[html]</b> view plain copy

print?

&lt;form id="frLogin" name="frLogin" method="post"  action="./loginmvc/login"&gt;  

    &lt;table&gt;  

    &lt;tr&gt;  

    &lt;td&gt;姓名&lt;/td&gt;  

    &lt;td&gt;&lt;input type="text" name="txtName" id="txtName"/&gt;&lt;/td&gt;  

    &lt;/tr&gt;  

     &lt;tr&gt;  

    &lt;td&gt;&lt;input type="password" name="pwd" id="pwd"/&gt;&lt;/td&gt;  

    &lt;td align="right"&gt;&lt;input type="submit" value="登入"/&gt;&lt;/td&gt;  

    &lt;td&gt;&lt;input type="reset" value="重填"/&gt;&lt;/td&gt;  

    &lt;/table&gt;  

  &lt;/form&gt;  

springmvc requestMapping 注解如下:

<b>[java]</b> view plain copy

@RequestMapping(value="/login",method=RequestMethod.GET)  

    public String login(HttpServletRequest request,HttpServletResponse response){  

        String strName=request.getParameter("txtName");  

        String strPassword=request.getParameter("pwd");  

        String sResult="loginError";  

        if(StringUtils.isBlank(strName)&amp;&amp;StringUtils.isBlank(strPassword)){  

            sResult="loginOK";  

        }  

浏覽器報錯為:

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,請求體說明:

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

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

public enum RequestMethod {  

    GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE  

}  

}

RequestMethod[] method() default {};