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. ...
随机推荐
- 18-09-20 关于Excel 表格重复问题解决示例
代码实现:b=a.drop_duplicates(subset=None, keep='first', inplace=False) Excel 去除重复项 在测试过程中,会经常遇到多张表格筛选比对的 ...
- HTML5:定位
定位 一.介绍: position设置块级元素相对于其父块的位置和相对于它自身应该在的位置,任何使用定位的元素都会成为块级元素. 1.属性值 属性值 描述 absolute 生成绝对定位的元素,相对于 ...
- fiddler之数据统计(statistics)
在使用fiddler代理监听访问时,可以使用statistics分页去统计请求和响应的一些信息. 界面显示如下: 可以在这里查看一个session的统计信息 说明: 1.request count:请 ...
- windows 安装mysql 5.7的正确姿势
1.首先上MySql的官网下载 https://dev.mysql.com/downloads/mysql/ 2. 以我所选版本为例(免安装版),选择MYSQL Community Server 然 ...
- L2-016. 愿天下有情人都是失散多年的兄妹(深搜)*
L2-016. 愿天下有情人都是失散多年的兄妹 参考博客 #include<iostream> #include<cstdio> #include<cstring> ...
- 小组互评Alpha版本
Thunder——爱阅app(测评人:任思佳) 一.基于NABCD评论作品,及改进建议 每个小组评论其他小组Alpha发布的作品:1.根据(不限于)NABCD评论作品的选题:2.评论作品对选题的实现效 ...
- AFN 二次封装
#import "YQDataManager.h" #import <YYModel/YYModel.h> #pragma mark - 数据model基类 @impl ...
- linux下设置mysql5.7数据库远程访问
1.在网上看了很多关于设置远程访问的方式,根本就不起作用,后来在网上看到有一篇文章终于解决了我的问题,在配置文件中 /etc/mysql/my.cnf : 2.编辑 vi /etc/mysql/mys ...
- 第一节《Git初始化》
创建版本库以及第一次提交 首先我看查看一下git的版本,本地的git是用的yum安装方式,如果想使用源码安装请参考官方文档. [root@git ~]# git --versiongit versio ...
- HTML5操作麦克风获取音频数据(WAV)的一些基础技能
基于HTML5的新特性,操作其实思路很简单. 首先通过navigator获取设备,然后通过设备监听语音数据,进行原始数据采集. 相关的案例比较多,最典型的就是链接:https://developer. ...