SpringBoot整合Hashids实现数据ID加密隐藏的全过程

 更新时间:2024年01月28日 10:55:27   作者:彭世瑜  
这篇文章主要为大家详细介绍了SpringBoot整合Hashids实现数据ID加密隐藏的全过程,文中的示例代码讲解详细,对大家的学习或工作有一定的帮助,感兴趣的小伙伴可以跟随小编一起学习一下

方式一

引入依赖

<dependency>
    <groupId>org.hashids</groupId>
    <artifactId>hashids</artifactId>
    <version>1.0.3</version>
</dependency>

步骤

1、自定义注解

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface JsonHashId {
}

2、定义序列化

public class HashIdLongSerializer extends JsonSerializer<Long> implements ContextualSerializer {

    @Override
    public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(HashIdUtil.encoded(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) throws JsonMappingException {
        JsonHashId annotation = property.getAnnotation(JsonHashId.class);

        if (annotation != null) {
            return this;
        } else{
            return new NumberSerializers.LongSerializer(Long.class);
        }
    }
}

3、定义反序列化

public class HashIdLongDeserializer extends JsonDeserializer<Long> implements ContextualDeserializer {
    @Override
    public Long deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException, JacksonException {
        String value = jsonparser.getText();
        return HashIdUtil.decode(value);
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException {
        JsonHashId annotation = property.getAnnotation(JsonHashId.class);

        if (annotation != null) {
            return this;
        } else {
            return new NumberDeserializers.LongDeserializer(Long.class, null);
        }
    }
}

4、添加自定义序列化器和反序列化器

public class JacksonObjectMapper extends ObjectMapper {

    public JacksonObjectMapper() {
        super();
        // 收到未知属性时不报异常
        this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 反序列化时,属性不存在的兼容处理
        this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        module..addDeserializer(Long.class, new HashIdLongDeserializer())
            .addSerializer(Long.class, new HashIdLongSerializer());

        // 注册功能模块 添加自定义序列化器和反序列化器
        this.registerModule(module);
    }
}

5、配置消息转换器

/**
 * 配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 扩展消息转换器
     *
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        // 设置对象转换器
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        // 添加到mvc框架消息转换器中,优先使用自定义转换器
        converters.add(0, messageConverter);
    }
}

6、hashids工具类

package com.springboot.api.util;

import org.hashids.Hashids;

/**
 * hashid
 */
public class HashIdUtil {

    public static Hashids getHashids() {
        return new Hashids("hashid", 8);
    }

    /**
     * 加密
     */
    public static String encoded(Long id) {
        Hashids hashids = getHashids();
        return hashids.encode(id);
    }

    /**
     * 解密
     */
    public static long decode(String uid) {
        Hashids hashids = getHashids();
        return hashids.decode(uid)[0];
    }
}

测试输出

userId: 1,

加密后
"userId": "ZxWD0W68",

方式二

定义转换器,将序列化器和反序列化器写在一起

public class HashIdConverter {

    public static class HashIdLongDeserializer extends JsonDeserializer<Long> {
        @Override
        public Long deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException, JacksonException {
            return HashIdUtil.decode(jsonparser.getText());
        }
    }


    public static class HashIdLongSerializer extends JsonSerializer<Long> {

        @Override
        public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(HashIdUtil.encoded(value));
        }
    }
}

配置内省器

public class HashIdFieldAnnotationIntrospector extends NopAnnotationIntrospector {
    @Override
    public Object findSerializer(Annotated annotated) {
        TableId annotation = annotated.getAnnotation(TableId.class);
        if(annotation != null){
            return HashIdConverter.HashIdLongSerializer.class;
        } else{
            return super.findSerializer(annotated);
        }
    }

    @Override
    public Object findDeserializer(Annotated annotated) {
        TableId annotation = annotated.getAnnotation(TableId.class);
        if(annotation != null){
            return HashIdConverter.HashIdLongDeserializer.class;
        } else{
            return super.findDeserializer(annotated);
        }
    }
}

配置

public class JacksonObjectMapper extends ObjectMapper {

 
    public JacksonObjectMapper() {
        super();

        // 将自定义注解內省器加入到Jackson注解内省器集合里,AnnotationIntrospector是双向链表结构
        AnnotationIntrospector annotationIntrospector = this.getSerializationConfig().getAnnotationIntrospector();
        AnnotationIntrospector pair = AnnotationIntrospectorPair.pair(annotationIntrospector, new HashIdFieldAnnotationIntrospector());
        this.setAnnotationIntrospector(pair);

    }
}

最后

到此这篇关于SpringBoot整合Hashids实现数据ID加密隐藏的全过程的文章就介绍到这了,更多相关SpringBoot Hashids数据ID隐藏内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中该如何优雅的使用线程池详解

    Java中该如何优雅的使用线程池详解

    在java开发中我们对“池”的概念并不陌生,常见的有数据库连接池、线程池、对象池、常量池等等,其作用基本上就是避免频繁的创建和回收,造成资源浪费,线程池也不例外,这篇文章主要给大家介绍了关于Java中该如何优雅的使用线程池的相关资料,需要的朋友可以参考下
    2021-12-12
  • Java 8中读取文件内容 Files.lines()方法使用示例

    Java 8中读取文件内容 Files.lines()方法使用示例

    这篇文章主要介绍了Java 8中读取文件内容Files.lines()方法如何使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • Java以struts2为例介绍如何实现图片上传

    Java以struts2为例介绍如何实现图片上传

    这篇文章主要介绍了Java struts2中如何实现图片上传的相关资料,需要的朋友可以参考下
    2015-11-11
  • Java三个类加载器及它们的相互关系

    Java三个类加载器及它们的相互关系

    Java在需要使用类别的时候,才会将类别加载,Java的类别载入是由类别载入器(Class loader)来达到的,预设上,在程序启动之后,主要会有三个类别加载器,文中详细介绍了这三个类加载器,需要的朋友可以参考下
    2021-06-06
  • 使用Spring Security搭建极简的安全网站教程

    使用Spring Security搭建极简的安全网站教程

    这篇文章主要为大家介绍了使用Spring Security搭建极简的安全网站教程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • Springboot工具类FileCopyUtils使用教程

    Springboot工具类FileCopyUtils使用教程

    这篇文章主要介绍了Springboot内置的工具类之FileCopyUtils的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2022-12-12
  • JDK8 HashMap扩容算法demo

    JDK8 HashMap扩容算法demo

    这篇文章主要为大家介绍了JDK8 HashMap扩容算法demo,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • 解决IDEA 2020.3 lombok失效问题

    解决IDEA 2020.3 lombok失效问题

    这篇文章主要介绍了IDEA 2020.3 lombok失效问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Java并发编程之synchronized底层实现原理分析

    Java并发编程之synchronized底层实现原理分析

    这篇文章主要介绍了Java并发编程之synchronized底层实现原理,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • IDEA编译时报常量字符串过长的解决办法

    IDEA编译时报常量字符串过长的解决办法

    本文主要介绍了IDEA编译时报常量字符串过长的解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07

最新评论