Spring4MVC Annotations [continuous update] And spring4mvc annotations

Source: Internet
Author: User

Spring4MVC Annotations [continuous update] And spring4mvc annotations

Notes frequently used by spring mvc:

.

@ Controller

@ Controller registers a bean to the spring context. The bean ID is

 

The class name starts with lowercase letters. You can also specify the name as follows:

Method 1:

@ Controller

Public class TestController {}

 

Method 2:

@ Controller ("tmpController ")

Public class TestController {}

 

@ RequestMapping

 

1. @ RequestMapping is used to define the access URL. You can define

 

@ RequestMapping, or specify one for each method.

Put @ RequestMapping at the class level, which can make it

 

@ RequestMapping: Annotations work collaboratively to narrow down the selection scope.

For example:

@ RequestMapping ("/test ")

Public class TestController {}

Then, 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, all methods

 

The access path configuration of is completely independent and has no association.

 

3. Complete parameter items: @ RequestMapping (value = "", method =

 

{"", ""}, Headers = {}, params = {"", ""}). The parameters are described as follows:

Value: String [] set the access address

Method: RequestMethod [] sets the access method and character array to view RequestMethod

 

Class, including GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, common

 

RequestMethod. GET, RequestMethod. POST

Headers: String [] headers are generally used in combination with method = RequestMethod. POST.

Params: String [] Access parameter settings, character array for example: userId = id

 

4. The value configuration can also be in the form of template variables, for example: @ RequestMapping

 

(Value = "/owners/{ownerId}", method = RequestMethod. GET ).

 

Detailed description in Shao @ PathVariable.

 

5. @ RequestMapping params supplementary instructions. You can set parameter conditions to limit

 

Access address, for example, params = "myParam = myValue" expression. The access address has only

 

Only the specified value "myParam = myValue" can be matched, such as "myParam ".

 

The expression is also supported, indicating that the current request address must have this parameter (the parameter value can be

 

Arbitrary ),"! 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 as *. do, *. html, and so on

 

In method-level @ RequestMapping, no value can 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 getList () method, while

 

If you ask/bbs. do/spList, an error is returned.

 

@ PathVariable

1. @ PathVariable is used for parameters in the method, indicating that the method parameters are bound to the URL template.

 

Variable.

For example:

Java code

@ RequestMapping (value = "/owners/{ownerId }",

 

Method = RequestMethod. GET)

Public String findOwner (@ PathVariable String ownerId, Model

 

Model ){

Owner owner = ownerService. findOwner (ownerId );

Model. addattriner ("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 method returns an error.

 

 

@ ModelAttribute

1. Applied to method parameters. parameters can be obtained directly on the page, which is equivalent

 

Request. setAttribute (,)

2. Apply the method to add @ ModelAttribute to any method with the returned value, so that

 

The returned value is displayed in the attribute list of the model object.

3. @ ModelAttribute ("xx") must be associated with the Data Type of the Object when the method parameter is applied.

 

, Basic data types such as int and String do not work

For example:

Java code

@ ModelAttribute ("items") // <-- ① add an item named items to the model object

 

Attribute

Public List <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 ();

// <-- ② The items attribute in this access model

System. out. println ("model. items:" + (List <String>)

 

Model. get ("items"). size ());

Return "listBoard ";

}

 

At ①, The populateItem () method will

 

Any request processing method called before execution, Spring MVC will return the value of this method with "items

 

In the hidden model object attribute list.

So in section ②, we can access the items attributes through ModelMap.

 

When the listAllBoard () line request processing method is used, ② is printed on the console

 

Output "model. items: 2. Of course, we can also access the model in the request view.

 

The items attribute in the object.

 

 

@ ResponseBody

This annotation can be directly put on the method, indicating that the return type will be directly used as the HTTP Response byte

 

Stream output (neither placed in the Model nor blocked as the view page name ). It can be used for ajax.

 

@ RequestParam

@ RequestParam is an optional parameter, for example, @ RequestParam ("id") annotation, so

 

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 ),

 

Must have corresponding parameters, otherwise it will throw

 

Org. springframework. web. util. NestedServletException exception.

 

Convert null to the basic data type.

 

@ RequestParam contains three configurations @ RequestParam (required =, value = "",

 

DefaultValue = "")

Required: required or not. boolean type. Optional. The default value is true.

Value: the name of the passed parameter. It is of the String type and optional. If there is a value, it corresponds to the setting party.

 

Parameters

DefaultValue: String type. It is the default value specified when the parameter is not passed.

 

@ SessionAttributes session management

Spring allows us to selectively specify which attributes in ModelMap need to be transferred

 

Session so that the next request can be accessed in the ModelMap attribute list

 

To these attributes. This function is marked by @ SessionAttributes annotation in the class definition.

 

. @ SessionAttributes can only be declared on the class, but not on the method.

 

For example

 

@ SessionAttributes ("currUser") // set the attribute named currUser in ModelMap

 

 

@ SessionAttributes ({"attr1", "attr2 "})

@ SessionAttributes (types = User. class)

@ SessionAttributes (types = {User. class, Dept. class })

@ SessionAttributes (types = {User. class, Dept. class}, value = {"attr1", "attr2 "})

 

 

@ CookieValue obtain cookie Information

@ RequestHeader: obtains the 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.