你的位置:首页 > 软件开发 > Java > springmvc一一种资源返回多种形式【ContentNegotiatingViewResolver】

springmvc一一种资源返回多种形式【ContentNegotiatingViewResolver】

发布时间:2016-09-24 18:00:09
restful服务中一个重要的特性就是一种资源可以有多种表现形式,在springmvc中可以使用ContentNegotiatingViewResolver这个视图解析器来实现这种方式。描述资源的三种形式 一、使用扩展名http://localhost:8080/t ...

springmvc一一种资源返回多种形式【ContentNegotiatingViewResolver】

restful服务中一个重要的特性就是一种资源可以有多种表现形式,在springmvc中可以使用ContentNegotiatingViewResolver这个视图解析器来实现这种方式。

描述资源的三种形式

    一、使用扩展名

http://localhost:8080/test/user.

http://localhost:8080/test/user.json  以json格式呈现

http://localhost:8080/test/user     以默认视图呈现,如jsp

    二、使用http request header的Accept

 

GET /user HTTP/1.1

Accept:application/

 

GET /user HTTP/1.1

Accept:application/json  请求时设置返回形式是json,如使用ajax请求,则需要设置contentType:application/json

    三、使用参数

 

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

http://localhost:8080/test/user?format=

 

上面了解了同一种资源的三种呈现方式,即json、

ContentNegotiatingViewResolver配置

ContentNegotiatingViewResolver是视图解析器,我们在使用jsp这个视图的时候也配置了一个视图解析器InternalResourceViewResolver,他们都是视图解析器,后者着重在配置一个默认的视图解析即jsp;ContentNegotiatingViewResolver本身不会解析,他会分配其他的viewResolver去解析,并选择一个看起来像是客户端请求需要返回的一种 View 返回。

下面是ContentNegotiatingViewResolver的具体配置

<!--springmvc中根据后缀不同返回不同格式的配置     如,XXX.json 返回json格式      XXX.-->  <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">    <!--这里是解析器的执行顺序,如果有多个的话,配置的数值越小,则越早执行-->    <property name="order" value="1" />    <!--    这里是是否启用扩展名支持,默认就是true          例如 /user/{userid}.json       -->    <property name="favorPathExtension" value="true"></property>     <!--这里是是否启用参数支持,默认就是true    例如 /user/{userid}?format=json       -->    <property name="favorParameter" value="false"></property>    <!--这里是否忽略掉accept header,默认就是false          例如   GET /user HTTP/1.1    Accept:application/json    -->     <property name="ignoreAcceptHeader" value="true"></property>    <!--        这里是扩展名到mimeType的映射,    例如 /user/{userid}.json 中的  .json 就会映射到  application/json    -->    <property name="mediaTypes">      <map>        <entry key="json" value="application/json" />         <entry key="class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"></bean>      <!--class="org.springframework.web.servlet.view.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>

原标题:springmvc一一种资源返回多种形式【ContentNegotiatingViewResolver】

关键词:Spring

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录