(学习笔记)SpringMVC Web项目中Thymeleaf配置

三步

1.配置TemplateResolver

2.配置SpringTemplateEngine

3.配置ViewResolver

代码:

@Bean
public ViewResolver viewResolver(SpringTemplateEngine engine) {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setCharacterEncoding("UTF-8");//设置编码
    resolver.setTemplateEngine(engine);
    return resolver;
}

@Bean
public SpringTemplateEngine engine(TemplateResolver resolver) {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(resolver);
    return engine;
}

@Bean
public TemplateResolver templateResolver() {
    TemplateResolver resolver = new ServletContextTemplateResolver();
    resolver.setPrefix("/WEB-INF/templates/");
    resolver.setSuffix(".html");
    resolver.setCharacterEncoding("UTF-8");//设置编码
    resolver.setTemplateMode("HTML5");
    return resolver;
}

  页面的乱码问题可以通过TemplateResolver和ViewResolver的setCharacterEncoding方法解决。

基于XML的配置如下

xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:p="http://www.springframework.org/schema/p"
             xsi:schemaLocation="http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">

    
    
    <context:component-scan base-package="user"/>
    <beans:bean id="ViewResolver" class="org.thymeleaf.spring3.view.ThymeleafViewResolver"
                p:templateEngine-ref="templateEngine"
                p:characterEncoding="UTF-8"/>
    <beans:bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine"
                p:templateResolver-ref="templateResolver"/>
    <beans:bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"
                p:prefix="/WEB-INF/templates//"
                p:suffix=".html"
                p:characterEncoding="UTF-8"
                p:templateMode="HTML5"/>
    
beans:beans>


你可能感兴趣的:(Java)