SPRINGMVC---Other common annotations

Source: Internet
Author: User

Common annotations

    • Pathvariable

In cases where placeholders are used @RequestMapping annotations, you need to specify placeholder parameters using @pathvariable annotations. That is, the value in the specified placeholder matches which parameter in the method. If the parameter name in the method is the same as the name of the {} (placeholder) in the URL, you can omit the userId in @pathvariable ("UserId"), which is @ pathvariable String userid

@RequestMapping (value= "/user/{userid}/roles/{roleid}", method = public String getlogin (@   Pathvariable ("userid") String userId) {System.out.println ("User Id:" + userId);  return "Hello";}

    • Requestparam

There are two main ways to get the parameters in the Springmvc background control layer, one is Request.getparameter ("name") and the other is obtained directly with the annotation @requestparam. @RequestParam has three properties, value (parameter name), required (whether the parameter value must be available), DefaultValue (default). Used in a method, if the annotation is used in a parameter in a method, the parameter must be included in the request, otherwise it will not be fired. The method can be triggered in the request even if there are no parameters annotated in the method, which is true by setting the required property to False. If the parameter is a value of the Int/boolean data type, it will be an error if the parameter is not passed because the Int/boolean type cannot assign a null value. So it is recommended to use Integer/boolean

 Public String GetLogin (@RequestParam (value= "userid", required=true, defaultvalue=0) string userId, @   Requestparam String userName) {System.out.println ("User Id:" + userId);  return "Hello";}

    • Cookievalue

Read the value in the cookie and assign the value to the variable. There are three properties of value, required, DefaultValue, and usage similar to Requestparam usage

    • Sessionattributes

If you need to share data between multiple requests, we usually save the data in the session. If you want to share a model property data across multiple requests, you can label a @sessionattributes,springmvc in the controller class to temporarily save the corresponding properties in the model to httpsession. In addition to using sessionattributes, you can also use Request.getsession () to process session data.

    • Responsebody

The object used to return the controller's method is written to the body data area of the response object after the appropriate Httpmessageconverter (converter) is converted to the specified format, typically used when the return value is not a page, such as returning JSON, XML and so on, using Responsebody will skip the part of view processing. The Httpmessageconverter interface is responsible for translating the request into an object and outputting the object as a response message, and after the <mvc:annotation-driven/> is turned on in the Spring-mvc.xml configuration file, Initializes 7 converters for Annotationmethodhandleradapter, which can be called by calling Annotationmethodhandleradapter's Getmessageconverts () method to get a collection of converters list

Commonly used Converters

Bytearrayhttpmessageconverter Read and write binary data
Stringhttpmessageconverter Convert 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 Convert request messages to standard xmlrootelement and XmlType annotation classes by JAXB2 Read and write XML messages
Mappingjacksonhttpmessageconverter Read and write JSON data

The next three are for processing XML data and JSON data, each request SPRINGMVC will pick one from the listcanRead () and CanWrite () methods , and the returned values are Boolean types to see if this httpmessageconverter supports the read and write of the current request. Read the corresponding requestbody annotations, write the corresponding responsebody annotations, requestbody annotations similar to Requestparam, mainly used to read the request body data. Finally, the Httpmessageconverter collection is traversed, matched with the previous fetch acceptable type, and if so, directly using the current first matching httpmessageconverter and then return

Example:

In Spring-mvc.xml configuration

<Mvc:annotation-drivenContent-negotiation-manager= "Contentnegotiationmanager">    <mvc:message-convertersRegister-defaults= "true">      <Beanclass= "Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />      <Beanclass= "Org.springframework.http.converter.StringHttpMessageConverter" />      <Beanclass= "Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />      <BeanID= "Marshallinghttpmessageconverter"class= "Org.springframework.http.converter.xml.MarshallingHttpMessageConverter" >        <Constructor-argref= "Jaxbmarshaller" />        < Propertyname= "Supportedmediatypes"value= "Application/xml"></ Property>      </Bean>    </mvc:message-converters></Mvc:annotation-driven>    <BeanID= "Jaxbmarshaller"class= "Org.springframework.oxm.jaxb.Jaxb2Marshaller">    < Propertyname= "Classestobound">      <List>        <value>Com.jikexueyuan.demo.springmvc.model.User</value>      </List>    </ Property></Bean>

By using responsebody annotations, depending on the value of the accept parameter in the request header, the JSON and XML results of an entity are rendered separately for the same address request, first in the configuration file, using MVC: Annotation-driven defines the required messageconverter, here we use 4 converters, respectively, to process JSON data, string data, XML data, In defining XML data processing, we need to use the Jaxb2marshaller class to define our entity classes, such as the user class, which need to be labeled xmlrootelement annotations

Converter implementation in Java

// annotate with responsebody annotations and return directly to the objects that need to be converted @ResponseBody @requestmapping (Value= "/user/{userid}", method = requestmethod.get)  Public Long   New  User ();  U.setunick ("Zhangsan");  U.setlastlogindatetime (new  Date ());  return  u;}
    • Requestheader

@RequestHeader annotations, you can bind the value of the header portion of a request to a method parameter. Use the method parameter on @requestheader ("keep-alive") long keepAlive

Header data includes

Host localhost:8080

Accept text/html,application/xhtml+xml,application/xml;q=0.9

Accept-language fr,en-gb;q=0.7,en;q=0.3

Accept-encoding gzip,deflate

Accept-charset iso-8859-1,utf-8;q=0.7,*;q=0.7

Keep-alive 300

SPRINGMVC---Other 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.