Theory
public class Contentnegotiatingviewresolverextends Webapplicationobjectsupportimplements Viewresolver, Orderedimplementation of viewresolver that resolves a view based on the request file name or Accept header. The contentnegotiatingviewresolver does not resolve views itself, but delegates to other viewresolvers. By default, these other view resolvers is picked up automatically from the application context, though they can also be s Et explicitly by using the Viewresolvers property. Note that-in order-this view resolver-to-work properly, the Order property needs to is set to a higher precedence than The others (the default is Ordered.highest_precedence.) This view resolver uses the requested media type to select a suitable view for a request. This media type was determined by using the following criteria:if the requested path has a file extension and If the setfav Orpathextension (Boolean) property is True, and the MediaTypes property was inspected for a matching media type. If the request CoNtains A parameter defining the extension and if the Setfavorparameter (Boolean) property was true, the MediaTypes property is inspected for a matching media type. The default name of the parameter is format and it can be configured using the ParameterName property. If there is no match with the MediaTypes property and if the Java Activation Framework (JAF) are both enabled and present on The Classpath, Filetypemap.getcontenttype (String) is used instead. If the previous steps did not have result in a media type, and Ignoreacceptheader are false, the request Accept header is USED.O NCE the requested media type have been determined, this resolver queries each delegate view resolver for a view and Determi NES if the requested media type is compatible with the view's content type). The most compatible view is returned. Additionally, this view resolver exposes the Defaultviews property, allowing you to override the "views" provided by the Vie W resolvers. Note that these the default views is offered as Candicates, and still need have the content type requested (via file extension, parameter, or Accept header, described above). You can also set the default content type directly, which'll be a returned when the other mechanisms (Accept header, file Extension or parameter) does not result in a match. For example, if the request path is/view.html, this view resolver would look for a view of the text/html content Typ E (based on the HTML file extension). A request For/view with a text/html request Accept header has the same result.
Spring MVC configuration file:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" Xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework . Org/schema/context http://www.springframework.org/schema/context/spring-context.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/m Vc/spring-mvc.xsd "><mvc:annotation-driven content-negotiation-manager=" Contentnegotiationmanager "/> <mvc:view-controller path= "/" view-name= "index"/><bean id= "Contentnegotiationmanager" class= " Org.springframework.web.accept.ContentNegotiationManagerFactoryBean "><property name="MediaTypes "><value>html=text/htmljson=application/json</value></property><property Name = "Defaultcontenttype" value= "text/html"/></bean><bean class= " Org.springframework.web.servlet.view.ContentNegotiatingViewResolver "><property name=" order "value=" 0 "/> <property name= "Contentnegotiationmanager" ref= "Contentnegotiationmanager"/><property name= " Viewresolvers "><list><bean class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "><property name=" Viewclass "value=" Org.springframework.web.servlet.view.JstlView "/><property name=" Prefix "value="/web-inf/jsp/"/><property name=" suffix "value=". JSP "></property></bean></ List></property><property name= "defaultviews" ><list><bean class= " Com.alibaba.fastjson.support.spring.FastJsonJsonView "><property name=" CharSet "value=" UTF-8 "/></bean ></list></property></bean><bean class= "com.Alibaba.fastjson.support.spring.FastJsonHttpMessageConverter "/></beans>
Write a test controller.
Package Com.doctor.springframework.web.view;import Java.util.hashmap;import Java.util.map;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.servlet.ModelAndView; @Controllerpublic class Simplecontroller {@RequestMapping ({"/test.html", "/test.json"}) public Modelandview test () { map<string, string> map = new hashmap<> (), Map.put ("Test", "JSON"), Map.put ("test-html", "html"), Map.put (" What "and" what "); Modelandview Modelandview = new Modelandview ("/contentviewtest"); Modelandview.addobject (map); return modelandview;}}
Test code:
Package Com.doctor.springframework.web.view;import Org.apache.http.client.fluent.request;import Org.apache.http.client.fluent.response;import Org.junit.after;import Org.junit.before;import org.junit.Test; Import com.doctor.embeddedjetty.embeddedjettyserver3;/** * Contentnegotiatingviewresolverpractice depending on the path suffix, select different views * @ Author Doctor * * @time January 7, 2015 morning 10:08:24 */public class ContentNegotiatingViewResolverPractice2 {private Embeddedjet TyServer3 embeddedjettyserver;private int port, @Beforepublic void Init () throws Throwable {port = 8989; Embeddedjettyserver = new EmbeddedJettyServer3 (port, "/contentnegotiatingviewresolverpractice/webapp", Springcontextconfig.class, Springmvcconfig2.class); Embeddedjettyserver.start ();} @Testpublic void Test () throws Throwable {Response Response = request.get ("Http://localhost:8989/test.json"). Execute () ; System.out.println (Response.returncontent (). asstring ()); response = Request.get ("http://localhost:8989/test.html" ). Execute (); System.out.println (Response.retUrncontent (). asstring ()); response = Request.get ("http://localhost:8989"). Execute (); System.out.println (Response.returncontent (). asstring ());} @Afterpublic void Destroy () throws Throwable {Embeddedjettyserver.stop ();}}
Output content:
01-10 10:18:40.513 main INFO o.e.j.s.server-started @4908ms{"HashMap": {"test": "JSON", "test-html": "HTML", " What ":" What "}}<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Code Download: https://github.com/doctorwho1986/doctor/blob/master/springmvc-practice/src/test/java/com/doctor/ Springframework/web/view/contentnegotiatingviewresolverpractice2.javaSpring MVC contentnegotiatingviewresolver Select different views based on the path suffix