thymeleaf template engine, extracting common segments and internationalization

What is thymeleaf?

Thymeleaf is facing and independent web server environment of modern java template engine, capable of handling Html, xml, javascript, CSS or even plain text; designed to provide an elegant way to create a template highly maintainable;

Why Thymeleaf template engine?

springBoot official does not recommend the use of jsp, because the embedded Tomcat, jetty container does not support running in a jar in the form of jsp; springBoot provides a large number of template engine, including FreeMarker, Mastache, Thymeleaf and so on; and SpringBoot official recommended to use as a template engine Thymeleaf because thymeleaf provide the perfect support springMVC of;

How to use Thymeleaf template engine?

1. First, add Thymeleaf starter

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

2, HTML file should be placed classpath: under / templates / directory, Thymeleaf can automatically rendered;

3. Add the name space on the html page, there is a grammar tips when using thymeleaf;

<html xmlns:th="http://www.thymeleaf.org">

Use Thymeleaf template engine and into the public statement fragments

For example: In our real development, many of our pages have duplicate code, we can be both written to the common area, it is declared, and then be introduced at the desired page;

<html xmlns:th="http://www.thymeleaf.org">
<head lang="en" id="head">
    <meta charset="UTF-8">
    <title>梦学谷账单管理系统</title>
    <link rel="stylesheet" href="../css/public.css"/>
</head>
<body>
<!--头部-->
    <header class="publicHeader" id="header">
        <h1>梦学谷账单管理系统</h1>
        <div class="publicHeaderR">
            <p><span>下午好!</span><span style="color: #fff21b"> Admin</span> , 欢迎你!</p>
            <a href="login.html">退出</a>
        </div>
    </header>
<!--时间-->
    <section class="publicTime" id="public_time">
        <span id="time">2028010111:11  星期一</span>
        <a href="#">温馨提示:为了能正常浏览,请使用高版本浏览器!(IE10+</a>
    </section>

As we can see our head, header, publicTime use id made a statement, to be used when we can directly reference it;

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en" th:replace="main/public :: #head">

</head>
<body>
<!--头部-->
<header class="publicHeader" th:replace="main/public :: #header">

</header>
<!--时间-->
<section class="publicTime" th:replace="main/public :: #public_time">

</section>

: Note: when we declare them and the reference syntax should match
no longer need to fragment 1, when the segment is declared, when we introduced the former name with #;
statement: header.html

<div th:fragment="header_common">
这是th:fragment声明的公共片段
</div>

Quote:

<div th:replace="header :: header_common">
</div>

2, when we use the id selector declared public fragments, fragments need to add # in front of the name;
declare: header.html

<div  id="header_common">
这是id声明的公共片段
</div>

Quote:

<div th:replace="header :: #header_common">

</div>

Login page internationalization

1, the first to write an international profile, international content needs to be added to the configuration of the display;
(1) create a file named i18n package folder, "i18n" is an abbreviation for the word internationalization, including a total of 20 letters, i headed letters, n is the last letter;
(2) Second, we need to modify the file character encoding, otherwise the latter will be garbled;
Here Insert Picture Description

(3) and then a new i18n package at a resourceBundle file; Here Insert Picture Description
Here Insert Picture Description
(4) the name of the current basis of our international resource file is not the original message, so we need a global configuration file: modification application.properties in;

//这里我们要关闭thymeleaf缓存
spring.thymeleaf.cache=false
//然后指定包名的方式指定基础名
spring.messages.basename=i18n.login

(5) Finally, we need to get the value of property in the international login.html template pages by # {}; (Note: We are here to process the login form, submit a login request, transfers control to the control treatment, and to )

 <section class="loginCont">
        <!--在这个form表单之上我们添加一个if表达式,当其登录失误的时候对其进行处理-->
        <div th:if="${not #strings.isEmpty(msg)}"
        th:text="${msg}"
        style="color:red; margin-left: 130px"> <!--这里的话对控制层打印出的错误信息进行显示-->
        </div>
        <!--我们这里的话对login表单进行处理,提交一个login请求,把控制权交给控制器进行处理-->
        <form class="loginForm" th:action="@{/login}" th:method="post">

            <div class="inputbox">
                <label for="user" th:text="#{login.username}">Username</label>
                <input id="user" type="text" name="username" required/>
            </div>
            <div class="inputbox">
                <label for="mima" th:text="#{login.password}">Password</label>
                <input id="mima" type="password" name="password" required/>
            </div>
            <div class="subBtn">
                <input type="checkbox"/> [[#{login.remember}]]
            </div>
            <br/>
            <div class="subBtn">
                <input type="submit" th:value="#{login.submit}"/>
                <input type="reset" th:value="#{login.reset}"/>
            </div>
            <br/>
            <!--这里我们添加一个连接点击切换国际化-->
            <div style="margin-left: 100px;">
                <a th:href="@{/index.html(l='zh_CH')}">中文</a>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <a th:href="@{/index.html(l='en_US')}">English</a>
            </div>
        </form>
    </section>

Custom parser to switch international

/**
 * 自定义解析器来切换国际化
 * 然后再注入到容器中
 */
public class MyLocalResolver implements LocaleResolver {
    /**
     * 解析区域信息
     */
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        System.out.println("区域信息~");
        //请求头中的l参数值
        String l = httpServletRequest.getParameter("l");
        //获取浏览器上的区域信息
        Locale locale = httpServletRequest.getLocale();
        //获取当前操作系统默认的区域信息
//        Locale locale=Locale.getDefault();
        //参数有区域信息,则用参数里的区域信息
        if (!StringUtils.isEmpty(l)) {
            String[] split = l.split("_");
            //接收第一个参数为:获取语言代码zh/en,获取国家代码CN/US
            locale = new Locale(split[0], split[1]);
        }
        return locale;
//        return null;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

Then we replace the automatic configuration MVC region parser class;

@Bean
public LocaleResolver localeResolver() {
    return new MyLocalResolver();
}
Published 37 original articles · won praise 12 · views 3977

Guess you like

Origin blog.csdn.net/z19950712/article/details/104410861