Spring MVC Learning Note (ii): @RequestMapping usage

Source: Internet
Author: User
Tags http post representational state transfer

First, @RequestMapping Introduction

Use @RequestMapping in spring MVC to map a request, that is, to specify which URL requests the controller can handle, which is equivalent to configuring the servlet in Web. xml

<servlet> <servlet-name>servletName</servlet-name> <servlet-class>servletclass</    Servlet-class></servlet><servlet-mapping> <servlet-name>servletName</servlet-name> <url-pattern>url</url-pattern></servlet-mapping>

The mapping effect is consistent. Let's look at the source code for the Requestmapping annotation class first:

@Target ({elementtype.method, elementtype.type}) @Retention (retentionpolicy.runtime) @Documented @mappingpublic @ Interface Requestmapping {String name () default ""; String[] Value () default {}; String[] Path () default {}; Requestmethod[] Method () default {}; String[] Params () default {}; String[] Headers () default {}; String[] Consumes () default {}; String[] produces () default {};}

1) There are two properties in @target, elementtype.method and elementtype.type respectively, which means that @RequestMapping can be used in methods and class is used in the declaration of the

2) You can see the attributes in the annotation in addition to the string returned by name (), other methods return an array , that is, you can define multiple property values, such as value () and path () can define multiple string values simultaneously to receive multiple URL requests


ii. Preparatory work: (Note: The following examples will be based on the preparation work)

1) Create a new Web project, named Springmvc

Slightly

2) Create a new controller class: Usercontroller

Package Cn.kolbe.spring.mvc.controller;import Org.springframework.stereotype.Controller; @Controllerpublic class Usercontroller {public String login () {return ' success ';}}

3) New and configured Web. XML and Spring-mvc.xml files

(See the previous chapter:? ) Spring MVC Learning Note (i): HelloWorld ? )

4) Create a new JSP page for the test index.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE html>

5) Create a new page for a successful jump JSP page welcome.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE html>


Third, the test @RequestMapping the value and path property (these two properties are the same, can be interchanged, if only this one attribute, you can omit, the following two examples are omitted)

1) The @RequestMapping annotation on the login method, and the Usercontroller does not add @RequestMapping annotations, at this time the request URL is relative to the Web root directory

@Controllerpublic class Usercontroller {@RequestMapping ("/login") public String login () {return "Success";}}

The method login () can handle the URL request path is based on the Web application, that is, Http://localhost/SpringMVC/login, that is, the index.jsp page of the User login link address should be:

<a href= "Login" >user login</a>


2) @RequestMapping annotations on the Usercontroller class, and @RequestMapping annotations are not added on the Usercontroller, when the annotations of the class are relative to the Web root, and the method is relative to the path on the class

@Controller @requestmapping ("/user") public class Usercontroller {@RequestMapping ("/login") public String login () { Return "Success";}}

At this point the method login () can handle the URL request path is Http://localhost/SpringMVC/user/login, that is, the index.jsp page of the user login link address should be:

<a href= "User/login" >user login</a>


Iv. Method properties for test @RequestMapping

1) Introduction: The method in @RequestMapping is used primarily to define what kind of request the receiving browser sends. In spring, the enumeration class is used

Org.springframework.web.bind.annotation.RequestMethod to define how the browser requests.

HTTP specification defines a variety of ways to request resources, the most basic four kinds are: GET (check), POST (Increase), PUT (change), delete (delete), and the URL is used to locate the network of resources equivalent to the role of the address, with four request methods, Can be implemented to the URL corresponding to the resources of the deletion and modification operation.

In practice, many people do not follow this specification, because using Get/post can also complete the put and delete operations, even get can complete the post operation, because get does not need to use the form, and post needs to be sent through the form.

2) by @RequestMapping (value= "/login", Method=requestmethod.get) to specify that the login() method only handles requests sent through the GET method

@Controller @requestmapping (Path = "/user") public class Usercontroller {@RequestMapping (Path = "/login", method= requestmethod.get) Public String login () {return "Success";}}

At this point, if the browser sends a request that is not a get, you will get the error message returned by the browser , that is, through the way of linking instead of the form:

<a href= "User/login>user login</a>

3) by @RequestMapping (value= "/login", method=requestmethod.post) to specify that the login () method only handles requests sent by POST

@Controller @requestmapping (Path = "/user") public class Usercontroller {@RequestMapping (Path = "/login", method= requestmethod.post) Public String login () {return "Success";}}

At this point, the request must be sent through the form, or you will receive an error message returned by the browser

<form action= "User/login" method= "POST" > <input type= "Submit" value= "Send request using POST"/></form>

4) because the method () methods in the Requestmapping annotation class return a Requestmethod array, you can specify multiple request methods for the method at the same time, for example:

@Controller @requestmapping (Path = "/user") public class Usercontroller {//The method will also receive requests sent through get and post @requestmapping (Path = "/login", method={requestmethod.post,requestmethod.get}) public String login () {return "Success";}}


The Params property of the test @RequestMapping, which represents the request parameter, which is a key-value pair appended to the URL, with multiple request parameters separated by &, for example:

http://localhost/SpringMVC/user/login?username=kolbe&password=123456

The parameter for this request is Username=kolbe and password=123456, @RequestMapping can use the params to limit the request parameters to implement further filtering requests, for example:

@Controller @requestmapping (Path = "/user") public class Usercontroller {//The method will receive a request from/user/login, and the request parameter must be For username=kolbe&password=123456@requestmapping (Path = "/login", params={"Username=kolbe", "password=123456"}) Public String Login () {return "Success";}}

This example indicates that the login () method in Usercontroller only processes requests from/user/login and must have username=kolbe&password=123456 request parameters, otherwise the browser will return an HTTP 404 error, corresponding to the key address in the index.jsp:

<a href= "user/login?username=kolbe&password=123456" >user login</a>


The Headers property of the test @RequestMapping that represents the request header

The information used for the HTTP semantic interaction is called an HTTP message, and the HTTP message sent by the client is called the request packet, and the HTTP message sent back to the client by the server is called the response message, which is composed of the message header and the newspaper style.

Request Headers: The request header contains many information about the client environment and the request body, such as the language supported by the browser, the requested server address, the client's operating system, and so on.

Response Head (Rsponse Headers): The response header also contains a number of useful information, including server type, date, response content type and encoding, response content length, and so on.

If you are installing a Chrome browser, you can right-click on the mouse----> review elements---->network---->name in the Web page----> Right view headers, if the page does not appear in the name, You can refresh it, and below is a sample request header in My computer:

Request Headers accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding : gzip, deflate, SDCH accept-language:zh-cn,zh;q=0.8 cache-control:max-age=0 connection:keep-alive Cookie:JSESS ionid=210075b5e521cwe3cde938076295a57a host:localhost:8080 upgrade-insecure-requests:1 User-Agent:Mozilla/5.0 (Ma Cintosh; Intel Mac OS X 10_9_5) applewebkit/537.36 (khtml, like Gecko) chrome/45.0.2454.93

The Headers property in the @RequestMapping allows you to limit the requests sent by the client

@Controller @requestmapping (Path = "/user") public class Usercontroller {//indicates that only incoming requests from this machine are received @requestmapping (path = "/log In ", headers=" host=localhost:8080 ") public String login () {return" Success ";}}


vii. URLs with placeholders

(a) The URL with placeholders is a new feature of Spring 3.0, which can be enclosed in {} by @PathVariable the placeholders in the URL are bound to the parameters of the controller's processing method.

(b) How to use:

1) Examples of URLs with placeholders:

@Controller @requestmapping (Path = "/user") public class Usercontroller {@RequestMapping (value= "/{id}", Method=reque Stmethod.get) public String Show (@PathVariable ("id") Integer ID) {return ' success ';}}

In this controller the show () method will be able to receive path requests for USER/1, USER/2, USER/3, and so on, and the requested method must be get, using the @PathVariable provides a great convenience for the application to implement the REST specification.


Eight, the use of RESTful URL requests

1) Introduction: REST (Representational State Transfer): (Resource) Presentation layer status transformation, which is currently the most popular software architecture, its structure is clear, easy to understand, easy to expand and meet the standards, is increasingly being applied to the application.

2) REST-style URL request

Request Path Request method function-/user/1 HTTP GET get ID 1 user-/user/1 HTTP delete Delete ID 1 user-/user/ 1 HTTP PUT update ID 1 for user-/user http POST New user

3) Because the browser table only supports GET and POST requests, in order to implement the DELETE and PUT requests, Spring Provides us with a filter org.springframework.web.filter.HiddenHttpMethodFilter, which translates get and POST requests through filters into DELETE and PUT requests.

4) Configure the filter in Web. xml

<!--configuring Org.springframework.web.filter.HiddenHttpMethodFilter filters--><filter> <filter-name> Hiddenhttpmethodfilter</filter-name> <filter-class> Org.springframework.web.filter.hiddenhttpmethodfilter</filter-class></filter> <filter-mapping > <filter-name>hiddenHttpMethodFilter</filter-name> <!--intercept all requests-<url-pattern>/*< ;/url-pattern></filter-mapping>

5) Because browser forms cannot send delete and PUT requests, in order for Hiddenhttpmethodfilter to recognize the requested method, you need to add a hidden field in the form with the name _method value of delete or post or PUT, modified IND The ex.jsp page code is as follows:

<%@ page language= "java"  contenttype= "Text/html; charset=utf-8"  pageEncoding= " UTF-8 "%><! doctype html>

6) Modified Usercontroller code

package cn.kolbe.spring.mvc.controller;import org.springframework.stereotype.controller;import  org.springframework.web.bind.annotation.pathvariable;import  org.springframework.web.bind.annotation.requestmapping;import  Org.springframework.web.bind.annotation.RequestMethod, @Controller @requestmapping (path =  "/user") public class usercontroller {@RequestMapping (value= "/{id}",  method=requestmethod.get) Public string show (@PathVariable ("id")  integer id)  {system.out.println ("View ID:"   + id +  "user");return  "Success";} @RequestMapping (value= "/{id}",  method=requestmethod.put) public string update (@PathVariable ("id" )  integer id)  {system.out.println ("Update ID:"  + id +  "user");return  " Success ";} @RequestMapping (value= "/{id}",  method=requestmethod.delete) Public string destroy (@PathVariable ( "id")  integer id) &NBSP;{SYSTEM.OUT.PRintln ("Delete ID:"  + id +  "user");return  "Success";} @RequestMapping (value= "",  method=requestmethod.post) public string create ()  { SYSTEM.OUT.PRINTLN ("New user");return  "Success";}}


Note: If your Web project is running under Tomcat 8, you will find that it is filtered to delete and put requests, and when returned (forward) will be reported with an HTTP 405 error prompt when the controller is reached

HTTP status 405-request method ' DELETE ' is supported or HTTP status 405-jsps only permit GET POST or HEAD

There are three types of solutions:

(i) the Tomcat 8 is changed to Tomcat 7 and it is normal for Tomcat 7 to run

(ii) Change request forwarding (forward) to request redirection (redirect)

(iii) Manually write a filter to wrap the GetMethod () method in the HttpRequest





Spring MVC Learning Note (ii): @RequestMapping usage

Related Article

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.