2018-03-14
springboot-集成velocity
springboot 评论:0 浏览:763

转载请注明出处:https://oldnoop.tech/c/171.html

springboot1.5.x版本不支持velocity

springboot在1.4.x的版本还提供velocity的支持,

引入起步依赖spring-boot-starter-velocity即可

springboot在1.5.x的版本去掉了velocity的支持,

不可以再通过起步依赖spring-boot-starter-velocity来集成

springboot选择何种版本

查看druid的官网,

druid提供的springboot支持的起步依赖druid-spring-boot-starter

最低版本1.1.0,要求的springboot的最低版本是1.5.3

选择springboot的1.5.x的版本

springboot1.5.x版本集成velocity

springboot提供的velocity的起步依赖spring-boot-starter-velocity,

只是简化了集成velocity的方式,

不使用它,也可以通过手动配置的方式,来集成velocity

单独引入velocity的依赖

引入spring-context-support的依赖

单独引入velocity的依赖,就不能像spring-boot-starter-velocity起步依赖那样,

引入需要的spring-context-support,所以需要单独引入这个依赖

配置velocity

配置velocity.properties

在src/main/resources下新建文件velocity.properties,配置如下内容

#设置字符集›†
input.encoding=UTF-8
output.encoding=UTF-8
contentType=text/html;charset=UTF-8

在src/main/resources下的templates文件夹下创建文件夹view,

存放velocity视图文件

配置velocity

这里是关键,通过编码式配置的方式

配置VelocityConfigurer,VelocityViewResolver

编写springmvc的配置类,继承VelocityViewResolver,在类上添加注解@Configuration

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
    //配置velocity配置bean
    @SuppressWarnings("deprecation")
    @Bean
    public VelocityConfigurer velocityConfigurer(ApplicationContext context) {
        VelocityConfigurer config = new VelocityConfigurer();
        config.setConfigLocation(new ClassPathResource("velocity.properties"));
        return config;
    }

    //配置velocity视图解析器
    @SuppressWarnings("deprecation")
    @Bean
    public VelocityViewResolver velocityResolver() {
        VelocityViewResolver resolver = new VelocityViewResolver();
        resolver.setCache(false);
        //设置视图路径前缀
        resolver.setPrefix("/templates/view/");
        //设置视图路径后缀
        resolver.setSuffix(".vm");
        resolver.setContentType("text/html;charset=UTF-8");
        resolver.setExposeSpringMacroHelpers(true);
        resolver.setExposeRequestAttributes(true);
        //设置RequestContext在视图页面中的变量名,以便使用${request}获取
        resolver.setRequestContextAttribute("request");
        return resolver;
    }

}

 



  • 转载请注明出处:https://oldnoop.tech/c/171.html

Copyright © 2018 oldnoop.tech. All Rights Reserved

鄂ICP备2023022735号-1