在WebConfig中配置
@Configuration@EnableWebMvc@ComponentScan("com.mcs.Sgin.web") // 启用自动扫描public class WebConfig extends WebMvcConfigurerAdapter { // 配置Thymeleaf视图解析器 @Bean public ViewResolver viewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); // 在这里templateEngine()并不是直接调用这个类里的方法,它是Spring管理的bean。Spring会拦截所有对templateEngine()的调用 resolver.setCharacterEncoding("UTF-8"); return resolver; } @Bean public SpringTemplateEngine templateEngine() { // SpringTemplateEngine自动接受SpringStandardDialect and // 开启Spring信息源。 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 SpringResourceTemplateResolver templateResolver() { // SpringResourceTemplateResolver automatically integrates with Spring's own // resource resolution infrastructure, which is highly recommended. SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setPrefix("/WEB-INF/views/"); templateResolver.setSuffix(".html"); // HTML is the default value, added here for the sake of clarity. templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver; } // 配置静态资源的处理 @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { // TODO Auto-generated method stub configurer.enable(); }}
要点