Live-Server-6-Thymeleaf

Thymeleaf Profile

Thymeleaf is Java and modern template engine for Web server for. The main objective is to Thymeleaf way to the workflow template and HTML display correctly in the browser, and can be used as a prototype. You can handle HTML, XML, JavaScript, CSS and other text formats.

In short, the ability to add Thymeleaf is fixed a label (standard dialect) in text format such as HTML and Java code by placing Thymeleaf engine data, text and other information to the user and displayed on the label. (In HTML digging through Thymeleaf, the pit is filled in Java code)

Standard dialect

Thymeleaf syntax is customizable, the official standard syntax called the standard dialect, mainly by property th prefix.

  1. $ {...}: variable expression
${session.user.name}
复制代码

Variable expression can be used as a variable part

<span th:text="${user.name}" />
复制代码
  1. * {...}: selection expression
<div th:object="${book}">
  ...
  <span th:text="*{title}">...</span>
  ...
</div>
复制代码

It chose th: object attributes of the object.

  1. {...} #: message (the i18n) expression allows to retrieve a specific message context files from an external source (e.g. .properties) file. In the Spring program will automatically integrate with MessageSource mechanism of Spring.
<table>
  ...
  <th th:text="#{header.address.city}">...</th>
  <th th:text="#{header.address.country}">...</th>
  ...
</table>
复制代码
  1. @ {...}: link (URL) expression in the expression construct URL link and add useful information.
<a th:href="@{/login}">...</a>
复制代码
  1. {...} ~: fragment expression fragment expression is a simple way to represent labeled fragments and move it to the template.
<div th:insert="~{commons :: main}">...</div>
复制代码

Operators

Connecting string: + alternate text: $ {name} operations: + - * /% boolean negation:! Comparison operators:> <> = <= equality operator: = ==!

Thymeleaf 实 操

Add Jar package dependencies

In Maven pom.xml to add Thymeleaf dependence. Because the project is SpringBoot basis, so use with SpringBoot adapted thymeleaf.

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
复制代码

SpringMVC Configuration

Add Thymeleaf configuration SpringMVC configuration file.

#thymeleaf
spring.thymeleaf.mode=HTML5   //文本模式
spring.thymeleaf.encoding=UTF-8 //字符编码
spring.thymeleaf.content-type=text/html
复制代码

Create a template Thymeleaf

Thymeleaf templates can be HTML file, XML, etc. can also be a text format. HTML used here as an example.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>注册</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<div class="container">
    <form action="register" method="post" th:object="${user}">
        <input type="hidden" name="tocken" id="tocken"/>
        <h2>注 册</h2>
        <div class="form-group" th:if="${null != error}">
            <div class="alert alert-success text-center">
                <div th:utext="${error}"></div>
            </div>
        </div>
        <div class="form-group">
            <label for="name" class="sr-only">用 户 名</label>
            <input type="text" name="name" th:value="*{name}" class="form-control" placeholder="用户名"/>
        </div>
        <div class="form-group">
            <label for="email" class="sr-only">邮 箱</label>
            <input type="email" name="email" th:value="*{email}" class="form-control" id="email" placeholder="邮箱"/>
        </div>
        <div class="form-group">
            <label for="password" class="sr-only">密 码</label>
            <input type="password" name="password" class="form-control" placeholder="密码"/>
        </div>
        <div class="form-group">
            <input type="text" name="code" style="width: 50%; display: inline-block; margin-right: 10px;"
                   class="form-control" placeholder="请输入验证码"/>
            <img id="code" alt="验证码" src="/kaptcha"/>
        </div>
        <div class="form-group">
            <p>
                已有账号?
                <a href="login">登录</a>
            </p>
        </div>
        <div class="form-group">
            <input type="submit" value="注册" class="btn btn-primary"/>
        </div>
    </form>
</div>
</body>
</html>
复制代码

The above page is Thymeleaf in a registration form, first define th: object = "$ {user }", indicating that the form of the object is a User object, TH: value = " {name}", TH: = value " {} in Email", indicating the selection User object name, email attribute, and the input form, the values of these properties will incoming connection request service.

Creating the Controller

With templates, you need a controller to control the pit in the end what values ​​need to fill in the template, and this controller is the last article referred to the Controller.

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 提交注册表单注册
	 * 
	 * @param user
	 * @param result
	 * @param code
	 * @param request
	 * @return
	 */
	@RequestMapping(path = { "register" }, method = { RequestMethod.POST })
	public String register(@Validated(value = { Register.class }) @ModelAttribute User user, BindingResult result,
			String code, HttpServletRequest request) {
		request.setAttribute("user", user);
		if (result.hasErrors()) {
			request.setAttribute("error", "有错误");
			return "register";
		}
		try {
			user.setPhone("");
			user.setSex("保密");
			user.setArticles(0);
			user.setPassword(xxx);
			user.setRoleId(3);
			userService.register(user);
			return "redirect:/login";
		} catch (Exception e) {
			log.debug(e.getMessage());
			request.setAttribute("error", e.getMessage());
		}
		return "register";
	}
}
复制代码

In the above Controller, according to the incoming object registration, if the registration is successful jump to the login page, or by request.setAttribute ( "error", e.getMessage ()) This line of code, the information will be registered by the failure Thymeleaf template engine to fill the pit HTML page and displayed to the user.

So far Thymeleaf use roughly the end of the process, let's look at how to meet Thymeleaf java mail messages sent unified format.

Thymeleaf template Mail

Principle is Thymeleaf message template, an HTML page by the processing engine thymeleaf into a string, then this MessageHelper tool string class pages, e-mail sender, recipient mail, e-mail and other data encapsulation header, and then transmits JavaMail. HTML template files:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>Insert title here</title>
</head>
<body>
<table cellspacing="0" cellpadding="20">
    <tr>
        <td>
            <table width="500" cellspacing="0" cellpadding="1">
                <tr>
                    <td bgcolor="#FF8E00" align="left"
                        style="font-family:'lucida grande',tahoma,'bitstream vera sans',helvetica,sans-serif;line-height:150%;color:#FFF;font-size:24px;font-weight:bold;padding:4px">
                        LIVE
                    </td>
                    <th></th>
                </tr>
                <tr>
                    <td bgcolor="#FF8E00">
                        <table width="100%" cellspacing="0" bgcolor="#FFFFFF"
                               cellpadding="20">
                            <tr>
                                <td style="font-family:'lucida grande',tahoma,'bitstream vera sans',helvetica,sans-serif;line-height:150%;color:#000;font-size:14px;">
                                    亲爱的用户:
                                    <blockquote>
                                        <br/> <strong>欢迎使用LIVE直播APP<br/>该邮件为你提供用于注册的验证码。</strong><br/>
                                        <br/>
                                        <p>code</p>
                                        <br/>
                                    </blockquote>
                                    <br/> <br/>社区<br/>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</body>
</html>
复制代码

Send e-mail service categories:

@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String fromEmailAddr;
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Override
    public boolean sendEmail(String template, Map<String, String> map, String sendTo, String subject)
            throws MessagingException {
        log.debug("EmailServiceImpl.sendEmail()");
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        // 开启带附件true
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);
        IContext context = new Context();
        // 获取模板html代码
        String process = templateEngine.process(template, context);
        Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, String> next = iterator.next();
            process = process.replace(next.getKey(), next.getValue());
        }
        try {
            //封装邮件的发送方、接收方、标题、邮件内容
            messageHelper.setFrom(fromEmailAddr);
            messageHelper.setTo(sendTo);
            messageHelper.setSubject(subject);
            messageHelper.setText(process, true);
            javaMailSender.send(mailMessage);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }
}
复制代码

Then directly call the business method can be achieved to send mail:

emailService.sendEmail("code", map, email, "LIVE注册");
复制代码

Guess you like

Origin juejin.im/post/5d5d3bdc6fb9a06b244320b9
Recommended