Thymeleaf 3.0 自定義標(biāo)簽方言屬性的實(shí)例講解
此篇文章內(nèi)容僅限于 描述 thy3.0 自定義標(biāo)簽的說明,所以你在看之前,請先會(huì)使用它。
直奔主題,以下代碼是如何引用 第三方標(biāo)簽的。說明: shrioDialect 是Shiro 官方為thy開發(fā)的自定義標(biāo)簽工具。和jsp的一樣
RiskDialect 是我寫的自定義標(biāo)簽
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver"/>
<property name="additionalDialects">
<set>
<!-- thymeleaf 使用shiro標(biāo)簽 -->
<bean class="at.pollux.thymeleaf.shiro.dialect.ShiroDialect"/>
<bean class="com.hpay.risk.boss.common.RiskDialect"/>
</set>
</property>
</bean>
首先看代碼:
import java.util.LinkedHashSet;
import java.util.Set;
import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.StandardDialect;
/**
*@author Garc
*@Date 2017年2月16日 上午11:42:51
*@info thymeleaf 自定義標(biāo)簽屬性
*@snise
**/
public class RiskDialect extends AbstractProcessorDialect {
private static final String NAME = "Risk";
private static final String PREFIX = "risk";
public RiskDialect() {
super(NAME, PREFIX, StandardDialect.PROCESSOR_PRECEDENCE);
}
@Override
public Set<IProcessor> getProcessors(String dialectPrefix) {
return createStandardProcessorsSet(dialectPrefix);
}
private Set<IProcessor> createStandardProcessorsSet(String dialectPrefix) {
LinkedHashSet<IProcessor> processors = new LinkedHashSet<IProcessor>();
processors.add(new SansitiveEncryptProcessor(dialectPrefix));
return processors;
}
}
我定義了 RiskDialect 類,并需要繼承 thymeleaf 官方 方言類
我定義的這個(gè)是為了做敏感數(shù)據(jù)加密用的。 這是前段代碼。
以下是實(shí)現(xiàn)自定義標(biāo)簽方言 代碼:
import static at.pollux.thymeleaf.shiro.processor.ThymeleafFacade.evaluateAsStringsWithDelimiter;
import static at.pollux.thymeleaf.shiro.processor.ThymeleafFacade.getRawValue;
import java.util.List;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
import org.unbescape.html.HtmlEscape;
import com.hpay.utils.StringUtils;
/**
*@author Garc
*@Date 2017年2月16日 上午11:48:34
*@info 敏感加密標(biāo)簽
*@snise
**/
public class SansitiveEncryptProcessor extends AbstractAttributeTagProcessor{
private static final String DELIMITER = ",";
private static final String ATTRIBUTE_NAME = "sansiEncrypt";
private static final int PRECEDENCE = 300;
private static final String CARD="card";
private static final String MOBILE="mobile";
private static final String IDENTITY="identity";
private static final String CSN="csn";
protected SansitiveEncryptProcessor( String dialectPrefix) {
super(
TemplateMode.HTML, // 處理thymeleaf 的模型
dialectPrefix, // 標(biāo)簽前綴名
null, // No tag name: match any tag name
false, // No prefix to be applied to tag name
ATTRIBUTE_NAME, // 標(biāo)簽前綴的 屬性 例如:< risk:sansiEncrypt="">
true, // Apply dialect prefix to attribute name
PRECEDENCE, // Precedence (inside dialect's precedence)
true); // Remove the matched attribute afterwards
}
@Override
protected void doProcess(ITemplateContext context,
IProcessableElementTag tag, AttributeName attributeName,
String attributeValue, IElementTagStructureHandler structureHandler) {
final String rawValue = getRawValue(tag, attributeName); //獲取標(biāo)簽內(nèi)容表達(dá)式
String type=null;
String exper=null;
if(StringUtils.isNotBlank(rawValue)){
type=rawValue.split(":")[0]; //獲取類型
exper=rawValue.split(":")[1]; //獲取表達(dá)式
}
//通過IStandardExpression 解析器 解析表達(dá)式獲取參數(shù)
final List<String> values = evaluateAsStringsWithDelimiter(context, exper, DELIMITER);
final String elementCompleteName = tag.getElementCompleteName(); //標(biāo)簽名
//創(chuàng)建模型
final IModelFactory modelFactory = context.getModelFactory();
final IModel model = modelFactory.createModel();
//添加模型 標(biāo)簽
model.add(modelFactory.createOpenElementTag(elementCompleteName));
for (String value : values) {
//創(chuàng)建 html5標(biāo)簽 文本返回?cái)?shù)據(jù)
if(CARD.equals(type)){
model.add(modelFactory.createText(HtmlEscape.escapeHtml5(getCardNo(value))));
}else if(MOBILE.equals(type)){
model.add(modelFactory.createText(HtmlEscape.escapeHtml5(getMobile(value))));
}else if(IDENTITY.equals(type)){
model.add(modelFactory.createText(HtmlEscape.escapeHtml5(getIdentity(value))));
}else if(CSN.equals(type)){
model.add(modelFactory.createText(HtmlEscape.escapeHtml5(getCsn(value))));
}
}
//添加模型 標(biāo)簽
model.add(modelFactory.createCloseElementTag(elementCompleteName));
//替換頁面標(biāo)簽
structureHandler.replaceWith(model, false);
}
protected String getCardNo(String cardNo) {
if (StringUtils.isNotBlank(cardNo) && cardNo.length() >= 9) {
return cardNo.substring(0, 4) + cardNo.substring(4, cardNo.length() - 3).replaceAll("[0-9]", "*") + cardNo.substring(cardNo.length() - 4, cardNo.length());
}
return cardNo;
}
protected static String getIdentity(String val){
if(org.apache.commons.lang.StringUtils.isBlank(val)||val.length()<9){
return val;
}else{
return val.substring(0, 4)+ val.substring(4, val.length()-4).replaceAll("[0-9]", "*") + val.substring(val.length()-4, val.length());
}
}
/**
* 前四后四顯示
* @param val
* @return
*/
protected static String getMobile(String val){
if(org.apache.commons.lang.StringUtils.isBlank(val)||val.length()<9){
return val;
}else{
return val.substring(0, 3)+ val.substring(4, val.length()-3).replaceAll("[0-9]", "*") + val.substring(val.length()-4, val.length());
}
}
/**
* 星星顯示
* @param val
* @return
*/
protected String getCsn(String val){
if(org.apache.commons.lang.StringUtils.isBlank(val)||val.length()<12){
return val;
}else{
return val.substring(0, 2)+ val.substring(2, val.length()-3).replaceAll("[0-9a-zA-Z]", "*") + val.substring(val.length()-6, val.length());
}
}
}
以下代碼是為了向SansitiveEncryptProcessor 提供的解析表達(dá)式 thymeleaf解析器,用來獲取參數(shù)值的:
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.exceptions.TemplateProcessingException;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressionParser;
import org.thymeleaf.util.EvaluationUtils;
import org.thymeleaf.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
import static org.thymeleaf.util.StringUtils.trim;
import static org.thymeleaf.util.Validate.notEmpty;
import static org.thymeleaf.util.Validate.notNull;
public final class ThymeleafFacade {
private ThymeleafFacade() {
throw new UnsupportedOperationException();
}
public static String getRawValue(final IProcessableElementTag element, final AttributeName attributeName) {
notNull(element, "element must not be null");
notNull(attributeName, "attributeName must not be empty");
final String rawValue = trim(element.getAttributeValue(attributeName));
notEmpty(rawValue, "value of '" + attributeName + "' must not be empty");
return rawValue;
}
public static String getRawValue(final IProcessableElementTag element, final String attributeName) {
notNull(element, "element must not be null");
notEmpty(attributeName, "attributeName must not be empty");
final String rawValue = trim(element.getAttributeValue(attributeName));
notEmpty(rawValue, "value of '" + attributeName + "' must not be empty");
return rawValue;
}
public static Object evaluateExpression(ITemplateContext arguments, String expression) throws TemplateProcessingException {
notNull(arguments, "arguments must not be null");
notEmpty(expression, "expression must not be empty");
final IStandardExpressionParser parser = new StandardExpressionParser();
final IStandardExpression evaluableExpression = parser.parseExpression(arguments, expression);
return evaluableExpression.execute(arguments);
}
public static List<Object> evaluateAsIterable(ITemplateContext arguments, String rawValue) throws TemplateProcessingException {
notNull(arguments, "arguments must not be null");
notEmpty(rawValue, "rawValue must not be empty");
final Object evaluatedExpression = evaluateExpression(arguments, rawValue);
return EvaluationUtils.evaluateAsList(evaluatedExpression);
}
public static List<Object> evaluateAsIterableOrRawValue(ITemplateContext arguments, String rawValue) {
notNull(arguments, "arguments must not be null");
notEmpty(rawValue, "rawValue must not be empty");
final List<Object> result = new ArrayList<Object>();
try {
result.addAll(evaluateAsIterable(arguments, rawValue));
} catch (TemplateProcessingException ex) {
result.add(rawValue);
}
return unmodifiableList(result);
}
public static List<String> evaluateAsStringsWithDelimiter(ITemplateContext arguments, String rawValue, String delimiter) {
notNull(arguments, "arguments must not be null");
notEmpty(rawValue, "rawValue must not be empty");
notEmpty(delimiter, "delimiter must not be empty");
final List<String> result = new ArrayList<String>();
final List<Object> iterates = evaluateAsIterableOrRawValue(arguments, rawValue);
for (Object o : iterates) {
result.addAll(asList(StringUtils.split(o, delimiter)));
}
return unmodifiableList(result);
}
以上為 后端代碼實(shí)現(xiàn)內(nèi)容,
頁面標(biāo)簽使用方式:
<td risk:sansiEncrypt="card:${data.payerCardNo}"></td>
card 是需要 加密的類型,我實(shí)現(xiàn)的代碼里 對身份證和 手機(jī)號還有 CSN 加了密。
上面的內(nèi)容講的是 標(biāo)簽傳入數(shù)據(jù) 并返回處理數(shù)據(jù)。
類似于 if 的標(biāo)簽屬性,就不寫了。
以上這篇Thymeleaf 3.0 自定義標(biāo)簽方言屬性的實(shí)例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Springboot Thymeleaf模板文件調(diào)用Java類靜態(tài)方法
- Spring Boot + Thymeleaf + Activiti 快速開發(fā)平臺(tái)項(xiàng)目 附源碼
- Spring Boot thymeleaf模板引擎的使用詳解
- Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)
- SpringBoot Security安裝配置及Thymeleaf整合
- springboot+thymeleaf 文件上傳功能的實(shí)現(xiàn)代碼
- SpringBoot 利用thymeleaf自定義錯(cuò)誤頁面
- SpringBoot使用Thymeleaf模板引擎訪問靜態(tài)html的過程
- springBoot加入thymeleaf模板的方式
- SpringBoot使用Thymeleaf自定義標(biāo)簽的實(shí)例代碼
- Java基礎(chǔ)之Thymeleaf的簡單使用
相關(guān)文章
Mac?Maven環(huán)境搭建安裝和配置超詳細(xì)步驟
這篇文章主要給大家介紹了關(guān)于Mac?Maven環(huán)境搭建安裝和配置的超詳細(xì)步驟,Maven是一種常用的Java構(gòu)建工具,它可以自動(dòng)化構(gòu)建、測試和打包Java項(xiàng)目,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-10-10
Java和c語言隨機(jī)數(shù)Random代碼詳細(xì)
這篇文章主要介紹Java和c語言得隨機(jī)數(shù)Random,隨機(jī)數(shù)的用處在生活中比較少見,但是用處并不少,比如一些小游戲的制作等等。下面我們就一起來學(xué)習(xí)這篇關(guān)于Java和c隨機(jī)數(shù)Random得文章吧2021-10-10
詳解Java8如何使用Lambda表達(dá)式進(jìn)行比較
Lambda表達(dá)式,也可稱為閉包,是java8的新特性,作用是取代大部分內(nèi)部類,優(yōu)化java代碼結(jié)構(gòu),讓代碼變得更加簡潔緊湊。本文將利用Lambda表達(dá)式進(jìn)行排序比較,需要的可以參考一下2022-01-01
Java設(shè)計(jì)模式之單一職責(zé)原則精解
設(shè)計(jì)模式(Design pattern)代表了最佳的實(shí)踐,通常被有經(jīng)驗(yàn)的面向?qū)ο蟮能浖_發(fā)人員所采用。設(shè)計(jì)模式是軟件開發(fā)人員在軟件開發(fā)過程中面臨的一般問題的解決方案。本篇介紹設(shè)計(jì)模式七大原則之一的單一職責(zé)原則2022-02-02
java中List<對象>如何根據(jù)對象的一個(gè)屬性進(jìn)行去重
這篇文章主要給大家介紹了關(guān)于java中List<對象>如何根據(jù)對象的一個(gè)屬性進(jìn)行去重的相關(guān)資料,在開發(fā)中可能會(huì)遇到很多需要去重的情況,比如Person對象有name跟age兩個(gè)屬性,需要根據(jù)age進(jìn)行去重,需要的朋友可以參考下2023-08-08

