6.4.1配置Thymeleaf视图解析器
如果配置了多个视图解析器,没有指定顺序,可以使用按照返回的名字匹配package spittr.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
/**
* @version 版权 Copyright(c)2019
* @ClassName:
* @Descripton:
* @author: Shing
* @date: 2020-06-13 14:21
*/
//开启扫描,启用springmvc
@Configuration
@EnableWebMvc
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter {
/**
* 配置jsp视图解析器
* @return
*/
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
// resolver.setOrder(2);
resolver.setViewNames(new String[]{"views/*"}); //如果配置了多个视图解析器,没有指定顺序,可以使用按照返回的名字匹配
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
/**
* 配置静态资源的处理
* @param configurer
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/**
* thymeleaf视图解析器
* @param templateEngine
* @return
*/
@Bean
public ViewResolver thymeleafViewresolver(SpringTemplateEngine templateEngine){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
// viewResolver.setOrder(1);
viewResolver.setViewNames(new String[]{"templates/*"}); //如果配置了多个视图解析器,没有指定顺序,可以使用按照返回的名字匹配
return viewResolver;
}
/**
* 模版引擎
* @param templateResolver
* @return
*/
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
/**
* 模版解析器
* @return
*/
@Bean
public ITemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
}
6.4.2定义Thymeleaf模版
百度Thymeleaf语法吧!${}与*{}的区别:${}:变量表达式,它会解析为key为spittr的model属性*{}:选择表达式来自为知笔记(Wiz)