SpringBoot中如何自定義Thymeleaf標(biāo)簽

閱讀原文
在使用Thymeleaf模板引擎開發(fā)頁面時(shí),我們可以自定義一些通用的標(biāo)簽,來簡化開發(fā)、降低代碼量,下面我以開發(fā)中常見的下拉選為例,使用Thymeleaf自定義一個下拉選的公共組件。

一、引入依賴

<dependencies>
?
    <!-- web啟動依賴 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
?
    <!-- thymeleaf依賴 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
?
    <!-- commons-lang3依賴 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.9</version>
    </dependency>
?
    <!-- commons-collections依賴 -->
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.2</version>
    </dependency>
?
    <!-- lombok依賴 -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
?
    <!-- jdbc依賴 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
?
    <!-- mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
  </dependencies>

二、基礎(chǔ)配置

# 關(guān)閉thymeleaf緩存
spring.thymeleaf.cache=false
# web模塊的日志為debug級別,便于分析問題
logging.level.web = debug
?
# 數(shù)據(jù)源配置
spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
#數(shù)據(jù)庫用戶名
spring.datasource.username=root
#數(shù)據(jù)庫密碼
spring.datasource.password=123580
#數(shù)據(jù)源
spring.datasource.type=com.mysql.cj.jdbc.MysqlDataSource
#數(shù)據(jù)庫驅(qū)動
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

三、創(chuàng)建數(shù)據(jù)表

-- ----------------------------
-- Table structure for dict_demo
-- ----------------------------
DROP TABLE IF EXISTS `dict_demo`;
CREATE TABLE `dict_demo` (
  `dict_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `dict_type` varchar(256) NOT NULL COMMENT '字典類型',
  `dict_value` varchar(256) NOT NULL COMMENT '字典值',
  `dict_label` varchar(256) DEFAULT NULL COMMENT '字典描述',
  PRIMARY KEY (`dict_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
?
-- ----------------------------
-- Records of dict_demo
-- ----------------------------
INSERT INTO `dict_demo` VALUES ('1', 'sex', '1', '男');
INSERT INTO `dict_demo` VALUES ('2', 'sex', '2', '女');

四、自定義標(biāo)簽

1、創(chuàng)建自定義標(biāo)簽注冊類

@Component
public class CustomTag extends AbstractProcessorDialect{
  /**
   * 定義方言名稱
   */
  private static final String NAME="系統(tǒng)自定義標(biāo)簽";
  
  /**
   * 定義方言屬性
   */
  private static final String PREFIX="Fw";
  
  protected CustomTag() {
    super(NAME, PREFIX, StandardDialect.PROCESSOR_PRECEDENCE);
  }
 
  @Override
  public Set<IProcessor> getProcessors(final String dialectPrefix) {
    final Set<IProcessor> processor=new HashSet<>();
    //<Fw:select>標(biāo)簽
    processor.add(new CustomTagSelect(PREFIX));
    return processor;
  }
}

2、創(chuàng)建自定義標(biāo)簽構(gòu)建類

public class CustomTagSelect extends AbstractElementTagProcessor {
  // 標(biāo)簽名
  private static final String TAG_NAME = "select";
?
  // 優(yōu)先級
  private static final int PRECEDENCE = 10000;
?
  public CustomTagSelect(String dialectPrefix) {
    super(
        // 模板類型為HTML
        TemplateMode.HTML,
        // 標(biāo)簽方言前綴
        dialectPrefix,
        // 標(biāo)簽名稱
        TAG_NAME,
        // 將標(biāo)簽前綴應(yīng)用于標(biāo)簽名稱
        true,
        // 無屬性名稱:將通過標(biāo)簽名稱匹配
        null,
        // 沒有要應(yīng)用于屬性名稱的前綴
        false,
        // 優(yōu)先級
        PRECEDENCE
    );
  }

  /**
   * 處理自定義標(biāo)簽 DOM 結(jié)構(gòu)
   *
   * @param iTemplateContext            模板頁上下文
   * @param iProcessableElementTag      待處理標(biāo)簽
   * @param iElementTagStructureHandler 元素標(biāo)簽結(jié)構(gòu)處理器
   */
  @Override
  protected void doProcess(ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, IElementTagStructureHandler iElementTagStructureHandler) {
    // 獲取 Spring 上下文
    ApplicationContext applicationContext = SpringContextUtils.getApplicationContext(iTemplateContext);
    // 獲取注入bean工廠
    AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    // 獲取所需的bean,一般情況下這里我們直接使用Jdbc來操作數(shù)據(jù)庫,因?yàn)樗且粋€公共組件,數(shù)據(jù)源不確定,所以要使用動態(tài)sql
    JdbcOperations jdbcOperations = autowireCapableBeanFactory.getBean(JdbcOperations.class);
    //select的id屬性
    String id = iProcessableElementTag.getAttributeValue("id");
    //select的name屬性
    String name = iProcessableElementTag.getAttributeValue("name");
    //option中value的值在數(shù)據(jù)表中的對應(yīng)字段
    String colVal = iProcessableElementTag.getAttributeValue("colVal");
    //option中文本的值在數(shù)據(jù)表中的對應(yīng)字段
    String colText = iProcessableElementTag.getAttributeValue("colText");
    //默認(rèn)值
    String value = iProcessableElementTag.getAttributeValue("value");
    value = StringUtils.isBlank(value) ? "" : value;
    //select的擴(kuò)展屬性
    String otherAttrs = iProcessableElementTag.getAttributeValue("otherAttrs");
    //sql where之后的部分
    String options = iProcessableElementTag.getAttributeValue("options");
    //是否顯示請選擇
    String selectFlag = iProcessableElementTag.getAttributeValue("selectFlag");
    //表名稱
    String tableName = iProcessableElementTag.getAttributeValue("tableName");
    StringBuffer result = new StringBuffer("<select><option value=''>--請選擇--</option></select>");
    if(validParamIsNotNull(id,name,colText, colVal, tableName)) {
      //最終拼接的sql語句,這里可以使用jdbc來查詢
      String selectSql = "select " + colVal + "," + colText + " from " + tableName + options;
      List<Map<String, Object>> mapList = jdbcOperations.queryForList(selectSql);
      if (mapList != null && mapList.size() >= 0) {
        result = new StringBuffer("<select ");
        result.append(" id='").append(id).append("'");
        result.append(" name='").append(name).append("'");
        if(StringUtils.isNotBlank(otherAttrs)) {
          result.append(" " + otherAttrs +" ");
        }
        result.append(">");
        if(StringUtils.isBlank(selectFlag) || (StringUtils.isNotBlank(selectFlag) && "true".equalsIgnoreCase(selectFlag))) {
          result.append("<option value=''>--請選擇--</option>");
        }
        for (Map<String, Object> vo : mapList) {
          String dictValue = MapUtils.getString(vo, colVal);
          String dictName = MapUtils.getString(vo, colText);
          if (value.equals(dictValue)) {
            result.append("<option value='").append(dictValue).append("' selected>").append(dictName).append("</option>");
          } else {
            result.append("<option value='").append(dictValue).append("'>").append(dictName).append("</option>");
          }
        }
        result.append("</select>");
      }
    }
    // 創(chuàng)建將替換自定義標(biāo)簽的 DOM 結(jié)構(gòu)
    IModelFactory modelFactory = iTemplateContext.getModelFactory();
    IModel model = modelFactory.createModel();
    // 這里是將字典的內(nèi)容拼裝成一個下拉框
    model.add(modelFactory.createText(result));
    // 利用引擎替換整合標(biāo)簽
    iElementTagStructureHandler.replaceWith(model, false);
  }
?
  /**
   * 驗(yàn)證參數(shù)是否不為空
   * @param params
   * @return true,不為空;false,為空
   */
  public static Boolean validParamIsNotNull(String ... params) {
    for(String param : params) {
      if(StringUtils.isBlank(param)) {
        return false;
      }
    }
    return true;
  }

3、使用自定義標(biāo)簽

<Fw:select id="sex" name="sex" colVal="dict_value" colText="dict_label" tableName="dict_demo" options=" where dict_type = 'sex'" value="1"/>

4、渲染效果

image

五、總結(jié)

1、在創(chuàng)建標(biāo)簽注冊類時(shí),需聲明該類為Spring的一個組件類,即使用@Component注解,否則標(biāo)簽將不會生效。

2、自定義標(biāo)簽的優(yōu)先級需和th標(biāo)簽同級,否則會導(dǎo)致和其他th標(biāo)簽連用時(shí)的數(shù)據(jù)解析問題。

3、自定義標(biāo)簽的實(shí)質(zhì)就是通過標(biāo)簽實(shí)現(xiàn)了一個動態(tài)SQL的拼接,并將查詢的數(shù)據(jù)組裝成一個組件域,所以需要注意SQL拼接時(shí)的語法規(guī)范問題。

更多最新技術(shù)文章,請關(guān)注“冰點(diǎn)IT”公眾號

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容