Summary of Spring MVC common annotations

Source: Internet
Author: User
Tags class definition html form wrapper

1. @RequestMapping
@RequestMapping
Requestmapping is an annotation that handles the request address mapping (mapping the request to the corresponding controller method) and can be used on a class or method. On a class, the method that represents all response requests in a class is the parent path of the address.
Requestmapping Request Path Mapping, if labeled at the class level of a controller, indicates that access to the method under such a path is accompanied by the path of its configuration, most commonly labeled on the method, indicating which specific method is used to accept processing of a request.

@Controller
@RequestMapping (value= "/book") public class Bookcontroller {    @RequestMapping (value= "/title") public    String GetTitle () {        return ' title ';    }                   @RequestMapping (value= "/content") public    String getcontent () {        return "content";    

Because the Bookcontroller class adds @requestmapping annotations to the value= "/book", the associated paths are added "/book", which is the URL of the request:
(1) Http://localhost:8080/book/title
(2) Http://localhost:8080/book/content
The value of the @RequestMapping "/" has no effect on the requested path, that is, value= "book", "/book", "/book/" have the same effect.

Properties of the Requestmapping
Value: Specifies the actual URL of the request
(1) Normal specific value. As in the previous value= "/book".
(2) A class of values containing a variable.

@RequestMapping (value= "/get/{bookid}") public string Getbookbyid (@PathVariable string Bookid,model Model) {    Model.addattribute ("BookId", bookId);    

The BookID in the path can be used as a variable, and the value of the variable in the path is extracted @PathVariable annotation.
(3) Ant style
@RequestMapping (value= "/get/id?") : Can match "/get/id1" or "/get/ida", but does not match "/get/id" or "/GET/IDAA";
@RequestMapping (value= "/get/id*"): Can Match "/get/idabc" or "/get/id", but does not match "/GET/IDABC/ABC";
@RequestMapping (value= "/get/id/*"): Can Match "/GET/ID/ABC", but does not match "/GET/IDABC";
@RequestMapping (value= "/get/id/**/{id}"): Can Match "/get/id/abc/abc/123" or "/get/id/123", that is, ant style and Uri template variant style can be mixed.
(4) A class of values with regular expressions
@RequestMapping (value= "/get/{idpre:\\d+}-{idnum:\\d+}"): Can Match "/get/123-1", but cannot match "/get/abc-1", so you can design stricter rules.
Variable (idpre,idnum) in the path can be extracted by @pathvariable annotations
(5) or relationship
@RequestMapping (value={"/get", "/fetch"}) that is/get or/fetch are mapped to the method.

Method: Specifies the type of method requested, GET, POST, PUT, delete, and so on;
@RequestMapping (value= "/get/{bookid}", method={requestmethod.get,requestmethod.post})

Params: Specifies that some parameter values must be included in the request before the method is processed.
@RequestMapping (params= "Action=del"), the request parameter contains "Action=del", such as: Http://localhost:8080/book?action=del

@Controller
@RequestMapping ("/owners/{ownerid}") public class Relativepathuritemplatecontroller {  @RequestMapping (value = "/ Pets/{petid} ", method = Requestmethod.get, params=" Myparam=myvalue ") public  void Findpet (@PathVariable String ownerID, @PathVariable String Petid, model model) {        //implementation omitted  }}

A request with a value of "myvalue" named "Myparam" is included in the processing request only.

Headers: Specifies that certain header values must be included in the request in order for the method to process requests.
@RequestMapping (value= "/header/id", headers = "Accept=application/json"): Indicates that the requested URL must be "/header/id and that the request header must have" Accept = Application/json "parameter to match.

@Controller
@RequestMapping ("/owners/{ownerid}") public class Relativepathuritemplatecontroller {@RequestMapping (value = "/pets") , method = Requestmethod.get, headers= "referer=http://www.ifeng.com/") public  void Findpet (@PathVariable String ownerID, @PathVariable String Petid, model model) {        //implementation omitted  }}

The header that handles request only contains requests that specify the "Refer" request header and the corresponding value " http://www.ifeng.com/ ".

Consumes: Specifies the commit content type (Content-type) that handles the request, such as Application/json, text/html.

@Controller @requestmapping (value = "/pets", method = Requestmethod.post, consumes= "Application/json") public void Addpet (@RequestBody Pet Pet, model model) {        //implementation omitted}

The Content-type method only processes requests with the request "Application/json" type.
produces: Specifies the type of content returned, only if the specified type is included in the (Accept) type in the request header.

@Controller @requestmapping (value = "/pets/{petid}", method = Requestmethod.get, produces= "Application/json") @ Responsebodypublic Pet Getpet (@PathVariable String Petid, model model) {        //implementation omitted}

The Application/json method only handles requests in the request that accept headers contain "a", and implies that the returned content type is Application/json;

2. @RequestParam bind order Request parameter value
@RequestParam is used to map the request parameter area data to the parameters of a functional processing method.

public string requestparam1 (@RequestParam string username)

The request contains a username parameter (such as/requestparam1?username=zhang), which is automatically passed in.

@RequestParam has the following three parameters:
Value: The parameter name, that is, the parameter name of the request parameter, such as username indicates the parameter area of the request name is username The value of the argument will be passed in;
Required: Whether it is necessary, the default is true, indicates that the request must have corresponding parameters, otherwise the exception will be thrown;
DefaultValue: The default value, which indicates that the required is set to false automatically if there is no default value for the parameter with the same name in the request.

public string Requestparam4 (@RequestParam (value= "username", Required=false) string username)

Indicates that there can be no parameter with the name username in the request, and if there is no default of NULL, here are a few points to note:
Atomic type: Must have a value, otherwise throws an exception, and if null values are allowed, use the wrapper class instead.
Boolean wrapper type: Default Boolean.false, other reference types default to NULL.

If there are multiple requests with the same name, how should they be received? When authorizing a user, multiple permissions may be granted, first look at the following code:

public string Requestparam7 (@RequestParam (value= "role") string rolelist)

If the request parameter is similar to Url?role=admin&rule=user, then the actual rolelist parameter data is "Admin,user", that is, the use of "," split between multiple data; We should use the following method to receive multiple request parameters:

Public String requestparam7 (@RequestParam (value= "role") string[] rolelist)

Or

Public String REQUESTPARAM8 (@RequestParam (value= "list") list<string> list)  

3. @PathVariable binding URI Template variable value
@PathVariable is used to map template variables in the request URL to the parameters of a functional processing method.

@RequestMapping (value= "/users/{userid}/topics/{topicid}") Public String test (       @PathVariable (value= "UserId") int userId,        @PathVariable (value= "topicid") int topicid)   

If the requested URL is "controller url/users/123/topics/456", the template variable {userId} and {topicid} in the URL are automatically bound to the parameter with the same name through the @pathvariable annotation, that is, after the parameter is entered userid=123, topicid=456.

4. @ModelAttribute

Modelattribute can be applied to method parameters or methods, his role is mainly when the annotation on the method parameters will be added to the parameter object of the annotated model, when the annotation on the request processing method action, the method will be turned into a non-request processing method, However, the method is called first when the other action is called.

4.1 @ModelAttribute Comment a method

The method that is annotated by @modelattribute means that the purpose of this method is to add one or more model properties. This method supports the @requestparam parameter as well as the @requestmapping annotation method, but it cannot be mapped directly by request. In fact, the @modelattribute method in the controller is called before the @requestmapping method in the same controller is called.

The @modelattribute annotated method is used to populate the Model property, for example, to populate the contents of a drop-down menu, or to retrieve a command object, such as account, which is used to represent the data in an HTML form.
A controller can have any number of @modelattribute methods. All of these methods are called before the @requestmapping method is called.
There are two types of @modelattribute methods. One is to include only one attribute, which is implicitly represented by the return type of the method. The other is that the method accepts a parameter of model type, which can be added to any number of model properties.

(1) @ModelAttribute comment void return value method

@Controller @requestmapping (value= "/test") public class TestController {        /**     * [email protected] Comment void return value method      * @param ABC     * @param model     *    /@ModelAttribute public    void Populatemodel (@RequestParam String ABC , model model) {        Model.addattribute ("AttributeName", ABC);    }        @RequestMapping (value = "/helloworld") public    String HelloWorld () {       return "Test/helloworld";    }}

In this example, after obtaining the request/helloworld, the Populatemodel method is called before the HelloWorld method, which puts the request parameter (/helloworld?abc= Text) is added to a model property named AttributeName, and HelloWorld is called after it executes, returning the view name HelloWorld and model have been produced by the @modelattribute method.
In this example, the model property name and the Model Property object are implemented by Model.addattribute (), but only if a parameter of model type is added to the method.

(2) How to return a specific class @ModelAttribute comment

/** * [email protected] Comment Returns the method of the specific class * @param ID * @return */@ModelAttributepublic User GetUserInfo (String ID) {    if (id!=nu ll &&!id.equals ("")) {        return userservice.getuserinfo (ID);    }    return null;}

In this case, the name of the model property is not specified, it is implicitly represented by the return type, and if this method returns the user type, the name of the model property is user.
In this example, the Model property name has an implied representation of the return object type, and the Model Property object is the return value of the method. It does not need to have a specific parameter.

(3) @ModelAttribute (value= "") Comment returns the method of the specific class

@Controller @requestmapping (value= "/test") public class TestController {        /**     * [email protected] (value= "") Note The method that returns a specific class      * @param ABC     * @return *    /@ModelAttribute ("str") public    String GetParam (@ Requestparam String param) {        return param;    }        @RequestMapping (value = "/helloworld") public    String HelloWorld () {       return "Test/helloworld";    }}

In this example, the Value property of the @modelattribute annotation is used to specify the name of the model property. The Model Property object is the return value of the method. It does not need to have a specific parameter.

The complete code:

Package Demo.controller;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.ui.model;import Org.springframework.web.bind.annotation.modelattribute;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestparam;import Demo.model.user;import demo.service.IUserService;@ Controller@requestmapping (value= "/test") public class TestController {@Autowired private iuserservice Userservic        E  /** * [email protected] Comment void return value method * @param ABC * @param model */@ModelAttribute public void    Populatemodel (@RequestParam String ABC, model model) {Model.addattribute ("AttributeName", ABC); }/** * [email protected] Comment Returns the method of the specific class * @param ID * @return */@ModelAttribute public use R GetUserInfo (String ID) {if (Id!=null &&!id.equals ("")) {return userservice.gEtuserinfo (ID);    } return null; }/** * [email protected] (value= "") Comment returns the method of the specific class * @param ABC * @return */@ModelAttribute ("s    TR ") public string GetParam (@RequestParam string param) {return param;    } @RequestMapping (value = "/helloworld") public String HelloWorld () {return "Test/helloworld"; }}

JSP Foreground value:

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Page:

URL format: http://localhost/SSMDemo/test/helloWorld?abc=text&id=1&param=aaa Note: When the URL or post does not contain the parameter ABC and the parameter param, Will error.

(4) @ModelAttribute and @RequestMapping simultaneously annotate a method

@Controller @requestmapping (value= "/test") public class TestController {    @RequestMapping (value = "/helloworld")    @ModelAttribute ("AttributeName") public    String HelloWorld () {       return "HI";    }}

At this point the return value of this method does not represent a view name, but rather the value of the Model property, and the view name is converted from Requesttoviewnametranslator to HelloWorld according to the request "/helloworld". The model property name is specified by @modelattribute (value= ""), which is equivalent to encapsulating the Key=attributename,value=hi in the request.

JSP page:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

4.2 @ModelAttribute Note the parameters of a method

A parameter representation of the @ModelAttribute annotation method should be obtained from the model. If it is not found in the model, then this parameter will be instantiated and added to the model first. If found in model, the request parameter name and the model attribute field are automatically populated if matched. This mechanism is useful for binding form submission data to object properties.

When @modelattribute annotations are used for method parameters, it has the dual function of "save/Fetch". First, it extracts the data from the model and assigns the corresponding parameters, if it is not already present in the model, instantiates one and stores it in the model, and second, once the data object already exists in the model, the next important step is to bind the request parameter to this object (request Parameter Name Mapping object property name). This is a very handy mechanism provided by spring MVC-data binding.

@RequestMapping (value = "/login.htm", method = requestmethod.get) public String dologin (@ModelAttribute ("Basemember") Basemember member) {    member.setloginname ("LoginName");    Return "Home";}

In the preceding code, if data with the key name "Basemember" does not already exist in the model, the default constructor of the Basemember class is called first to create an object and throws an exception if no default constructor exists. Therefore, it is a good programming habit to provide a default constructor for the entity class. When the request parameter of the request path or the submitted form matches the Basemember property name, its value is automatically bound to the Basemember object, which is very convenient! This is probably one of the most important reasons we use @modelattribute. For example: The request path is Http://localhost:8080/spring-web/login.htm?loginName=myLoginName, The value of the LoginName property in the Basemember object is set to Myloginname.

4.3 Usage Scenarios for @ModelAttribute annotations
When the @modelattribute annotation is used in a method, this method is executed once for all the request methods that are in the same processing class, which may not be what we want, so we use more of it to apply it to the parameters of the request method. Some of its functions are consistent with @requestparam annotations, except that @requestparam is used to bind the order parameter values, and @modelattribute annotations can be bound to match all names, and it automatically adds the bound data to the model. It also gives us convenience, which may be the reason it is named Modelattribute.

5, Sessionattributes

By default, the attribute scope in Modelmap is the request level, that is, when the request ends, the properties in Modelmap are destroyed. If you want to share attributes in Modelmap in multiple requests, you must dump their properties into the session so that the Modelmap properties can be accessed across requests.
Spring allows us to selectively specify which attributes in the modelmap need to be dumped into the session so that the next request belongs to the corresponding Modelmap property list, which also has access to those properties. This function is implemented by annotating @SessionAttributes annotations at the class definition.

Package Demo.controller;import Org.springframework.stereotype.controller;import Org.springframework.ui.ModelMap; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.sessionattributes;import Demo.model.User; @Controller @requestmapping ( Value= "/demo1")//(1) Place the attribute named Curruser in Modelmap in the Session property list so that this property can access @sessionattributes ("Curruser") public across requests Class Demo1controller {@RequestMapping (value= "/getuser") public String GetUser (Modelmap model) {User use        R=new User ();        User.setuser_name ("Zhangsan");        User.setuser_age (25);        User.setuser_email ("[email protected]");        (2) Add an attribute Model.addattribute ("Curruser", user) to the Modelmap;    return "/demo/user"; } @RequestMapping (value= "/getuser1") public String GetUser1 (Modelmap model) {User user= (user) Model.get ("C        Urruser ");        System.out.println (User.getuser_name ());        System.out.println (User.getuser_age ()); SysteM.out.println (User.getuser_email ());    return "Demo/user1"; }}

We add a Modelmap property at (2) with the property named Curruser, and (1) place the attribute named Curruser in Modelmap in the Session by @SessionAttributes annotation, so we can not only The JSP view page for the TUser () request takes the user object through Request.getattribute ("Curruser") and Session.getattribute ("Curruser"), and can also be in the next request ( GetUser1 ()) is accessed through Session.getattribute ("Curruser") or Session.getattribute ("Curruser") in the JSP view page corresponding to this property.

Here we only put a Modelmap attribute in the Session, in fact @SessionAttributes allow multiple properties to be specified. You can specify multiple properties, such as @SessionAttributes ({"Attr1", "ATTR2"}) by means of a string array. In addition, @SessionAttributes can also specify the Modelmap property to be session by the property type, such as @SessionAttributes (types = user.class), or you can specify multiple classes, such as @ Sessionattributes (types = {User.class,dept.class}) can also be specified jointly using the property name and property type: @SessionAttributes (types = {User.class, dept.class},value={"Attr1", "ATTR2"}).

user.jsp page:

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%><%@ page import= "Demo.model.User"%> <%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Binding via @modelattribute

@SessionAttributes is used to share the model property within the controller. we can add a @SessionAttributes to the controller that needs to access the Session property, and then add @ModelAttribute on the User parameter that the action requires, and ensure that the property names are the same. SPRINGMVC will automatically inject @SessionAttributes-defined attributes into the Modelmap object, and in the Setup Action's argument list, go to Modelmap to get such objects and add them to the parameter list. As long as we do not call Sessionstatus's SetComplete () method, this object will remain in the session, thus realizing the sharing of session information.

@Controller  @SessionAttributes ("CurrentUser") Public  class greetingcontroller{       @RequestMapping      public void Hello (@ModelAttribute ("CurrentUser") user user) {       //user.sayhello ()       }   }  

@SessionAttributes Clear
@SessionAttributes need to clear, use Sessionstatus.setcomplete (); Note that it clears only the @sessionattributes session and does not erase the httpsession data. Therefore, such as the user authentication object's session generally does not use it to implement, or uses session.setattribute and so on traditional way realizes.

6. @Responsebody and @requestbody

The

@Responsebody indicates that the return result of the method is written directly to the HTTP response body. Generally used when retrieving data asynchronously, after using @requestmapping, the return value is usually resolved to the jump path, plus @responsebody returns the result will not be resolved to the jump path, but directly to the HTTP response body. For example, asynchronously fetching JSON data, plus @responsebody, will return the JSON data directly. The
@RequestBody inserts the HTTP request body into the method, using the appropriate httpmessageconverter to write the request body to an object.

 $ ("#btn2"). Click (function () {var url= ' <%=request.getcontextpath ()%>/user/adduserinfo '; var data={"user_name": $ ("#userName"). Val (), "User_sex": $ ("#userSex"). Val (), "User_age": $ ("#userAge"). Val (), "User_ Email ": $ (" #userEmail "). Val ()," User_telephone ": $ (" #userTelephone "). Val ()," User_education ": $ (" #userEducation ").        Val (), "User_title": $ ("#userTitle"). Val ()}; $.ajax ({type: ' POST ', ContentType: ' Application/json ', Url:url, DataType: "JSON", Data:json. Stringify (data), Async:false, success:function (data) {alert ("added success!)            ");           }, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {alert (xmlhttprequest.status);           alert (xmlhttprequest.readystate);      alert (textstatus); }    })})
@RequestMapping (value= "/adduserinfo", Method=requestmethod.post) @ResponseBody//writes data from the request to the Usermodel object in public String adduserinfo (@RequestBody usermodel user) {    System.out.println ("User_name--------" +user.getuser_name ());    System.out.println ("User_sex--------" +user.getuser_sex ());    System.out.println ("User_age--------" +user.getuser_age ());    System.out.println ("User_email--------" +user.getuser_email ());    System.out.println ("User_title--------" +user.getuser_title ());    System.out.println ("User_education--------" +user.getuser_education ());    System.out.println ("User_telephone--------" +user.getuser_telephone ());    Will not be resolved to a jump path, but rather write directly to the HTTP response body in    return "{}";}

@RequestBody convert the HTTP request body to the appropriate Httpmessageconverter object.
The @ResponseBody returns the content or object as the HTTP response body, and calls the adapter transform object that is appropriate for Httpmessageconverter to write to the output stream.

@RequestBody
Role:
i) This annotation is used to read the body portion of the request requests, parse using the httpmessageconverter of the system default configuration, and then bind the corresponding data to the object to be returned;
II) Then bind the object data returned by Httpmessageconverter to the parameters of the method in the controller.
Use time:
A) GET, post method, according to the request header Content-type value to determine:
application/x-www-form-urlencoded, Optional (that is, not necessary, because the data of this situation @requestparam, @ModelAttribute can also be processed, of course @requestbody can also handle);
Multipart/form-data, cannot be processed (i.e. using @requestbody cannot process data in this format);
Other formats must be (other formats include Application/json, Application/xml, etc.). Data in these formats must be handled using @requestbody);

B) When put is submitted, it is judged according to the value of the request header Content-type:
Application/x-www-form-urlencoded, must;
Multipart/form-data, unable to deal with;
Other formats, must;
Description: The data encoding format of the body part of request is specified by the Content-type of the header section;

@ResponseBody
Role:
The annotation is used to write the object returned by the controller's method to the body data area of the response object after the appropriate httpmessageconverter is converted to the specified format.
Use time:
The returned data is not a page of HTML tags, but is used in some other form of data (JSON, XML, etc.);

Summary of Spring MVC common annotations

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.