对DispatcherServlet进行配置
Spring MVC的配置实际上就是对DispatcherServlet的配置
public class DispatcherServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses() // 加载自定义的配置类
{
return new Class<?>[]{BeanConfig.class, SecurityConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() // 加载web配置类,如viewResolver
{
return new Class<?>[]{WebConfig.class};
}
@Override
protected String[] getServletMappings()
{
return new String[]{"/"};
}
}
WebConfig的实现
@Configuration
@EnableWebMvc // 在此开启WebMvc
@ComponentScan(basePackageClasses = {BasePackageMarker.class})
public class WebConfig extends WebMvcConfigurerAdapter
{
@Bean
public ViewResolver viewResolver(TemplateEngine templateEngine)
{
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
@Bean
public TemplateEngine templateEngine(ITemplateResolver templateResolver)
{
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
@Bean
public ITemplateResolver templateResolver()
{
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setCacheable(false);
return templateResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}