ライブサーバー-6-Thymeleaf

Thymeleafプロフィール

Thymeleafは、JavaとのためのWebサーバのための現代的なテンプレートエンジンです。主な目的は、ワークフローテンプレートとブラウザで正しくHTML表示にThymeleafの道にあり、プロトタイプとして使用することができます。あなたは、HTML、XMLやJavaScript、CSSおよびその他のテキストフォーマットを扱うことができます。

要するに、Thymeleafを追加する機能は、ユーザにThymeleafエンジンデータ、テキストおよびその他の情報を配置することによって、このようなHTMLおよびJavaコードのようなテキスト形式のラベル(標準方言)に固定されており、ラベルに表示されます。(HTMLはThymeleafを通して掘削では、ピットはJavaコードで充填されています)

標準の方言

Thymeleaf構文は、公式の標準構文は、主に接頭辞番目のプロパティによって、標準の方言と呼ばれる、カスタマイズ可能です。

  1. $ {...}:変数式
${session.user.name}
复制代码

変数式は、可変部として使用することができます

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

オブジェクトのオブジェクト属性:それは目を選びました。

  1. {...}#:メッセージ(I18N)の発現は、外部ソース(例えば.propertiesファイル)ファイルから特定のメッセージコンテキストファイルを取得することを可能にします。春のプログラムで自動的に春のMessageSource機構を統合します。
<table>
  ...
  <th th:text="#{header.address.city}">...</th>
  <th th:text="#{header.address.country}">...</th>
  ...
</table>
复制代码
  1. @ {...}:式のリンク(URL)の発現は、URLリンクを構築し、有用な情報を追加します。
<a th:href="@{/login}">...</a>
复制代码
  1. {...}〜:断片発現断片発現は、標識された断片を表し、テンプレートに移動する簡単な方法です。
<div th:insert="~{commons :: main}">...</div>
复制代码

演算子

接続文字列:+代替テキスト:$ {名前}操作:+ - * /%ブール否定:! 比較演算子:> <> = <=等価演算子:= ==!

Thymeleaf实操

ジャーパッケージの依存関係を追加します。

Mavenののpom.xmlでThymeleaf依存性を追加します。プロジェクトはSpringBootの基礎となっているので、そうthymeleafを適応SpringBootで使用しています。

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

SpringMVCの設定

Thymeleaf設定SpringMVCの設定ファイルを追加します。

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

テンプレートThymeleafを作成します。

Thymeleafのテンプレートは、HTMLなどのファイル、XML、することができ、テキスト形式することができます。HTMLは、一例として、ここで使用します。

<!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>
复制代码

オブジェクト=「$ {ユーザーを:上記ページが最初に目を定義、登録フォームでThymeleafあり 、}」 オブジェクトの形が、THユーザオブジェクトであることを示す:値=「{名前}」、TH: =値「 {}メールで送信」、選択ユーザ・オブジェクト名、電子メールの属性、及び入力フォームを示し、意志着信接続要求サービスこれらのプロパティの値。

コントローラの作成

テンプレートを使用すると、値は、テンプレートを埋めるために必要なものを最後にピットを制御するためのコントローラを必要とし、このコントローラは、コントローラと呼ば前回の記事です。

@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";
	}
}
复制代码

上記コントローラは、入ってくるオブジェクト登録によれば、登録は、ログインページに、またはrequest.setAttribute(「エラー」、e.getMessage())このコード行によって成功したジャンプがある場合、情報は、障害によって登録されますThymeleafのテンプレートエンジンは、ピットHTMLページを記入し、ユーザに表示します。

これまでのところThymeleafはのは、Thymeleaf Javaのメールメッセージを満たす方法を見てみましょう、およそプロセスの終了を使用する統一フォーマットを送りました。

Thymeleafのテンプレートメール

原理は、文字列に処理エンジンthymeleafによってThymeleafメッセージテンプレート、HTMLページであり、このMessageHelperツールストリングクラスページ、電子メールの送信者、受信者メール、電子メールおよび他のデータ・カプセル化ヘッダ、およびその後のJavaMailを送信します。HTMLテンプレートファイル:

<!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>
复制代码

電子メールサービスのカテゴリを送ります:

@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;
    }
}
复制代码

そして、直接ビジネス方法は、メールを送信するために達成することができます呼び出します。

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

おすすめ

転載: juejin.im/post/5d5d3bdc6fb9a06b244320b9