Common annotation classes for Spring MVC

Source: Internet
Author: User
Tags class definition rowcount

First, the annotation class configuration

To use the SPRINGMVC annotation class, you need to scan with context:component-scan/in the Springmvc.xml configuration file:

?

Two or five major annotation classes 1. requestmapping annotations How to use requestmapping annotation classes

@requestmapping annotations can be annotated at the class definition and method definition of a controller class
Dispatcherservlet intercepts the request, it is possible to determine the processing method for the request through the mapping information provided by the @requestmapping on the controller

 PackageNet.quickcodes.controller;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping, @Controller @requestmapping ("/Home")//class level, it is not required, and if so, all of the following request paths need to be preceded by " /Home" Public classIndexcontroller {//method level, must have, decide which request this method handles (processing/helloworld/home/index.html requests here)@RequestMapping (value = "/index")     PublicString HelloWorld () {return"Index";//"web-inf/page/index.jsp"    }    }

requestmapping properties of the annotation class

requestmapping annotation class properties, respectively, value, method, consumes, produces, params, headers
1>.value Property
• Represents a specific request path, such as "/home" above, "/index" is value
value can be omitted, as in the example, directly in the format of the @RequestMapping ("Home"), which is equivalent to @requestmapping (value = "/Home")

?

2>.method Property
• Specify the type of method requested, GET, POST, PUT, delete, and so on:
Example: @RequestMapping (value = "/login", Method = Requestmethod.post) Then this method will only be triggered if a POST request is sent
• The value can be either a string or an array:
Example: @RequestMapping (value = "/login", method = {requestmethod.post, requestmethod.get})

3>.consumes Property
• Specify the requested commit content type (Content-type), such as Application/json, text/html
Example: @RequestMapping (value = "/login", consumes = "Application/json")
• The value can be either a string or an array
Example: @RequestMapping (value = "/login", consumes = {"Application/json", "text/html"})

4>.produces Property
• Specifies the type of content returned (Content-type), such as Application/json, text/html
Example: @RequestMapping (value = "/login", produces = "Application/json")
• The value can be either a string or an array
Example: @RequestMapping (value = "/login", produces = {"Application/json", "text/html"})

5>.params Property
• Specifies that certain parameter values must be included in the request to trigger this processing method
Example: @RequestMapping (value = "/login", params = "id=1")
• In addition to the = equals sign, you can use the! = number to indicate that the method is triggered if the value of the parameter is not equal
Example: @RequestMapping (value = "/login", params = {"Id=1", "age!=18"})
• You can also use the "paramname" format without specifying a specific value, and the parameter named ParamName must be included in the request.
• Use the "!paramname" format directly to indicate that a request cannot contain a request parameter named ParamName

6>.headers Property
• The request header must contain some specified parameter values in order for the method to process the request, which can be used to deny access to clients from non-specified sources to enhance the security of the site.
Example: @RequestMapping (value = "/login", headers = "content-type=text/*")
Example: @RequestMapping (value = "/login", headers = {"content-type=text/*", "referer=http://www.buyinplay.com"})

Define ant style and URLs with placeholders

@RequestMapping not only supports standard URLs, it also supports Ant-style and URLs with {XXX} placeholders, and the following URLs are valid:

•   /user/*/login:匹配/user/aaa/login,/user/任意字符/login 等•   /user/**/login:匹配/user/login, /user/aaa/bbb/login 等•   /user/login??:匹配/user/loginAA, /user/loginbb 等•   /user/{userId}:匹配/user/123, /user/234 等•   /user/**/{userId}:匹配/user/aaa/bbb/123,/user/aaa/234等
2.Component annotations

component annotations are common annotations for controller annotations, service annotations, and repository annotations, and can play the same role ( using component when you're not sure about using that annotation). It is recommended to use specific annotations for clarity of code logic . These four annotations are class-level, with no parameters, or with a parameter that represents the bean name, which can be injected by name when injected.

![](media/14612091580198/14612489590879.jpg)?

Using @resource or @autowired annotations for injection
Similarities and differences between the @Resource and @autowired annotations:
@Resource for injection, (provided by the Java EE) by default assembly by name , @Resource (name= "Beanname")
@Autowired used for injection, (Srping provided) is assembled by type By default, the dependent object must be required to exist by default, and if you want to allow null values, you can set its Required property to False, for example: @Autowired ( Required=false), if we want to use name assembly can be used in conjunction with @qualifier annotations

?

In general I will use @resource to inject:

?

3.Controller annotations

Class-level annotations for declaring the controller class. Usage Reference "component annotations".

?

@Controller is responsible for registering a bean into the spring context, the bean ID defaults to the first letter of the class name lowercase, you can also specify, as follows
Method One:
@Controller
public class TestController {}

Method Two:
@Controller ("tmpcontroller")
public class TestController {}

4.Service annotations

Class-level annotations for declaring the service class. Usage Reference "component annotations".

?

5.Repository annotations

Class-level annotations that are used to declare DAO classes. Usage Reference "component annotations".

?

Third, other commonly used annotation Class 1. Cookievalue annotations

Read the value in the cookie and assign the value to the variable
There are three properties of value, required, DefaultValue, which represent the name of the cookie, whether it must have this cookie value, and if not, use the default value
Does not take any parameters, indicating that the required parameter name is the same as the label's variable name

@RequestMapping ("/listone") PublicString Listone (@CookieValue string goodsname) {//without any parameters    return"Listone";} @RequestMapping ("/listtwo") PublicString Listtwo (@CookieValue ("Goodsname") string goodsname) {//Specify the name of the cookie    return"Listtwo";} @RequestMapping ("/listthree") PublicString Listthree (@CookieValue (value= "Goodsname", defaultvalue= "new", Required =false) String Goodsname) {//Specifies the name of the cookie, if not, assigns the default value new    return"Listthree";}

2.PathVariable annotations

1>[email protected] is used for a parameter in a method that represents a template variable that the method parameter binds to the address URL.
For example:

@RequestMapping (value= "/owners/{ownerid}", method=requestmethod.get)  public  String Findowner (@PathVariable String ownerid, model model) {    = Ownerservice.findowner (ownerid);      Model.addattribute ("owner", owner);       return "Displayowner";  }  

?

2>[email protected] used when using the {XXX} template variable for the address bar.
If @requestmapping does not define a variable like "/{ownerid}", then using @pathvariable in the method will cause an error.

3.RequestBody Annotations 4.RequestHeader Annotations

You can bind the value of the header portion of the request to the parameters of the method

?

?

5.RequestMethod Annotations 6.RequestParam Annotations

@RequestParam is an optional parameter, such as a @RequestParam ("id") annotation, so it is bound to the URL with the parameter ID.
If the entry parameter is a basic data type (such as int, long, float, etc.), the URL request parameter must have corresponding parameter, otherwise it will throw
Org.springframework.web.util.NestedServletException exception indicating that null cannot be converted to the base data type.

@RequestParam consists of 3 configuration @RequestParam (required =, value= "", DefaultValue = "")
Required: Whether the parameter must be, Boolean type, optional, default to True
Value: passed the parameter name, string type, optional, if there is a value, corresponding to the parameter of the Set method
Defaultvalue:string type, the value that is specified by default for the parameter when the parameter is not passed

7.ResponseBody annotations

This annotation can be placed directly on the method, indicating that the return type will be output directly as an HTTP response byte stream (not placed in model or blocked as the View page name). Can be used for Ajax.

Object that is used to return the controller's method to the body data area of the response object after it is converted to the specified format by the appropriate Httpmessageconverter (converter)
Returns to be used when JSON, XML, and so on
Through the SPRINGMVC configuration file, initialize the 7 converters to Annotationmethodhandleradapter

    • Bytearranhttpmessageconverter Read and write binary data
    • Stringhttpmessageconverter converting request information to a string
    • Resourcehttpmessageconverter Read and write Org.springframework.core.io.Resource objects
    • Sourcehttpmessageconverter Read and write Javax.xml.transform.Source types of data
    • Xmlawareformhttpmessageconverter working with XML data in forms
    • Jaxb2rootelementhttpmessageconverter the request message to the annotation class of the callout Xmlrootelement and XmlType by JAXB2 reading and writing the XML message
    • Mappingjacksonhttpmessageconverter reading and writing JSON data

?

?

8.SessionAttribute annotations

Session Management
If you want a model property data to be common across multiple requests, you can label a @sessionattributes,spring MVC in the controller class to httpserssion the corresponding properties in the model
In addition to Sessionattributes, the session data can be processed directly using the Request.getsession ()

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. @SessionAttributes can only be declared on a class, not on a method.

@SessionAttributes (//@SessionAttributes ({"attr1", "attr2"= User. ) Class= {User.  Class, Dept.class= {User.  Class, Dept.class

@Controller @requestmapping (value= "/goods") @SessionAttributes ("RowCount")//all attributes named RowCount in the code are automatically stored in the session Public classGoodscontroller {@Resource goodsservice service; /**injection Syntax @Autowired @Qualifier ("Goodsservice") Goodsservice service; */@RequestMapping (Value= "/list")     Publicstring HelloWorld (HttpServletRequest request) {string Currpagestr= Request.getparameter ("page"); intCurrpage = 1; Try{currpage=Integer.parseint (CURRPAGESTR); } Catch(Exception e) {}//gets the total number of records        intRowCount = Service.getrowcount ();//is automatically stored in the sessionPageparam Pageparam =NewPageparam ();        Pageparam.setrowcount (RowCount); if(Pageparam.gettotalpage () <currpage) {Currpage=Pageparam.gettotalpage ();        } pageparam.setcurrpage (Currpage); Pageparam=service.getgoodsbypage (Pageparam); Request.setattribute ("Pageparam", Pageparam); return"List"; } @RequestMapping ("/clearsession")//This method is used only to demonstrate clear session     Publicstring Doclearsession (string goodsname,sessionstatus status) {Status.setcomplete (); return"List"; }}

9.Scope ("prototype") annotations

Set the scope of the bean

10.Transactional (Rollbackfor={exception.class}) annotations

Transaction management

11.ModelAttribute annotations

1>: Apply to method parameters, parameters can be obtained directly on the page, equivalent to Request.setattribute (,)
2> Apply to a method to label any method that has a return value @ModelAttribute so that its return value is entered into the list of properties for the model object.
3>: When applied to a method parameter @modelattribute ("XX"), the data type to be associated with the object, basic data type such as int,string does not work
For example:
Java code

@ModelAttribute ("Items")//<--① Adding a property named items to the model object PublicList<string>Populateitems () {List<String> lists =NewArraylist<string>(); Lists.add ("Item1"); Lists.add ("Item2"); returnlists; } @RequestMapping (Params= "Method=listallboard")   PublicString Listallboard (@ModelAttribute ("Curruser"user User, Modelmap model) {Bbtforumservice.getallboard (); //<--② The Items property in this access modelSystem.out.println ("Model.items:" + ((list<string>) Model.get ("Items") ). Size ()); return"Listboard"; } 


At ①, by using the @ModelAttribute annotations, the Populateitem () method is called before any request processing method executes, and Spring MVC places the return value of the method in the implied list of model object properties with the name "items". So at ②, we can access the Items property through Modelmap, and when the Listallboard () Request processing method is executed, the "model.items:2" message is printed on the console at ②. Of course we can also access the Items property in the model object in the requested view.

Common annotation classes for Spring MVC

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.