Springmvc & lt; 1 & gt; a kind of resource return multiple forms [ContentNegotiatingViewResolver], springmvc returns json

Source: Internet
Author: User

Springmvc <1> multiple forms of resource return [ContentNegotiatingViewResolver], springmvc returns json

An important feature of restful services is that resources can have multiple forms of representation. In springmvc, you can use the ContentNegotiatingViewResolver view parser to implement this method.

Three types of Resource Description

1. Use the extension

Http: // localhost: 8080/test/user. xml is displayed in xml format.

Http: // localhost: 8080/test/user. json is displayed in json format.

Http: // localhost: 8080/test/user is displayed in the default view, such as jsp

2. Use the Accept of the http request header

 

GET/user HTTP/1.1

Accept: The returned format is xml when the application/xml request is set. For ajax requests, you need to set contentType: application/xml

 

GET/user HTTP/1.1

Accept: The Return format is json when the application/json request is set. For ajax requests, you need to set contentType: application/json

3. Use Parameters

 

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

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

 

We have learned three ways to present the same resource: json, xml, and jsp. How can we use the ContentNegotiatingViewResolver class configuration to make the client request in different ways, what are the three methods for returning the same resource?

ContentNegotiatingViewResolver Configuration

ContentNegotiatingViewResolver is a view parser. We also configured a view parser InternalResourceViewResolver when using the jsp view. They are all view Resolvers, the latter focuses on configuring a default view resolution, that is, jsp. ContentNegotiatingViewResolver does not parse itself, and other viewResolver will be allocated for parsing, and select a View that looks like a client request needs to return.

The following describes the specific configuration of ContentNegotiatingViewResolver.

<! -- Springmvc returns different format Configurations Based on Different suffixes, for example, XXX. json return format XXX. xml return xml format xxx return jsp --> <bean class = "org. springframework. web. servlet. view. contentNegotiatingViewResolver "> <! -- Here is the execution sequence of the parser. If there are multiple, the smaller the value configured, the sooner you execute --> <property name = "order" value = "1"/> <! -- Whether to enable extension support. The default value is true, for example,/user/{userid }. json --> <property name = "favorPathExtension" value = "true"> </property> <! -- Whether to enable parameter support. The default value is true, for example,/user/{userid }? Format = json --> <property name = "favorParameter" value = "false"> </property> <! -- Whether to ignore the accept header. The default value is false, for example, GET/user HTTP/1.1 Accept: application/json --> <property name = "ignoreAcceptHeader" value = "true"> </property> <! -- Here is the miing between the extension and mimeType, for example,/user/{userid }. in json. json is mapped to application/json --> <property name = "mediaTypes"> <map> <entry key = "json" value = "application/json"/> <entry key = "xml" value = "application/xml"/> </map> </property> <! -- View --> <property name = "defaultViews"> <list> <! -- Json view --> <bean class = "org. springframework. web. servlet. view. json. MappingJackson2JsonView"> </bean> <! -- Xml View --> <bean class = "org. springframework. web. servlet. view. xml. marshallingView "<constructor-arg> <bean class =" org. springframework. oxm. jaxb. jaxb2Marshaller "> <property name =" classesToBeBound "> <list> <value> com.cn. my. entity. course </value> <value> com.cn. my. entity. courseList </value> </list> </property> </bean> </constructor-arg> </bean> </list> </property> </bean>

Order: if multiple viewresolvers exist, the order value is small. If no suitable viewResolver exists, another one is used;

FavorPathExtension: whether the extension is supported. The default value is true (supported). The extension is in the format of xxx. json and xxx. xml.

FavorParameter: whether to enable parameter support. The default value is true (supported), that is, xxx? Format = json, xxx? Format = xml. The default parameter name here is format, which can be changed through configuration.

IgnoreAcceptHeader: whether to ignore the accept header. The default value is false (not ignored), that is, the specified contentType: application/json in the request. because I want to use the extension here to return, therefore, the other two items are disabled. Different settings are used depending on different situations;

MediaTypes: configure the miing between the extension and mimeType. The json ing between json and xml is configured here;

DefaultViews: configuration view. json and xml views are configured here. jackson is used in json;

Finally, I configure another view parser, InternalResourceViewResolver,

<bean 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 view parser of jsp. If the order attribute is set to 2 and cannot match json or xml, the view of jsp is returned.

The following describes the controller method.

Package com.cn. my. controllor; import java. util. arrayList; import java. util. list; import org. springframework. stereotype. controller; import org. springframework. ui. modelMap; import org. springframework. web. bind. annotation. pathVariable; import org. springframework. web. bind. annotation. requestMapping; import com.cn. my. entity. course; import com.cn. my. entity. courseList; @ Controller @ RequestMapping ("/mul") public class MultiView {@ RequestMapping ("/simple/{coursId}") public String method1 (@ PathVariable ("coursId ") string coursId, ModelMap model) {Course c = new Course (); c. setId (coursId); c. setContent ("this is the test content"); c. setName ("Li Si"); model. put ("course", c); return "course ";}}

The uri format in the restful service used here uses the @ PathVariable annotation. Here, the String returned by the method does not have the @ ResponseBody annotation, And the json configuration is returned in the header of the returned json, @ ResponseBody annotation is required. For details, refer to the front side and use ModelMap in the method parameters. Why is a string returned here for unification? We know that if we want to return to the jsp view, here we will return a string that represents the name of the logical view. to unify the three methods, we will return a string. If we do not return it back to jsp, we can return an actual object.

The test result is as follows,

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 is intended to output content on the jsp page. I didn't do it here, but I just output a paragraph. Please forgive me!

 

From the test results above, we use three different request methods to request the same resource and return their respective forms, this method is suitable for different systems to call the same system. Other systems may process data in different ways. We can use the above configuration to implement a set of code and return different forms.

Last

When configuring the default jsp parser, you can also follow the configuration method below,

<! -- Springmvc returns different format Configurations Based on Different suffixes, for example, XXX. json return format XXX. xml return xml format xxx return jsp --> <bean class = "org. springframework. web. servlet. view. contentNegotiatingViewResolver "> <! -- Here is the execution sequence of the parser. If there are multiple, the smaller the value configured, the sooner you execute --> <property name = "order" value = "1"/> <! -- Whether to enable extension support. The default value is true, for example,/user/{userid }. json --> <property name = "favorPathExtension" value = "true"> </property> <! -- Whether to enable parameter support. The default value is true, for example,/user/{userid }? Format = json --> <property name = "favorParameter" value = "false"> </property> <! -- Whether to ignore the accept header. The default value is false, for example, GET/user HTTP/1.1 Accept: application/json --> <property name = "ignoreAcceptHeader" value = "true"> </property> <! -- Here is the miing between the extension and mimeType, for example,/user/{userid }. in json. json is mapped to application/json --> <property name = "mediaTypes"> <map> <entry key = "json" value = "application/json"/> <entry key = "xml" value = "application/xml"/> </map> </property> <! -- View parser --> <property name = "viewResolvers"> <list> <bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "> <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> </list> </property> <! -- View --> <property name = "defaultViews"> <list> <! -- Json view --> <bean class = "org. springframework. web. servlet. view. json. MappingJackson2JsonView"> </bean> <! -- Xml View --> <bean class = "org. springframework. web. servlet. view. xml. marshallingView "<constructor-arg> <bean class =" org. springframework. oxm. jaxb. jaxb2Marshaller "> <property name =" classesToBeBound "> <list> <value> com.cn. my. entity. course </value> <value> com.cn. my. entity. courseList </value> </list> </property> </bean> </constructor-arg> </bean> </list> </property> </bean>

Statement: My environment here is spring4.1

Refer:

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

There is a good explanation above.

Correct the error. Thank you!

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.