发表文章

[最新] springMVC多视图解析器配置

u011528917 1月前 8

需求是项目中同时使用html,jsp,freemarker,即freemarker可以生成html,也可以直接渲染页面返回视图。
在这种情况下,共需要配置三个视图解析器,这里我选择了两个freemarkerViewResolver,一个internalResourceViewResolver,原因是internalRrsourceViewResolver只能选择一个,该视图解析器不会返回空,会返回一个默认值,也就是说在找不到视图的情况下,会直接报404而不是进入下一级视图解析器,所以针对该视图解析器我们直接配置Ordered.LOWEST_PRECEDENCE即可。
下面是下我的demo:
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer(){
    FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
    //freeMarkerConfigurer.setTemplateLoaderPath("WEB-INF/ftl");
    freeMarkerConfigurer.setDefaultEncoding("UTF-8");
    freeMarkerConfigurer.setFreemarkerVariables(Collections.singletonMap("xml_escape",xmlEscape()));
    //这里需要设为空,前缀分别在html和freemarker视图解析器中设置即可,不需要在这里设置
    freeMarkerConfigurer.setTemplateLoaderPath("");
    Properties properties = new Properties();
    properties.setProperty("locale","zh_CN");
    properties.setProperty("datetime_format","yyyy-MM-dd HH:mm:SS");
    properties.setProperty("date_format","yyyy-MM-dd");
    properties.setProperty("number_format","#.##");
    //设置模板刷新时间,为0时不从缓存读取
    properties.setProperty("template_update_delay","30000");
    freeMarkerConfigurer.setFreemarkerSettings(properties);
    return freeMarkerConfigurer;
}

/**
 * 转义字符支持
 * @return 转义字符支持类
 */
private XmlEscape xmlEscape(){
    return new XmlEscape();
}

/**
 * html视图解析器
 * @return InternalResourceViewResolver
 */
@Bean
public FreeMarkerViewResolver htmlViewResolver(){
    FreeMarkerViewResolver htmlViewResolver = new FreeMarkerViewResolver();
    htmlViewResolver.setPrefix("WEB-INF/views/html/");
    htmlViewResolver.setSuffix(".html");
    htmlViewResolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
    htmlViewResolver.setContentType("text/html;charset=UTF-8");
    return htmlViewResolver;
}

/**
 * freemarker视图解析器
 * @return FreeMarkerViewResolver
 */
@Bean
public FreeMarkerViewResolver freeMarkerViewResolver(){
    FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
    freeMarkerViewResolver.setPrefix("WEB-INF/views/ftl/");
    freeMarkerViewResolver.setSuffix(".ftl");
    freeMarkerViewResolver.setCache(true);
    freeMarkerViewResolver.setContentType("text/html;charset=UTF-8");
    freeMarkerViewResolver.setOrder(2);
    return freeMarkerViewResolver;
}

/**
 * jsp视图解析器
 * @return InternalResourceViewResolver
 */
@Bean
public InternalResourceViewResolver jspViewResolver(){
    InternalResourceViewResolver jspViewResolver = new InternalResourceViewResolver();
    jspViewResolver.setViewClass(JstlView.class);
    jspViewResolver.setPrefix("WEB-INF/views/jsp/");
    jspViewResolver.setSuffix(".jsp");
    jspViewResolver.setOrder(Ordered.LOWEST_PRECEDENCE);
    return jspViewResolver;
}
**重点是freeMarkerConfigurer.setTemplateLoaderPath("");**
如果不写这项配置则html和freemarker视图解析器匹配一定会失败,一定要设置路径,这里设置为空,前缀在html和freemarker视图解析器中配置即可。
相关推荐
最新评论 (0)
返回
发表文章
u011528917
文章数
3
评论数
0
注册排名
586805