Spring MVC集成模板引擎方法

一 Spring MVC的JSP集成

1 代码

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/classes/views/");
    viewResolver.setSuffix(".jsp");
    viewResolver.setViewClass(JstlView.class);  //使用JstlView定义了一个InternalResourceViewResolver
    return viewResolver;
}

二 Spring MVC的Thymeleaf集成

1 说明

要在Spring中使用Thymeleaf,我们需要配置三个启用Thymeleaf与Spring集成的bean:

  • ThymeleafViewResolver:将逻辑视图名称解析为Thymeleaf模板视图

  • SpringTemplateEngine:处理模板并渲染结果

  • TemplateResolver:加载Thymeleaf模板

2 代码

@Bean      //Thymeleaf视图解析器
public ViewResolver viewResolver(SpringTemplateEngine templateEngine){
    ThymeleafViewResolver ViewResolver = new ThymeleafViewResolver();
    ViewResolver.setTemplateEngine(templateEngine);
    return viewResolver;
}
@Bean    //模板引擎
public TemplateEngine templateEngine(TemplateResolver templateResolver){
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    return templateEngine;
}
@Bean
public TemplateResolver templateResolver(){          //模板解析器
    TemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResovler.setPrefix("/WEB-INF/templates/");
    templateResovler.setSufix(".html");
    templateResovler.setTemplateMode("HTML5");
    return templateResolver;
}

 

你可能感兴趣的:(Spring,MVC)