zoukankan      html  css  js  c++  java
  • 解决SpringBoot项目中Thymeleaf模板的中文乱码问题

    1、使用IDEA创建SpringBoot项目




    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    
    @ComponentScan(basePackages="com.example")
    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }
    

    这里通过@ComponentScan(basePackages="com.example")来扫描包。

    package com.example.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
    
        @RequestMapping("/hello")
        public String index(){
            return "Hello Spring Boot^^^";
        }
    
    }
    

    2、导入Thymeleaf依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    

    3、读取properties文件

    # application.properties
    server.port=8080
    server.servlet.context-path=/demo
    spring.thymeleaf.cache=false
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.check-template-location=true
    spring.thymeleaf.suffix=.html
    spring.thymeleaf.encoding=UTF-8
    spring.thymeleaf.mode=HTML
    spring.messages.basename=i18/home
    

    # home.properties、home_zh_CN.properties
    welcome=欢迎您!
    
    # home_en_US.properties
    welcome=Welcome!
    
    package com.example.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class HelloController {
    
        @RequestMapping("/goToViewPage")
        public ModelAndView passParametersWithModelAndView() {
            ModelAndView modelAndView = new ModelAndView("viewPage");
            modelAndView.addObject("message", "Baeldung");
            return modelAndView;
        }
    
    }
    
    <!-- viewPage.html -->
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Thymeleaf测试</title>
    </head>
    <body>
    <P th:text="#{welcome}"></P>
    </body>
    </html>
    

    注意:properties文件的编码格式必须是UTF-8

  • 相关阅读:
    深度可分离卷积、分组卷积、空洞卷积、转置卷积
    Batch Normalization
    激活函数
    容器————vector
    39XML文档类
    38初识xml
    37QT程序打包
    36可视化操作数据库
    35使用模型操作数据库
    34sqlite
  • 原文地址:https://www.cnblogs.com/gzhjj/p/13385306.html
Copyright © 2011-2022 走看看