您的位置:首页 > 编程语言 > Java开发

Spring MVC 集成 Thymeleaf

2017-12-08 11:01 106 查看
使用不同的视图模板需要配置三个内容:

视图解析器,根据逻辑视图名解析正确的模板视图

模板引擎,处理模板视图并渲染结果

模板解析器,加载模板

注意:Thymeleaf 默认的 page encoding 不是 UTF-8,如果要使用UTF-8 编码页面,必须进行相关设置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.workfun.web")
public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

private ApplicationContext applicationContext;

public WebConfig() {
super();
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

//访问静态资源
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);        registry.addResourceHandler("/images/**").addResourceLocations("/images/");     registry.addResourceHandler("/css/**").addResourceLocations("/css/");       registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}

@Bean
public SpringResourceTemplateResolver templateResolver() {
// SpringResourceTemplateResolver automatically integrates with Spring's own
// resource resolution infrastructure, which is highly recommended.
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// HTML is the default value, added here for the sake of clarity.
templateResolver.setTemplateMode(TemplateMode.HTML);
// recource encoding
templateResolver.setCharacterEncoding("UTF-8");
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
templateResolver.setCacheable(true);
return templateResolver;
}

@Bean
public SpringTemplateEngine templateEngine() {
// SpringTemplateEngine automatically applies SpringStandardDialect and
// enables Spring's own MessageSource message resolution mechanisms.
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
// Enabling the SpringEL compiler with Spring 4.2.4 or newer can
// speed up execution in most scenarios, but might be incompatible
// with specific cases when expressions in one template are reused
// across different data types, so this flag is "false" by default
// for safer backwards compatibility.
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}

@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
// pageEncoding , very important
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息