关于springboot:Springboot更改Thymeleaf中js块的对象序列化方式

1次阅读

共计 1791 个字符,预计需要花费 5 分钟才能阅读完成。

在默认状况下 Thymeleaf 对于 js 块中的对象解析是应用 jackson 进行序列化,然而特定状况下咱们须要更换成其余类型的序列话工具。
例如:因为 springboot 默认的序列化应用的 jackson,而咱们的脱敏规定也是建设在 jackson 序列化时对属性进行脱敏。
在 thymeleaf 模板中注入 html 块变量时能够间接通过对象设值,不存在序列化的动作,然而对于 js 块中的对象须要 javaScriptSerializer 进行序列化
因而会存在列表中是脱敏的数据,进行编辑页面如果属性赋值是通过 thymeleaf 的 js 块,则会触发 jackson 的脱敏规定。
咱们对象中曾经存在很多 jackson 属性的注解例如日期等,所以为了防止大规模改变,我抉择更改 thymeleafjs 块的序列化形式。
通过浏览 Thymeleaf 源码咱们发现 javaScriptSerializer 默认应用的为 Jackson 的 ObjectMapper 进行序列化,然而察看调用方咱们发现如果曾经设置 javaScriptSerializer。
则不会应用 jackson,除 jackson 之外还存在一个默认的序列化器,因为其属于外部类,无奈内部调用初始化,因此我抉择通过实现 IStandardJavaScriptSerializer 来
定义本人的 js 对象序列化器,其中应用 fastjson,至此咱们能够躲避在 js 中应用对象时,属性被脱敏的状况产生。

咱们首先须要实现能够作为 JavaScript 序列化的通用接口类来自定义序列化器

package com.common.nmg.utils;

import com.alibaba.fastjson.JSONObject;
import org.thymeleaf.standard.serializer.IStandardJavaScriptSerializer;

import java.io.Writer;

public class FastJsonJavaScriptSerializer implements IStandardJavaScriptSerializer {

    @Override
    public void serializeValue(Object object, Writer writer) {JSONObject.writeJSONString(writer,object);
    }
}

再将自定义的序列化器注入到 spring 的 thymeleaf 模板解析器中

package com.nmg.framework.config;

import com.nmg.common.utils.FastJsonJavaScriptSerializer;
import com.nmg.common.utils.spring.SpringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.standard.StandardDialect;

import javax.annotation.PostConstruct;

/**
 *
 * @author zengzp
 * @date 2022 年 6 月 14 日 17 点 38 分
 * @desc
 */
@Configuration
public class ThymeleafConfig {

    @PostConstruct
    public void init() {SpringTemplateEngine springTemplateEngine = SpringUtils.getBean(SpringTemplateEngine.class);
        StandardDialect standardDialect = CollectionUtils.findValueOfType(springTemplateEngine.getDialects(), StandardDialect.class);
        standardDialect.setJavaScriptSerializer(new FastJsonJavaScriptSerializer());
    }
}
正文完
 0