Springmvc--requestmapping

Source: Internet
Author: User

One, @RequestMapping mapping requests

Spring MVC uses @requestmapping annotations to define different processor mapping rules.

    • @RequestMapping placed on top of the class name, set the request prefix
    • Set Request Map URL above method name

Mapping request parameters, request methods, or request headers

@RequestMapping can use request methods, request parameters, and request header mapping requests in addition to request URL mapping requests

1, @RequestMapping the value, method, params and heads respectively represents the request URL, request methods, request parameters and the mapping condition of the request header, they are the relationship between them, using multiple conditions together to make the request mapping more accurate.

/**      * Common: Use the Method property to specify the     request method *    /= "/testmethod", method = requestmethod.post)      Public String TestMethod () {        System.out.println ("TestMethod");         return SUCCESS;    }

2. Params and headers support simple expressions:

    • PARAM1: Indicates that the request must contain a request parameter named param1
    • !PARAM1: Indicates that the request cannot contain a request parameter named param1
    • Param1! = value1: Indicates that the request contains a request parameter named param1, but its value cannot be value1
    • {"Param1=value1", "param2"}: The request must contain two request parameters named Param1 and param2, and the value of the param1 parameter must be value1
/**     
* The request must contain the username request parameter, the value of the age request parameter cannot be equal to 10
*/="Testparamsandheaders", params = {"Username" ,"age!=10"}, headers = {" accept-language=en-us,zh;q=0.8 " }) public String testparamsandheaders () { System.out.println ("testparamsandheaders"); return SUCCESS; }
Third, @PathVariable placeholder for map URL bindings
    • The URL with placeholders is a new feature of Spring3.0, a milestone in the development of SPRINGMVC to REST goals
    • By @PathVariable You can bind a placeholder parameter in a URL to an entry in the Controller processing method: the {XXX} placeholder in the URL can be bound to the entry of an action method by @PathVariable ("xxx").
    /**      * @PathVariable can map placeholders in URLs to parameters in the target method.      @param ID      @return     */     @RequestMapping ("/testpathvariable/{id}")    public String Testpathvariable (@PathVariable ("id") Integer ID) {        System.out.println (ID);         return SUCCESS;    }    
Four, Hiddenhttpmethodfilter:

The browser form table only supports get and post requests, while the delete, put, and other methods are not supported, Spring3.0 adds a filter that can convert these requests to a standard HTTP method, enabling GET, POST, PUT, and DELE TE request.

How do I send a PUT request and a DELETE request?
1. Need to configure Hiddenhttpmethodfilter

<!--configuration Org.springframework.web.filter.HiddenHttpMethodFilter: Can convert a POST request to a DELETE or POST request -    <Filter>        <Filter-name>Hiddenhttpmethodfilter</Filter-name>        <Filter-class>Org.springframework.web.filter.HiddenHttpMethodFilter</Filter-class>    </Filter>    <filter-mapping>        <Filter-name>Hiddenhttpmethodfilter</Filter-name>        <Url-pattern>/*</Url-pattern>    </filter-mapping>
////Source code recreated from a. class file by IntelliJ idea//(Powered by Fernflower Decompiler)// PackageOrg.springframework.web.filter;Importjava.io.IOException;ImportJava.util.Locale;ImportJavax.servlet.FilterChain;Importjavax.servlet.ServletException;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletRequestWrapper;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.util.Assert;Importorg.springframework.util.StringUtils;ImportOrg.springframework.web.filter.OncePerRequestFilter; Public classHiddenhttpmethodfilterextendsOnceperrequestfilter { Public Static FinalString Default_method_param = "_method"; PrivateString Methodparam = "_method";  PublicHiddenhttpmethodfilter () {} Public voidSetmethodparam (String methodparam) {assert.hastext (Methodparam,"\ ' methodparam\ ' must not being empty");  This. Methodparam =Methodparam; }    protected voidDofilterinternal (HttpServletRequest request, httpservletresponse response, Filterchain Filterchain)throwsservletexception, IOException {String paramvalue= Request.getparameter ( This. Methodparam); if("POST". Equals (Request.getmethod ()) &&stringutils.haslength (paramvalue)) {String method=paramvalue.touppercase (locale.english); Hiddenhttpmethodfilter.httpmethodrequestwrapper wrapper=NewHiddenhttpmethodfilter.httpmethodrequestwrapper (Request, method);        Filterchain.dofilter (wrapper, response); } Else{filterchain.dofilter (request, response); }    }    Private Static classHttpmethodrequestwrapperextendsHttpservletrequestwrapper {Private FinalString method;  PublicHttpmethodrequestwrapper (HttpServletRequest request, String method) {Super(Request);  This. method =method; }         PublicString GetMethod () {return  This. method; }    }}

2. Need to carry a hidden field name= "_method" when sending a POST request with a value of DELETE or PUT

    <formAction= "SPRINGMVC/TESTREST/1"Method= "POST">        <inputtype= "hidden"name= "_method"value= "PUT"/>        <inputtype= "Submit"value= "Testrest PUT"/>    </form>        <formAction= "SPRINGMVC/TESTREST/1"Method= "POST">        <inputtype= "hidden"name= "_method"value= "DELETE"/>        <inputtype= "Submit"value= "Testrest DELETE"/>    </form>        <formAction= "Springmvc/testrest"Method= "POST">        <inputtype= "Submit"value= "Testrest POST"/>    </form>        <ahref= "SPRINGMVC/TESTREST/1">Test Rest Get</a>

[Email protected] Add method property

@RequestMapping (value = "/testrest/{id}", method =requestmethod.put) PublicString testrestput (@PathVariable Integer id) {SYSTEM.OUT.PRINTLN ("Testrest Put:" +ID); returnSUCCESS; } @RequestMapping (Value= "/testrest/{id}", method =requestmethod.delete) PublicString testrestdelete (@PathVariable Integer id) {SYSTEM.OUT.PRINTLN ("Testrest Delete:" +ID); returnSUCCESS; } @RequestMapping (Value= "/testrest", method =requestmethod.post) PublicString testrest () {System.out.println ("Testrest POST"); returnSUCCESS; } @RequestMapping (Value= "/testrest/{id}", method =requestmethod.get) PublicString testrest (@PathVariable Integer id) {SYSTEM.OUT.PRINTLN ("Testrest GET:" +ID); returnSUCCESS; }

Springmvc--requestmapping

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.