java - Spring Boot 中内容类型为 application/x-www-form-urlencoded 的请求的自定义反序列化器

标签 java spring spring-mvc spring-boot deserialization

我想为 application/x-www-form-urlencoded 类型的请求中的某些参数编写一个自定义反序列化器,就像在 application/json 类型的请求中使用的那样code>,带有 @JsonDeserialize(using = AbcDeserializer.class) 注释。我正在使用 spring boot 和 Jackson,尽管我发现这里没有使用 Jackson。

我尝试弄清楚 spring 默认情况下如何反序列化对象。但没找到办法。

spring默认如何反序列化application/x-www-form-urlencoded类型的请求?

我可以覆盖此反序列化吗?最好是在需要特殊处理的参数上使用一些注释?

最佳答案

我的解决方案基于自定义ConditionalGenericConverter。它与@ModelAttribute一起使用。让我们看看整个实现。

应用程序引导示例。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class DemoApplication {

    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {

        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new Base64JsonToObjectConverter());
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

这是自定义注释。

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Base64Encoded {
}

接下来我们需要实现转换器。如您所见,转换器仅转换 String -> Object,其中 Object 字段必须使用 Base64Encoded 注解进行注解。

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.Set;

@Component
public class Base64JsonToObjectConverter implements ConditionalGenericConverter {

    private final ObjectMapper objectMapper;
    private final Base64.Decoder decoder;

    public Base64JsonToObjectConverter() {
        this.objectMapper = new ObjectMapper();
        this.decoder = Base64.getDecoder();
    }

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return targetType.hasAnnotation(Base64Encoded.class);
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, Object.class));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        }
        String string = (String) source;

        try {
            byte[] decodedValue = this.decoder.decode(string);

            return this.objectMapper.readValue(decodedValue, targetType.getType());
        } catch (IllegalArgumentException | IOException e) {
            throw new ConversionFailedException(sourceType, targetType, source, e);
        }
    }
}

这里是 POJO(参见带注释的字段)和 REST Controller 的示例。

import com.example.demo.Base64Encoded;

public class MyRequest {

    private String varA;

    @Base64Encoded
    private B varB;

    public String getVarA() {
        return varA;
    }

    public void setVarA(String varA) {
        this.varA = varA;
    }

    public B getVarB() {
        return varB;
    }

    public void setVarB(B varB) {
        this.varB = varB;
    }
}
import com.example.demo.domain.MyRequest;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @RequestMapping(path = "/test", method = RequestMethod.POST)
    public MyRequest test(@ModelAttribute MyRequest myRequest) {
        return myRequest;
    }
}

关于java - Spring Boot 中内容类型为 application/x-www-form-urlencoded 的请求的自定义反序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44384557/

相关文章:

java - Spring MVC 中 @RequestMapping() 的正则表达式

java - elasticsearch lib不能同时添加commons-beanutils和commons-collections

java - JButtons 不会在单击按钮时更新

java - 为什么 Spring Boot 要求我定义 'entityManagerFactory' bean?

java - 有没有一种简单的方法可以在启动时在露天创建用户/组?

spring-mvc - 春罗Excel View

java - 在根容器中分层多个 GlassPane

java - 处理 Spring Webflux MultipartFile.transferTo 中的错误

Spring - JSP 表单 :input on jsp page error: jasperexception

java - Http Status 404错误处理spring mvc