Spring MVC learning 2: annotation Introduction

Source: Internet
Author: User

There are many annotations for spring. Today we will introduce the following commonly used annotations for spring mvc. @ Controller registers a bean to the spring context. The bean ID starts with a class name in lowercase by default. You can also specify it by yourself. method 1 is as follows: @ Controller public class TestController {} Method 2: @ Controller ("tmpController") public class TestController {} @ RequestMapping 1. @ RequestMapping is used to define the access URL. You can define a @ RequestMapping for the entire class or specify a @ RequestMapping for each method. Put @ RequestMapping at the class level, which allows it to work with the @ RequestMapping annotation at the method level to narrow the selection scope. For example: @ RequestMapping ("/test") public class TestController {}, all access paths under this class are under/test. 2. It is not necessary to use @ RequestMapping for the entire class. If no configuration is available, the access path configuration for all methods will be completely independent without any association. 3. the complete parameter items are: @ RequestMapping (value = "", method = {"", ""}, headers = {}, params = {"",""}), parameters are described as follows: value: String [] sets the access address method: RequestMethod [] sets the access method, character array, and views the RequestMethod class, including GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, commonly used RequestMethod. GET, RequestMethod. POST headers: String [] headers are generally combined with method = RequestMethod. POST uses params: String [] to access parameter settings. The character array is: userId = id 4. value can also be configured in the form of template variables, for example: @ RequestMapping (value = "/ow Ners/{ownerId} ", method = RequestMethod. GET). This will be detailed in @ PathVariable. 5. @ RequestMapping supplementary description of params. You can set parameter conditions to restrict the access address, for example, params = "myParam = myValue" expression, only the specified value "myParam = myValue" can be matched in the access address parameter. expressions like "myParam" are also supported, indicates that the current request address must have this parameter (the parameter value can be any ),"! Expressions such as myParam indicate that the current request address cannot contain the specified parameter "myParam ". 6. note that if the access address for the class is defined *. do ,*. for example, in method-level @ RequestMapping, the value cannot be defined. Otherwise, an error is reported, for example, Java code @ RequestMapping ("/bbs. do ") public class BbsController {@ RequestMapping (params =" method = getList ") public String getList () {return" list ";}@ RequestMapping (value ="/spList ") public String getSpecialList () {return "splist" ;}} For example:/bbs. do? Method = getList can access the method getList (), and access/bbs. do/spList will report an error. @ PathVariable 1. @ PathVariable is used for parameters in the method, indicating the template variable bound to the URL of the method parameter. Example: Java code @ RequestMapping (value = "/owners/{ownerId}", method = RequestMethod. GET) public String findOwner (@ PathVariable String ownerId, Model model) {Owner owner = ownerService. findOwner (ownerId); model. addAttribute ("owner", owner); return "displayOwner";} 2. @ PathVariable is used when {xxx} template variables are used in the address bar. If @ RequestMapping does not define a variable similar to "/{ownerId}", @ PathVariable in the method will report an error. @ ModelAttribute 1. it is applied to method parameters. parameters can be obtained directly on the page, which is equivalent to request. setAttribute (,) 2. apply to methods. Add @ ModelAttribute to any method with the returned value so that the returned value enters the attribute list of the model object. 3. when it is applied to method parameters @ ModelAttribute ("xx"), it must be associated with the Data Type of the Object. Basic data types such as int and String do not work. For example: java code @ ModelAttribute ("items") // <-- ① Add a public List named items to the model object <String> populateItems () {List <String> lists = new ArrayList <String> (); lists. add ("item1"); lists. add ("item2"); return lists;} @ RequestMapping (params = "method = listAllBoard") public String listAllBoard (@ ModelAttribute ("currUser") User user, ModelMap model) {bbtForumService. getAllBoard (); // <-- ② access the items attribute System in the model. out. println ("model. items: "+ (List <String>) model. get ("items ")). size (); return "listBoard";} At ①, The populateItem () method is called before any request processing method is executed by using the @ ModelAttribute annotation, spring MVC puts the return value of this method in the implicit model object attribute list in the name of "items. Therefore, in section ②, we can access the items attributes through ModelMap. When the listAllBoard () request processing method is executed, section ② prints the "model" on the console. items: 2. Of course, we can also access the items attribute in the model object in the request view. The @ ResponseBody annotation can be directly put on the method, indicating that the return type will be directly used as the HTTP Response byte stream output (not placed in the Model or blocked as the view page name ). It can be used for ajax. @ RequestParam is an optional parameter, for example, @ RequestParam ("id") annotation, therefore, it is bound to the parameter id of the URL. If the input parameter is of the basic data type (such as int, long, float), the URL request parameter must have a corresponding parameter, otherwise, org. springframework. web. util. nestedServletException exception, prompting that null cannot be converted to the basic data type. @ RequestParam contains three configurations @ RequestParam (required =, value = "", defaultValue = "") required: required or not, boolean Type, optional, default: true value: passed parameter name, String type, option. If there is a value, it corresponds to the defaultValue: String type parameter of the Setting method. The parameter is not passed @ SessionAttributes session management Spring, which is the default value for the parameter at the time of delivery, allows us to selectively specify which attributes in ModelMap need to be transferred to the session, so that the attribute list of ModelMap corresponding to the next request can also access these attributes. This function is implemented by annotation @ SessionAttributes in the class definition. @ SessionAttributes can only be declared on the class, but not on the method. For example, @ SessionAttributes ("currUser") // set the attribute name in ModelMap to currUser @ SessionAttributes ({"attr1", "attr2"}) @ SessionAttributes (types = User. class) @ SessionAttributes (types = {User. class, Dept. class}) @ SessionAttributes (types = {User. class, Dept. class}, value = {"attr1", "attr2"}) @ CookieValue get cookie Information @ RequestHeader GET request header information

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.