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

  • 相关阅读:
    linux使用docker-compose部署软件配置
    Linux CentOS Python开发环境搭建教程
    Linux使用scp命令进行文件远程拷贝详解
    浅析Vue.js 中的条件渲染指令
    浅谈Vue响应式(数组变异方法)
    Laravel框架定时任务2种实现方式示例
    Docker 运行时的用户与组管理的方法
    laravel5实现微信第三方登录功能
    Linux服务器间文件实时同步的实现
    从零开始搭建vue移动端项目到上线的步骤
  • 原文地址:https://www.cnblogs.com/gzhjj/p/13385306.html
Copyright © 2011-2022 走看看