Spring MVC annotation in-depth study

Source: Internet
Author: User
Tags throw exception

@Controller @Service @Controller and @Component
Registering an action into the spring context, the Bean's ID defaults to the first letter of the class name lowercase.
@Repository, @Service and @controller. These 3 annotations and @Component are equivalent, but from the name of the annotation class it is easy to see that the 3 annotations correspond to the persistence layer, the business layer, and the control layer (the WEB layer), respectively. While these 3 annotations are not new to @Component, Spring will add special features to them in future releases. Therefore, if a WEB application uses a classic three-tier hierarchy, it is best to annotate the classes in the hierarchy using @repository, @Service, and @Controller, respectively, in the persistence layer, the business layer, and the control layer, using @Component Annotate classes that are more neutral.

Cases:

@Controllerpublic class Apple extends Friut {}

@Autowired
The class member variables, methods and constructors are labeled in Bytype to complete the automatic assembly work. Spring will use the Java reflection mechanism to automatically inject private member variables in the class. So when you use @Autowired for member variables, you can delete their getter and setter methods.
Cases:

public class Boss {@Autowired private car car; @Autowired Private Office office;}

You can also use the @ autowired annotation for the set method and the constructor, equivalent to the

public class Boss {private car car;   Private Office Office;   @Autowired public void Setcar (car car) {This.car = car;   } @Autowired public void Setoffice (office office) {this.office = office;   }}public class Boss {private car car;   Private Office Office;     @Autowired public Boss (car car, office office) {This.car = car;   This.office = Office; } }

How to use the required parameter of autowired

@Autowired (required = false) public void Setoffice (office office) {this.office = office;}

In general, the use of @Autowired place is the need to inject beans, using automatic injection and allow non-injection is generally only encountered during the development period or test period (such as to quickly start the spring container, only some of the module's spring configuration file), so @ Autowired (required = false) is seldom used.

@Resource
The function of the @Resource is equivalent to @Autowired, except that the @Autowired is automatically injected by Bytype, and the @Resource is automatically injected by ByName by default. @Resource There are two attributes that are more important, name and type,spring resolve the Name property of the @Resource annotation to the bean, while the type attribute resolves to the bean. So if you use the Name property, you use the ByName Auto-injection policy, and the Type property uses the Bytype auto-injection policy. If neither name nor the type attribute is specified, the ByName auto-injection policy is used through the reflection mechanism.
Cases:

public class Boss {//Automatically injects Bean of type car @Resource private car car; Automatic injection bean name is called Office bean @Resource (name = "Office") private office office; }

@PostConstruct and @PreDestroy
You only need to label the @PostConstruct or @PreDestroy before the method, which is executed by the Spring container after the Bean is initialized or destroyed, and is often used for handling static variables.

public class Boss {private static car car = Initcar ();   @Resource (name = "Office") private office office;   @PostConstruct public void Initcar () {System.out.println ("PostConstruct1");   } @PreDestroy public void PreDestroy1 () {System.out.println ("preDestroy1"); } }

@RequestMapping
Maps a URL to a class or method.

Request the method by http://{ip:port/context}/car/getname

When it is defined at the class level, it indicates that the controller handles all requests that are mapped to the/car path. The method property can be used in @RequestMapping to mark the type of methods it accepts, and if you do not specify a method type, you can use the HTTP Get/post method to request data, but once you specify the method type, you can only use that type to get the data. There are four types of support methods: GET, POST, PUT, DELETE

@RequestMapping (value= "/getname", method = requestmethod.get) public String getName (string userName) {return userName;}

Binding @RequestMapping Parameters
Use the @PathVariable annotation method parameter and bind it to the value of the URI template variable

@RequestMapping (value= "/departments/{departmentid}/employees/{employeeid}") Public String Findemployee (@ Pathvariable string DepartmentID, @PathVariable string employeeId) {System.out.println ("Find Employee W   ITH ID: "+ employeeId +" from Department: "+ DepartmentID); return "Someresult"; }

Support for regular expressions

@RequestMapping (value= "/{textualpart:[a-z-]+}.{  numericpart:[\\d]+} ") public string RegularExpression (@PathVariable string Textualpart, @PathVariable   String Numericpart) {System.out.println ("Textual part:" + Textualpart + ", numeric part:" + Numericpart); return "Someresult"; }

@RequestParam
Request parameters can be passed to the request method
Example: http://{ip:port/context}/car/getname?ownerid=5


@RequestMapping (value= "/getname") public String Mycarname (@RequestParam ("ownerid") int ownerid) {return "Audi"; }}

@ModelAttribute
There are three ways to use @ModelAttribute:
1. Annotation method
When it works on a method, the purpose of marking the method is to add one or more model attributes. This method supports the same parameter types as @requestmapping, but does not map directly to requests. The @modelattribute method in the controller is called before all @requestmapping method calls, so use it with care.

Using this feature for permission validation, the Prerun method is executed before the index method executes.

@Controller @requestmapping (value= "/test") public class Passportcontroller {@ModelAttribute public void Prerun () {if (    User! = "Admin") {throw Exception ("no permission");  }} @RequestMapping (method=requestmethod.get) public String index () {return ' Login/index '; } }

2. The entry in the annotation method
Used to bind multiple request parameters to a Command object, add this object to the request scope, simplify the binding process, and automatically expose the use of model data for JSP presentation

@RequestMapping (value= "test") public String Test (@ModelAttribute ("user") Usermodel user) {user.setname ("AAA");}

You can now use ${user.name} on the view page to get the properties of the bound Command object

3, the return value of the annotation method, the effect is the same, add the return value to the request scope, the JSP page can be called directly by ${user.name}, @ModelAttribute the return value of the annotation will overwrite @requestmapping The @modelattribute annotation in the annotation method has the same name as the Command object.

@RequestBody
Reads the body portion of the request requests, parses using the system's default configuration, httpmessageconverter the corresponding data to the object to be returned, and binds the object data returned by Httpmessageconverter to The parameters of the method in the controller.

@ResponseBody
Writes the controller's method to the body data area of the response object, after the object is converted to the specified format by the appropriate httpmessageconverter.

@ExceptionHandler and @controlleradvice
@ExceptionHandler annotation to a method, the method is executed when an exception occurs. @ControllerAdvice make a Contoller a global exception-handling class, the class uses the @exceptionhandler method annotation method to handle the exception that occurs with all controllers.

@RestController (Spring 3.1 or more)
Causes a class to return the request data in restful style, which differs from the @controller in that the category using the @controller callout eventually returns a string and then assembles the full view through Viewresolver The page path renders the view on the front-end page. Using a @RestController callout means that the category will eventually return a Pojo object instead of a page, so you don't need to use viewresolver to help assemble the callback value.
With the Jackson Suite, you can return the domain object Restcontroller back to the front end in JSON or XML format.

@RestControllerpublic class Helloworldrestcontroller {      @RequestMapping ("/hello/{player}") Public   Message Message (@PathVariable String player) {        message msg = new Message (player, "Hello," + player);     return msg;}   }

Vo Field Validation
@AssertFalse
Validated data type: Boolean,boolean
Description: Verify that the element value of the annotation is false


@AssertTrue
Validated data type: Boolean,boolean
Description: Verify that the element value of the annotation is true


@NotNull
Validated data type: any type
Description: Verify that the element value of the annotation is not null


@Null
Validated data type: any type
Description: Verify that the element value of the annotation is null


@Min (value= value)
Validated data types: Bigdecimal,biginteger, byte,short, int, long, and so on any number or charsequence (stored as a numeric) subtype
Description: Verify that the element value of the annotation is greater than or equal to the value specified by @min


@Max (value= value)
Validated data type: Same as @min requirements
Description: Verify that the element value of the annotation is less than or equal to the value specified by @max


@DecimalMin (value= value)
Validated data type: Same as @min requirements
Description: Verify that the element value of the annotation is greater than or equal to the value specified by @ decimalmin


@DecimalMax (value= value)
Validated data type: Same as @min requirements
Description: Verify that the element value of the annotation is less than or equal to the value specified by @ Decimalmax


@Digits (integer= integer digits, fraction= decimal place)
Validated data type: Same as @min requirements
Description: Verifies the maximum number of integers and decimal digits of element values for annotations


@Size (min= lower limit, max= upper limit)
Validated data types: string, Collection, Map, array, etc.
Description: Validates the element value of an annotation within a specified interval of min and max (inclusive), such as character length, collection size


@Past
Validated data type: Java.util.date,java.util.calendar,joda date type of the time class library
Description: Validates the element value of the annotation (date type) earlier than the current time


@Future
Validated data type: Same as @past requirements
Description: Validates the element value of the annotation (date type) later than the current time


@NotBlank
Validated data type: Charsequence subtype
Description: Verifies that the element value of the annotation is not null (NOT NULL, the first space is removed after the length is 0), differs from @notempty, that the @NotBlank is applied only to strings and that the first space of the string is stripped when compared


@Length (min= lower limit, max= upper limit)
Validated data type: Charsequence subtype
Description: Validates the element value length for annotations within min and Max intervals


@NotEmpty
Validated data types: Charsequence subtype, Collection, Map, array
Description: Validation of element values for annotations is not NULL and is not NULL (string length is not 0, collection size is not 0)


@Range (min= min, max= max)
Validated data types: Bigdecimal,biginteger,charsequence, Byte, short, int, long, etc. atomic type and packing type
Description: Validates the element value of the annotation between the minimum and maximum values


@Email (regexp= Regular expression, flag= flag pattern)
Validated data type: Charsequence subtype (string, for example)
Description: Verify the element value of the annotation is email, or you can specify a custom email format via REGEXP and flag


@Pattern (regexp= Regular expression, flag= flag pattern)
Validated data type: String, subtype of any charsequence
Description: Validates the element value of the annotation to match the specified regular expression


@Valid
Validated data type: Any non-atomic type
Description: Specifies a recursive validation of the associated object, such as an Address object property in a User object, if you want to validate the address object together when validating the user object, add @valid annotations on the Address object to cascade validation

Spring MVC annotation in-depth study

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.