Spring MVC 之 ContentNegotiatingViewResolver
我们已经知道 对于 RequestMappingInfoHandlerMapping, 它在对带有后缀的http 请求进行匹配的时候,如果找不到精确的pattern, 那么就会 pattern+.* 后再匹配 url。 它会处理多个不同形式是 url, 但是返回的只是一个view。
ContentNegotiatingViewResolver 貌似也有这样的功能,但实际上是大不一样的。ContentNegotiatingViewResolver 有些难懂, 开始的时候, 我也是一直没有搞懂,反而搞晕了, 非常郁闷和尴尬。 它有些复杂,但也还好。
现在考虑这么一个情况,只配置一个@RequestMapping, 匹配多个 url, 这些url 可能有三个方面的不同:
1 其他都相同,只是后缀不同。 比如 /aa.jsp /aa.pdf /aa.xml /aa.json /aa (无后缀)
2 其他都相同,只是format参数不同。 比如 /aa?view=jsp /aa?view=pdf /aa?view=xml /aa?view=json /aa(无view 参数)
3 其他都相同,只是accept-type不同。 比如 /aa HTTP Request Header中的Accept 分别是 text/jsp, text/pdf, text/xml, text/json, 无Accept 请求头
如果是RequestMappingInfoHandlerMapping, 那么无法一个@RequestMapping满足这样的要求, 它需要多个@RequestMapping。
ContentNegotiatingViewResolver 可以一个@RequestMapping,返回多个view。
我的配置如下:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="favorParameter" value="true"/>
<property name="favorPathExtension" value="true"/>
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml"/> //
<entry key="json" value="application/json"/> // 这里, 对于 json ,必须是application/json
<!--<entry key="json" value="text/plain"/>-->
<entry key="xls" value="application/vnd.ms-excel"/>
</map>
</property>
<property name="viewResolvers">
<list>
<ref bean="jaxb2MarshallingXmlViewResolver"></ref>
<ref bean="jsonViewResolver"></ref>
<ref bean="excelViewResolver"></ref>
</list>
</property>
</bean>
上面的 viewResolvers 属性是可以不用配置的, 默认spring 会查找所有 ViewResolver类型的对象。这样, 就同时支持了 parameter参数方式和 后缀拓展名方式。
这里我直接使用了ContentNegotiatingViewResolver, 实际spring 给我们提供了 ContentNegotiationManagerFactoryBean,这是推荐的方式。 配置上类似。
默认是支持path 后缀拓展方式, 也支持accept 请求头,但不支持 format 参数的。 因此如果我们想使用 进行参数方式匹配, 那么我们需要把favorParameter 设置为true, 另外此时mediaTypes 也是必须正确配置的。 我感觉有些不合理。 应该是默认支持的, 现在却要我手动配置, 不过,我测试就是这样的结果。
源码是:
private boolean favorPathExtension = true; // 支持 private boolean favorParameter = false; // 默认不支持 private boolean ignoreAcceptHeader = false; // 默认支持accept头 private Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>(); private boolean ignoreUnknownPathExtensions = true; private Boolean useJaf; private String parameterName = "format";
除了xml 方式配置, 我们可以使用注解方式配置:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.yiibai.springmvc")
public class AppConfig extends WebMvcConfigurerAdapter { /*
* Configure ContentNegotiationManager
*/
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.ignoreAcceptHeader(true).defaultContentType(
MediaType.TEXT_HTML);
} /*
* Configure ContentNegotiatingViewResolver
*/
@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager); // Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<ViewResolver>(); resolvers.add(jaxb2MarshallingXmlViewResolver());
resolvers.add(jsonViewResolver());
resolvers.add(jspViewResolver());
resolvers.add(pdfViewResolver());
resolvers.add(excelViewResolver()); resolver.setViewResolvers(resolvers);
return resolver;
} /*
* Configure View resolver to provide XML output Uses JAXB2 marshaller to
* marshall/unmarshall POJO's (with JAXB annotations) to XML
*/
@Bean
public ViewResolver jaxb2MarshallingXmlViewResolver() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Pizza.class);
return new Jaxb2MarshallingXmlViewResolver(marshaller);
} /*
* Configure View resolver to provide JSON output using JACKSON library to
* convert object in JSON format.
*/
@Bean
public ViewResolver jsonViewResolver() {
return new JsonViewResolver();
} /*
* Configure View resolver to provide PDF output using lowagie pdf library to
* generate PDF output for an object content
*/
@Bean
public ViewResolver pdfViewResolver() {
return new PdfViewResolver();
} /*
* Configure View resolver to provide XLS output using Apache POI library to
* generate XLS output for an object content
*/
@Bean
public ViewResolver excelViewResolver() {
return new ExcelViewResolver();
} /*
* Configure View resolver to provide HTML output This is the default format
* in absence of any type suffix.
*/
@Bean
public ViewResolver jspViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
} }
对于boot, 其自动配置了一个
@Bean
@ConditionalOnBean({ViewResolver.class})
@ConditionalOnMissingBean(
name = {"viewResolver"},
value = {ContentNegotiatingViewResolver.class}
)
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager((ContentNegotiationManager)beanFactory.getBean(ContentNegotiationManager.class));
resolver.setOrder(-2147483648);
return resolver;
} @Bean
public ContentNegotiationManager mvcContentNegotiationManager() {
ContentNegotiationManager manager = super.mvcContentNegotiationManager();
List<ContentNegotiationStrategy> strategies = manager.getStrategies();
ListIterator iterator = strategies.listIterator(); while(iterator.hasNext()) {
ContentNegotiationStrategy strategy = (ContentNegotiationStrategy)iterator.next();
if (strategy instanceof PathExtensionContentNegotiationStrategy) { // 只支持后缀 方式匹配
iterator.set(new WebMvcAutoConfiguration.OptionalPathExtensionContentNegotiationStrategy(strategy));
}
} return manager;
}
但是, 它只支持 后缀方式匹配。
参考
http://blog.csdn.net/fw0124/article/details/48315523
http://blog.csdn.net/fw0124/article/details/48315523
http://blog.csdn.net/z69183787/article/details/41696709
Spring MVC 之 ContentNegotiatingViewResolver的更多相关文章
- Spring学习笔记之五----Spring MVC
Spring MVC通常的执行流程是:当一个Web请求被发送给Spring MVC Application,Dispatcher Servlet接收到这个请求,通过HandlerMapping找到Co ...
- Spring MVC视图解析器
Spring MVC提供的视图解析器使用ViewResolver进行视图解析,实现浏览器中渲染模型.ViewResolver能够解析JSP.Velocity模板.FreeMarker模板和XSLT等多 ...
- Spring MVC 学习总结(四)——视图与综合示例
一.表单标签库 1.1.简介 从Spring2.0起就提供了一组全面的自动数据绑定标签来处理表单元素.生成的标签兼容HTML 4.01与XHTML 1.0.表单标签库中包含了可以用在JSP页面中渲染H ...
- spring笔记3 spring MVC的基础知识3
4,spring MVC的视图 Controller得到模型数据之后,通过视图解析器生成视图,渲染发送给用户,用户就看到了结果. 视图:view接口,来个源码查看:它由视图解析器实例化,是无状态的,所 ...
- 【Spring】搭建最简单的Spring MVC项目
每次需要Spring MVC的web项目测试一些东西时,都苦于手头上没有最简单的Spring MVC的web项目,现写一个. > 版本说明 首先要引入一些包,Spring的IOC.MVC包就不用 ...
- 四、Spring——Spring MVC
Spring MVC 1.Spring MVC概述 Spring MVC框架围绕DispatcherServlet这个核心展开,DispatcherServlet负责截获请求并将其分配给响应的处理器处 ...
- Spring 4 官方文档学习(十一)Web MVC 框架之配置Spring MVC
内容列表: 启用MVC Java config 或 MVC XML namespace 修改已提供的配置 类型转换和格式化 校验 拦截器 内容协商 View Controllers View Reso ...
- 【Spring学习笔记-MVC-18.1】Spring MVC实现RESTful风格-同一资源,多种展现:xml-json-html
概要 要实现Restful风格,主要有两个方面要讲解,如下: 1. 同一个资源,如果需要返回不同的形式,如:json.xml等: 不推荐的做法: /user/getUserJson /user/get ...
- spring mvc中的json整合
spring mvc整合过程中是有版本兼容的问题.具体的哪个版本的springmvc和哪个个版本的json包冲突我也无从考证了.我用的springmvc版本是3.2.1jaskson的版本是 1.1. ...
随机推荐
- html页面调用js文件里的函数报错-->方法名 is not defined处理方法
前几天写了一个时间函数setInterval,然后出现了这个错误:Uncaught ReferenceError: dosave is not defined(…) 找了半天都没发现错在哪,最后找到解 ...
- ES6新特性,对象的快速创建
//es6对象快速赋值 //es5对象赋值 var name="xiaoming"; var age=18 var person={ name:name, age:age } co ...
- mybatis xml配置文件模版
mybatis xml配置文件模版 1.mybatis核心配置文件书写(SqlMapConfig.xml) <?xml version="1.0" encoding=&quo ...
- Ubuntu 17.10 安装Caffe(cpu)并配置Matlab接口
(1)安装依赖: sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libhdf5-ser ...
- Apache Shiro 快速入门教程,shiro 基础教程
第一部分 什么是Apache Shiro 1.什么是 apache shiro : Apache Shiro是一个功能强大且易于使用的Java安全框架,提供了认证,授权,加密,和会话管理 ...
- 【leetcode】453. Minimum Moves to Equal Array Elements
problem 453. Minimum Moves to Equal Array Elements 相当于把不等于最小值的数字都减到最小值所需要次数的累加和. solution1: class So ...
- Date.parse()转化日期为时间戳,ios与Android兼容写法
把固定格式日期转化为时间戳: //格式化当地日期 new Date('2017-11-11 0:0:0') //结果为:Sat Nov 11 2017 00:00:00 GMT+0800 (中国标准时 ...
- python3 基础整理
基础语法 1.python中区分大小写 2.查看关键字用 import keyword print (keyword.kwlist) 3.注释 # 单行注释,多行注释的快捷键是ctr+/,取消注释的 ...
- macbook hive安装
1 原材料 1.1 已经安装好的伪分布式hadoop,版本2.8.3(参见链接https://www.cnblogs.com/wooluwalker/p/9128859.html) 1.2 apach ...
- 《Linux内核原理与分析》第九周作业
课本:第八章 进程的切换和系统的一般执行过程 进行进程调度的时机 Linux内核通过schedule函数实现进程调度,schedule函数在运行队列中找到一个进程,把CPU分配给它 调用schedul ...