经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
Spring Boot thymeleaf模板引擎的使用详解
来源:jb51  时间:2021/3/8 13:36:12  对本文有异议

在早期开发的时候,我们完成的都是静态页面也就是html页面,随着时间轴的发展,慢慢的引入了jsp页面,当在后端服务查询到数据之后可以转发到jsp页面,可以轻松的使用jsp页面来实现数据的显示及交互,jsp有非常强大的功能,但是,在使用springboot的时候,整个项目是以jar包的方式运行而不是war包,而且还嵌入了tomcat容器,因此,在默认情况下是不支持jsp页面的。如果直接以纯静态页面的方式会给我们的开发带来很大的麻烦,springboot推荐使用模板引擎。

模板引擎有很多种,jsp,freemarker,thymeleaf,模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,我们来组装一些数据,我们把这些数据找到。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过不同的模板引擎语法不同而已,下面重点学习下springboot推荐使用的thymeleaf模板引擎,语法简单且功能强大

1、thymeleaf的介绍

官网地址:https://www.thymeleaf.org/

thymeleaf在github的地址:https://github.com/thymeleaf/thymeleaf

中文网站:https://raledong.gitbooks.io/using-thymeleaf/content/

导入依赖:

  1. <!--thymeleaf模板-->
  2. <dependency>
  3. <groupId>org.thymeleaf</groupId>
  4. <artifactId>thymeleaf-spring5</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.thymeleaf.extras</groupId>
  8. <artifactId>thymeleaf-extras-java8time</artifactId>
  9. </dependency>

在springboot中有专门的thymeleaf配置类:ThymeleafProperties

  1. @ConfigurationProperties(prefix = "spring.thymeleaf")
  2. public class ThymeleafProperties {
  3. private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
  4. public static final String DEFAULT_PREFIX = "classpath:/templates/";
  5. public static final String DEFAULT_SUFFIX = ".html";
  6. /**
  7. * Whether to check that the template exists before rendering it.
  8. */
  9. private boolean checkTemplate = true;
  10. /**
  11. * Whether to check that the templates location exists.
  12. */
  13. private boolean checkTemplateLocation = true;
  14. /**
  15. * Prefix that gets prepended to view names when building a URL.
  16. */
  17. private String prefix = DEFAULT_PREFIX;
  18. /**
  19. * Suffix that gets appended to view names when building a URL.
  20. */
  21. private String suffix = DEFAULT_SUFFIX;
  22. /**
  23. * Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
  24. */
  25. private String mode = "HTML";
  26. /**
  27. * Template files encoding.
  28. */
  29. private Charset encoding = DEFAULT_ENCODING;
  30. /**
  31. * Whether to enable template caching.
  32. */
  33. private boolean cache = true;

2、thymeleaf使用模板

在java代码中写入如下代码:

  1. @RequestMapping("/hello")
  2. public String hello(Model model){
  3. model.addAttribute("msg","Hello");
  4. //classpath:/templates/hello.html
  5. return "hello";
  6. }

html页面中写入如下代码:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <body>
  4. <h1>Hello</h1>
  5. <div th:text="${msg}"></div>
  6. </body>
  7. </html>

3、thymeleaf的表达式语法

  1. Simple expressions:
  2. Variable Expressions: ${...}
  3. Selection Variable Expressions: *{...}
  4. Message Expressions: #{...}
  5. Link URL Expressions: @{...}
  6. Fragment Expressions: ~{...}
  7. Literals
  8. Text literals: 'one text', 'Another one!',…
  9. Number literals: 0, 34, 3.0, 12.3,…
  10. Boolean literals: true, false
  11. Null literal: null
  12. Literal tokens: one, sometext, main,…
  13. Text operations:
  14. String concatenation: +
  15. Literal substitutions: |The name is ${name}|
  16. Arithmetic operations:
  17. Binary operators: +, -, *, /, %
  18. Minus sign (unary operator): -
  19. Boolean operations:
  20. Binary operators: and, or
  21. Boolean negation (unary operator): !, not
  22. Comparisons and equality:
  23. Comparators: >, <, >=, <= (gt, lt, ge, le)
  24. Equality operators: ==, != (eq, ne)
  25. Conditional operators:
  26. If-then: (if) ? (then)
  27. If-then-else: (if) ? (then) : (else)
  28. Default: (value) ?: (defaultvalue)
  29. Special tokens:
  30. No-Operation: _

4、thymeleaf实例演示

1、th的常用属性值

​一、th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7

​二、th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6

​三、th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2

​四、th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3

​五、th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1

​六、th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8

​七、th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4

​八、th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5

thymeleaf.html

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <p th:text="${thText}"></p>
  9. <p th:utext="${thUText}"></p>
  10. <input type="text" th:value="${thValue}">
  11. <div th:each="message:${thEach}">
  12. <p th:text="${message}"></p>
  13. </div>
  14. <div>
  15. <p th:text="${message}" th:each="message:${thEach}"></p>
  16. </div>
  17. <p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p>
  18. <div th:object="${thObject}">
  19. <p>name:<span th:text="*{name}"/></p>
  20. <p>age:<span th:text="*{age}"/></p>
  21. <p>gender:<span th:text="*{gender}"/></p>
  22. </div>
  23.  
  24. </body>
  25. </html>

ThymeleafController.java

  1. import org.springframework.stereotype.Controller;
  2. import org.springframework.ui.ModelMap;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4.  
  5. @Controller
  6. public class ThymeleafController {
  7.  
  8. @RequestMapping("thymeleaf")
  9. public String thymeleaf(ModelMap map){
  10.  
  11. map.put("thText","th:text设置文本内容 <b>加粗</b>");
  12. map.put("thUText","th:utext 设置文本内容 <b>加粗</b>");
  13. map.put("thValue","thValue 设置当前元素的value值");
  14. map.put("thEach","Arrays.asList(\"th:each\", \"遍历列表\")");
  15. map.put("thIf","msg is not null");
  16. map.put("thObject",new Person("zhangsan",12,"男"));
  17. return "thymeleaf";
  18. }
  19. }

2、标准表达式语法

​${...} 变量表达式,Variable Expressions

​*{...} 选择变量表达式,Selection Variable Expressions

​一、可以获取对象的属性和方法

​二、可以使用ctx,vars,locale,request,response,session,servletContext内置对象

  1. session.setAttribute("user","zhangsan");
  2. th:text="${session.user}"

​三、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法

standardExpression.html

  1. <!--
  2. 一、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
  3.  
  4. 二、numbers:数值格式化方法,常用的方法有:formatDecimal等
  5.  
  6. 三、bools:布尔方法,常用的方法有:isTrue,isFalse等
  7.  
  8. 四、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
  9.  
  10. 五、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
  11.  
  12. 六、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
  13.  
  14. 七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等
  15. -->
  16. <!DOCTYPE html>
  17. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  18. <head>
  19. <meta charset="UTF-8">
  20. <title>thymeleaf内置方法</title>
  21. </head>
  22. <body>
  23. <h3>#strings </h3>
  24. <div th:if="${not #strings.isEmpty(Str)}" >
  25. <p>Old Str : <span th:text="${Str}"/></p>
  26. <p>toUpperCase : <span th:text="${#strings.toUpperCase(Str)}"/></p>
  27. <p>toLowerCase : <span th:text="${#strings.toLowerCase(Str)}"/></p>
  28. <p>equals : <span th:text="${#strings.equals(Str, 'blog')}"/></p>
  29. <p>equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(Str, 'blog')}"/></p>
  30. <p>indexOf : <span th:text="${#strings.indexOf(Str, 'r')}"/></p>
  31. <p>substring : <span th:text="${#strings.substring(Str, 2, 4)}"/></p>
  32. <p>replace : <span th:text="${#strings.replace(Str, 'it', 'IT')}"/></p>
  33. <p>startsWith : <span th:text="${#strings.startsWith(Str, 'it')}"/></p>
  34. <p>contains : <span th:text="${#strings.contains(Str, 'IT')}"/></p>
  35. </div>
  36. <h3>#numbers </h3>
  37. <div>
  38. <p>formatDecimal 整数部分随意,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(Num, 0, 2)}"/></p>
  39. <p>formatDecimal 整数部分保留五位数,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(Num, 5, 2)}"/></p>
  40. </div>
  41.  
  42. <h3>#bools </h3>
  43. <div th:if="${#bools.isTrue(Bool)}">
  44. <p th:text="${Bool}"></p>
  45. </div>
  46.  
  47. <h3>#arrays </h3>
  48. <div th:if="${not #arrays.isEmpty(Array)}">
  49. <p>length : <span th:text="${#arrays.length(Array)}"/></p>
  50. <p>contains : <span th:text="${#arrays.contains(Array,2)}"/></p>
  51. <p>containsAll : <span th:text="${#arrays.containsAll(Array, Array)}"/></p>
  52. </div>
  53. <h3>#lists </h3>
  54. <div th:if="${not #lists.isEmpty(List)}">
  55. <p>size : <span th:text="${#lists.size(List)}"/></p>
  56. <p>contains : <span th:text="${#lists.contains(List, 0)}"/></p>
  57. <p>sort : <span th:text="${#lists.sort(List)}"/></p>
  58. </div>
  59. <h3>#maps </h3>
  60. <div th:if="${not #maps.isEmpty(hashMap)}">
  61. <p>size : <span th:text="${#maps.size(hashMap)}"/></p>
  62. <p>containsKey : <span th:text="${#maps.containsKey(hashMap, 'thName')}"/></p>
  63. <p>containsValue : <span th:text="${#maps.containsValue(hashMap, '#maps')}"/></p>
  64. </div>
  65. <h3>#dates </h3>
  66. <div>
  67. <p>format : <span th:text="${#dates.format(Date)}"/></p>
  68. <p>custom format : <span th:text="${#dates.format(Date, 'yyyy-MM-dd HH:mm:ss')}"/></p>
  69. <p>day : <span th:text="${#dates.day(Date)}"/></p>
  70. <p>month : <span th:text="${#dates.month(Date)}"/></p>
  71. <p>monthName : <span th:text="${#dates.monthName(Date)}"/></p>
  72. <p>year : <span th:text="${#dates.year(Date)}"/></p>
  73. <p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(Date)}"/></p>
  74. <p>hour : <span th:text="${#dates.hour(Date)}"/></p>
  75. <p>minute : <span th:text="${#dates.minute(Date)}"/></p>
  76. <p>second : <span th:text="${#dates.second(Date)}"/></p>
  77. <p>createNow : <span th:text="${#dates.createNow()}"/></p>
  78. </div>
  79. </body>
  80. </html>

ThymeleafController.java

  1. @RequestMapping("standardExpression")
  2. public String standardExpression(ModelMap map){
  3. map.put("Str", "Blog");
  4. map.put("Bool", true);
  5. map.put("Array", new Integer[]{1,2,3,4});
  6. map.put("List", Arrays.asList(1,3,2,4,0));
  7. Map hashMap = new HashMap();
  8. hashMap.put("thName", "${#...}");
  9. hashMap.put("desc", "变量表达式内置方法");
  10. map.put("Map", hashMap);
  11. map.put("Date", new Date());
  12. map.put("Num", 888.888D);
  13. return "standardExpression";
  14. }

​@{...} 链接表达式,Link URL Expressions

  1. <!--
  2. 不管是静态资源的引用,form表单的请求,凡是链接都可以用@{...} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问
  3. 链接表达式结构
  4. 无参:@{/xxx}
  5. 有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2
  6. 引入本地资源:@{/项目本地的资源路径}
  7. 引入外部资源:@{/webjars/资源在jar包中的路径}
  8. -->
  9. <link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="external nofollow" rel="stylesheet">
  10. <link th:href="@{/main/css/123.css}" rel="external nofollow" rel="stylesheet">
  11. <form class="form-login" th:action="@{/user/login}" th:method="post" >
  12. <a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}" rel="external nofollow" >中文</a>
  13. <a class="btn btn-sm" th:href="@{/login.html(l='en_US')}" rel="external nofollow" >English</a>

​#{...} 消息表达式,Message Expressions

  1. <!--
  2. 消息表达式一般用于国际化的场景。结构:th:text="#{msg}"
  3. -->

​~{...} 代码块表达式,Fragment Expressions

fragment.html

  1. <!--
  2. 支持两种语法结构
  3. 推荐:~{templatename::fragmentname}
  4. 支持:~{templatename::#id}
  5. templatename:模版名,Thymeleaf会根据模版名解析完整路:/resources/templates/templatename.html,要注意文件的路径。
  6. fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment="fragmentname"
  7. id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。
  8.  
  9. 代码块表达式的使用
  10. 代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。
  11. th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,
  12. th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,
  13. th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中,
  14. -->
  15. <!DOCTYPE html>
  16. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  17. <head>
  18. <meta charset="UTF-8">
  19. <title>Title</title>
  20. </head>
  21. <body>
  22. <!--th:fragment定义代码块标识-->
  23. <footer th:fragment="copy">
  24. 2019 The Good Thymes Virtual Grocery
  25. </footer>
  26.  
  27. <!--三种不同的引入方式-->
  28. <div th:insert="fragment::copy"></div>
  29. <div th:replace="fragment::copy"></div>
  30. <div th:include="fragment::copy"></div>
  31.  
  32. <!--th:insert是在div中插入代码块,即多了一层div-->
  33. <div>
  34. <footer>
  35. &copy; 2011 The Good Thymes Virtual Grocery
  36. </footer>
  37. </div>
  38. <!--th:replace是将代码块代替当前div,其html结构和之前一致-->
  39. <footer>
  40. &copy; 2011 The Good Thymes Virtual Grocery
  41. </footer>
  42. <!--th:include是将代码块footer的内容插入到div中,即少了一层footer-->
  43. <div>
  44. &copy; 2011 The Good Thymes Virtual Grocery
  45. </div>
  46. </body>
  47. </html>

5、国际化的配置

​在很多应用场景下,我们需要实现页面的国际化,springboot对国际化有很好的支持, 下面来演示对应的效果。

1、在idea中设置统一的编码格式,file->settings->Editors->File Encoding,选择编码格式为utf-8

2、在resources资源文件下创建一个i8n的目录,创建一个login.properties的文件,还有login_zh_CN.properties,idea会自动识别国际化操作

3、创建三个不同的文件,名称分别是:login.properties,login_en_US.properties,login_zh_CN.properties

内容如下:

  1. #login.properties
  2. login.password=密码1
  3. login.remmber=记住我1
  4. login.sign=登录1
  5. login.username=用户名1
  6. #login_en_US.properties
  7. login.password=Password
  8. login.remmber=Remember Me
  9. login.sign=Sign In
  10. login.username=Username
  11. #login_zh_CN.properties
  12. login.password=密码~
  13. login.remmber=记住我~
  14. login.sign=登录~
  15. login.username=用户名~

4、配置国际化的资源路径

  1. spring:
  2. messages:
  3. basename: i18n/login

5、编写html页面

  1. 初始html页面
  2. <!DOCTYPE html>
  3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5. <meta charset="UTF-8"/>
  6. <title>Title</title>
  7. </head>
  8. <body>
  9. <form action="" method="post">
  10.  
  11. <label >Username</label>
  12. <input type="text" name="username" placeholder="Username" >
  13. <label >Password</label>
  14. <input type="password" name="password" placeholder="Password" >
  15. <br> <br>
  16. <div>
  17. <label>
  18. <input type="checkbox" value="remember-me"/> Remember Me
  19. </label>
  20. </div>
  21. <br>
  22. <button type="submit">Sign in</button>
  23. <br> <br>
  24. <a>中文</a>
  25. <a>English</a>
  26. </form>
  27. </body>
  28. </html>
  29.  
  30. 修改后的页面
  31. <!DOCTYPE html>
  32. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  33. <head>
  34. <meta charset="UTF-8"/>
  35. <title>Title</title>
  36. </head>
  37. <body>
  38. <form action="" method="post">
  39. <label th:text="#{login.username}">Username</label>
  40. <input type="text" name="username" placeholder="Username" th:placeholder="#{login.username}">
  41. <label th:text="#{login.password}">Password</label>
  42. <input type="password" name="password" placeholder="Password" th:placeholder="#{login.password}">
  43. <br> <br>
  44. <div>
  45. <label>
  46. <input type="checkbox" value="remember-me"/> [[#{login.remmber}]]
  47. </label>
  48. </div>
  49. <br>
  50. <button type="submit" th:text="#{login.sign}">Sign in</button>
  51. <br> <br>
  52. <a>中文</a>
  53. <a>English</a>
  54. </form>
  55. </body>
  56. </html>

可以看到通过浏览器的切换语言已经能够实现,想要通过超链接实现的话,如下所示:

添加WebMVCConfig.java代码

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.util.StringUtils;
  4. import org.springframework.web.servlet.LocaleResolver;
  5. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  6. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  7.  
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import java.util.Locale;
  11.  
  12. @Configuration
  13. public class WebMVCConfig implements WebMvcConfigurer {
  14.  
  15. @Override
  16. public void addViewControllers(ViewControllerRegistry registry) {
  17. registry.addViewController("/").setViewName("login");
  18. registry.addViewController("/login.html").setViewName("login");
  19. }
  20.  
  21. @Bean
  22. public LocaleResolver localeResolver(){
  23. return new NativeLocaleResolver();
  24. }
  25.  
  26. protected static class NativeLocaleResolver implements LocaleResolver{
  27.  
  28. @Override
  29. public Locale resolveLocale(HttpServletRequest request) {
  30. String language = request.getParameter("language");
  31. Locale locale = Locale.getDefault();
  32. if(!StringUtils.isEmpty(language)){
  33. String[] split = language.split("_");
  34. locale = new Locale(split[0],split[1]);
  35. }
  36. return locale;
  37. }
  38.  
  39. @Override
  40. public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
  41.  
  42. }
  43. }
  44. }

login.html页面修改为:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <form action="" method="post">
  9. <label th:text="#{login.username}">Username</label>
  10. <input type="text" name="username" placeholder="Username" th:placeholder="#{login.username}">
  11. <label th:text="#{login.password}">Password</label>
  12. <input type="password" name="password" placeholder="Password" th:placeholder="#{login.password}">
  13. <br> <br>
  14. <div>
  15. <label>
  16. <input type="checkbox" value="remember-me"/> [[#{login.remmber}]]
  17. </label>
  18. </div>
  19. <br>
  20. <button type="submit" th:text="#{login.sign}">Sign in</button>
  21. <br> <br>
  22. <a th:href="@{/login.html(language='zh_CN')}" rel="external nofollow" >中文</a>
  23. <a th:href="@{/login.html(language='en_US')}" rel="external nofollow" >English</a>
  24. </form>
  25. </body>
  26. </html>

国际化的源码解释:

  1. //MessageSourceAutoConfiguration
  2. public class MessageSourceAutoConfiguration {
  3. private static final Resource[] NO_RESOURCES = new Resource[0];
  4.  
  5. public MessageSourceAutoConfiguration() {
  6. }
  7.  
  8. @Bean
  9. @ConfigurationProperties(prefix = "spring.messages") //我们的配置文件可以直接放在类路径下叫: messages.properties, 就可以进行国际化操作了
  10. public MessageSourceProperties messageSourceProperties() {
  11. return new MessageSourceProperties();
  12. }
  13.  
  14. @Bean
  15. public MessageSource messageSource(MessageSourceProperties properties) {
  16. ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
  17. if (StringUtils.hasText(properties.getBasename())) {
  18.         //设置国际化文件的基础名(去掉语言国家代码的)
  19. messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
  20. }
  21.  
  22. if (properties.getEncoding() != null) {
  23. messageSource.setDefaultEncoding(properties.getEncoding().name());
  24. }
  25.  
  26. messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
  27. Duration cacheDuration = properties.getCacheDuration();
  28. if (cacheDuration != null) {
  29. messageSource.setCacheMillis(cacheDuration.toMillis());
  30. }
  31.  
  32. messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
  33. messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
  34. return messageSource;
  35. }
  36. }
  37.  
  38.  
  39. //WebMvcAutoConfiguration
  40. @Bean
  41. @ConditionalOnMissingBean
  42. @ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
  43. public LocaleResolver localeResolver() {
  44. if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
  45. return new FixedLocaleResolver(this.mvcProperties.getLocale());
  46. }
  47. AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
  48. localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
  49. return localeResolver;
  50. }
  51.  
  52. //AcceptHeaderLocaleResolver
  53. @Override
  54. public Locale resolveLocale(HttpServletRequest request) {
  55. Locale defaultLocale = getDefaultLocale();
  56. if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
  57. return defaultLocale;
  58. }
  59. Locale requestLocale = request.getLocale();
  60. List<Locale> supportedLocales = getSupportedLocales();
  61. if (supportedLocales.isEmpty() || supportedLocales.contains(requestLocale)) {
  62. return requestLocale;
  63. }
  64. Locale supportedLocale = findSupportedLocale(request, supportedLocales);
  65. if (supportedLocale != null) {
  66. return supportedLocale;
  67. }
  68. return (defaultLocale != null ? defaultLocale : requestLocale);
  69. }

到此这篇关于Spring Boot thymeleaf模板引擎的使用详解的文章就介绍到这了,更多相关Spring Boot thymeleaf模板引擎内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号