统一拦截处理图片前缀地址

一、自定义注解 

package com.xxxx.common.sdk.annotation;

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.xxxx.common.sdk.Serializer.UrlPrefixSerializer;

import java.lang.annotation.*;

/**
 * @ClassName UrlPrefix
 * @Description 地址前缀
 * @email 853632587@qq.com
 * @Date 2021/12/21 14:46
 * @Version  1.0
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = UrlPrefixSerializer.class)//注解中引入自定义序列化器
public @interface UrlPrefix {
}

二、序列化

package com.xxxx.common.sdk.Serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.xxxx.common.sdk.annotation.UrlPrefix;
import com.xxxx.common.sdk.constant.BaseConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Arrays;

/**
 * @ClassName UrlPrefixSerializer
 * @Description 图片前缀处理
 * @email 853632587@qq.com
 * @Date 2021/12/21 14:28
 * @Version 1.0
 */
public class UrlPrefixSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private boolean addPrefix;

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        UrlPrefix addUrlPrefix = property.getAnnotation(UrlPrefix.class);
        if (!ObjectUtils.isEmpty(addUrlPrefix)) {
            this.addPrefix = true;
        }
        return this;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (addPrefix && StringUtils.isNotBlank(value)) {
            //如果检测到有自定义注解进行前缀处理
            String[] values = value.split(",");
            StringBuilder str = new StringBuilder();
            Arrays.stream(values).forEach(v -> {
                if (str.length() > 0) {
                    str.append(",");
                }
                str.append(BaseConstant.FtpConstant.ftpVisitUrl.concat(v).replaceAll("///", "/"));
            });
            gen.writeString(str.toString());
        } else {
            gen.writeString(value);
        }
    }

}

三、指定拦截的字段

    @UrlPrefix
    @FieldDescrib(name = "求购照片附件" ,desc = "多个图片地址逗号(,)切割")
    private String buyImageFiles;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值