springmvc< > A resource returns multiple forms of "contentnegotiatingviewresolver"

Source: Internet
Author: User
Tags mul

One of the important features of restful services is that a resource can have multiple representations, which can be implemented in SPRINGMVC using the Contentnegotiatingviewresolver view parser.

Three forms of describing resources

First, use the extension

Http://localhost:8080/test/user.xml rendering in XML format

Http://localhost:8080/test/user.json rendered in JSON format

Http://localhost:8080/test/user is rendered in the default view, such as JSP

Ii. accept with HTTP request header

Get/user http/1.1

Accept:application/xml when the request is set to return the form is XML, such as using AJAX requests, you need to set the Contenttype:application/xml

Get/user http/1.1

Accept:application/json when the request is set back as JSON, such as using an AJAX request, you need to set the Contenttype:application/json

Third, the use of parameters

Http://localhost:8080/test/user?format=json

Http://localhost:8080/test/user?format=xml

The three ways to render the same resource, JSON, XML, JSP, how do we use the Contentnegotiatingviewresolver class configuration to make the client request different ways to return three ways of the same resource?

Contentnegotiatingviewresolver Configuration

Contentnegotiatingviewresolver is the view parser, we also configure a view parser when using the JSP view Internalresourceviewresolver, they are the view parser, The latter focuses on configuring a default view resolution that Jsp;contentnegotiatingviewresolver itself does not parse, he assigns other viewresolver to parse, and chooses a view return that looks like a client request needs to be returned.

Here is the specific configuration of the Contentnegotiatingviewresolver

<!--SPRINGMVC returns different format configurations according to the suffix, Xxx.json returns the JSON format Xxx.xml returns the XML format XXX returns the JSP 
    -<beanclass= "Org.springframework.web.servlet.view.ContentNegotiatingViewResolver" > <!--here is the execution order of the parser, if there are multiple, the smaller the configured value, The sooner you do--<property name= "Order" value= "1"/> <!--here is whether to enable the extension support, the default is true for example/user/{Userid}.json--<property name= "Favorpathextension" value= "true" ></property> <!--here is whether the parameter support is enabled, the default is true for example/user/{userid}?format=JSON--<property name= "Favorparameter" value= "false" ></property> <!--If this ignores the accept header, the default is false such as GET/user http/1.1accept:application/JSON--<property name= "Ignoreacceptheader" value= "true" ></property> <!--here is the extension to mimetype mapping, for exampleThe. JSON in/user/{userid}.json is mapped to application/JSON--<property name= "MediaTypes" > <map> <entry key= "json" value= "Applica        Tion/json "/> <entry key=" xml "value=" Application/xml "/> </map> </property> <!--View--<property name= "Defaultviews" > <list> <!--JS On view-<beanclass= "Org.springframework.web.servlet.view.json.MappingJackson2JsonView" ></bean> <!--XML View-- <beanclass= "Org.springframework.web.servlet.view.xml.MarshallingView" <constructor-arg> <beanclass= "Org.springframework.oxm.jaxb.Jaxb2Marshaller" > <property name= "Classestobebound" > <list> <value>com.cn.my.entity.course</valu                                E> <value>com.cn.my.entity.CourseList</value> </list> </property> </bean> &L t;/constructor-arg> </bean> </list> </property> </bean>

Order: If there are more than one viewresolver, the order value is used, if there is no suitable viewresolver, the other is used;

Favorpathextension: Whether the extension is supported, the default is True (support), the extension refers to the form of Xxx.json, xxx.xml, etc.

Favorparameter: Whether to enable parameter support, the default is True (support), that is, Xxx?format=json, Xxx?format=xml, and so on, the parameter name here defaults to format, can be changed by configuration.

Ignoreacceptheader: Whether to ignore the Accept header, the default is False (not ignored), that is, the request specified Contenttype:application/json, etc., because I would like to use the extension to return the form, So the other two are closed, depending on the situation, the use of different settings;

MediaTypes: Configure the extension to mimetype mapping, where the JSON and XML mappings are configured;

Defaultviews: Configuration view, where JSON and XML views are configured, and JSON uses the Jackson;

Finally, I also configured a different view parser, Internalresourceviewresolver,

class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >        <property name= " Order "value=" 2 "/>        <property name=" prefix "value="/web-inf/jsp/"></property>        <property Name= "suffix" value= ". jsp" ></property>        <property name= "Viewclass" value= " Org.springframework.web.servlet.view.JstlView "/>    </bean>

This is the JSP view resolver, and the Order property is configured for 2, which returns the view of the JSP in the case of a mismatch to JSON and XML.

Here's how the controller is.

 PackageCom.cn.my.controllor;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.ModelMap;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;ImportCom.cn.my.entity.Course;Importcom.cn.my.entity.CourseList, @Controller @requestmapping ("/mul") Public classMultiView {@RequestMapping ("/simple/{coursid}")     PublicString method1 (@PathVariable ("Coursid") {Course C, String coursid,modelmap model)=NewCourse ();        C.setid (COURSID); C.setcontent ("This is the test content"); C.setname ("John Doe"); Model.put ("Course", c); return"Course"; }}

The format of the URI used in the restful service here uses the @pathvariable annotation, where the method returns a string with no @responsebody annotations, and returns the JSON configuration in the front of the return JSON article. Need @responsebody annotations, detailed can see the front, at the same time in the method parameters have Modelmap, why here to return a string, the purpose is to unify, we know that if you want to return to the JSP view, then here to return a string representing the logical view name, In order to unify three ways, the string is returned, and if you do not return to the JSP you can return an actual object.

See the test results below,

Request: Http://localhost:8081/springmvc/mul/simple2/1212.json

Request: Http://localhost:8081/springmvc/mul/simple2/1212.xml

Request: http://localhost:8081/springmvc/mul/simple2/1212

The last JSP view, originally to be in the JSP page output content, I did not do here, just output a paragraph. Please understand!

From the above test results, we used three different request methods to request the same resource, return the respective form, which is very suitable for different systems to call the same system, perhaps other systems processing data differently, we use the above configuration can implement a set of code, return different forms.

At last

The default JSP parser can also be configured as follows.

<!--SPRINGMVC returns different format configurations according to the suffix, Xxx.json returns the JSON format Xxx.xml returns the XML format XXX returns the JSP 
    -<beanclass= "Org.springframework.web.servlet.view.ContentNegotiatingViewResolver" > <!--here is the execution order of the parser, if there are multiple, the smaller the configured value, The sooner you do--<property name= "Order" value= "1"/> <!--here is whether to enable the extension support, the default is true for example/user/{Userid}.json--<property name= "Favorpathextension" value= "true" ></property> <!--here is whether the parameter support is enabled, the default is true for example/user/{userid}?format=JSON--<property name= "Favorparameter" value= "false" ></property> <!--If this ignores the accept header, the default is false such as GET/user http/1.1accept:application/JSON--<property name= "Ignoreacceptheader" value= "true" ></property> <!--here is the extension to mimetype mapping, for exampleThe. JSON in/user/{userid}.json is mapped to application/JSON--<property name= "MediaTypes" > <map> <entry key= "json" value= "Applica        Tion/json "/> <entry key=" xml "value=" Application/xml "/> </map>                                </property> <!--View Resolver--<property name= "Viewresolvers" > <list> <beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name= "pre Fix "value="/web-inf/jsp/"></property> <property name=" suffix "value=". JSP "></propert                y> <property name= "Viewclass" value= "Org.springframework.web.servlet.view.JstlView"/> </bean> </list> </property> <!--View--<property Nam E= "Defaultviews" > <list> <!--JSON View--<beanclass= "Org.springframework.web.servlet.view.json.MappingJackson2JsonView" ></bean> <!--XML View-- <beanclass= "Org.springframework.web.servlet.view.xml.MarshallingView" <constructor-arg> <beanclass= "Org.springframework.oxm.jaxb.Jaxb2Marshaller" > <property name= "Classestobebound" > <list> <value>com.cn.my.entity.course</valu                                E> <value>com.cn.my.entity.CourseList</value> </list> </property> </bean> &L t;/constructor-arg> </bean> </list> </property> </bean>

Disclaimer: My environment here is spring4.1.

Reference:

http://blog.csdn.net/z69183787/article/details/41654603

There is a good explanation on the top.

There is an incorrect place to welcome correct, thank you!

springmvc< > A resource returns multiple forms of "contentnegotiatingviewresolver"

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.