Spring:在POST请求中如何接收多个对象参数

时间:2024-10-18 07:55:04

在POST请求中如何接收多个对象参数

  • 场景
  • 方案一:使用自定义包装类
  • 方案二:使用Map
  • 方案三:使用自定义参数解析器

场景

在Post请求中,使用@RequestBody接收两个入参

@RestController
public class TestController{
	@PostMapping("/test")
	public Result<String> test(@RequestBody ParamA a, @RequestBody ParamB b){
		//to do
	}
}

方案一:使用自定义包装类

@Data
public class RequestParam{
	private ParamA a;
	private ParamB b;
}
@RestController
public class TestController{
	@PostMapping("/test")
	public void test(@RequestBody RequestParam requestParam){
		// todo
	}
}

方案二:使用Map

@RestController
public class TestController{
	private static final ObjectMapper JACKSON = new ObjectMapper();

	@PostMapping("/test")
	public void test(@RequestBody Map<String,Object> map){
		Object aObject = map.get("a");
		Object bObject = map.get("b");
		ParamA a = JACKSON.readValue(JACKSON.writeValueAsString(aObject), ParamA.class);
		ParamB b = JACKSON.readValue(JACKSON.writeValueAsString(bObject), ParamB.class);
		//to do
	}
}

方案三:使用自定义参数解析器

1.自定义注解

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Params{
}

2.自定义参数解析器

@Component
public ParamsResolver implements HandlerMethodArgumentResolver{
	@Override
	public boolean supportsParameter(MethodParameter methodParameter){
		return methodParameter.hasParameterAnnotation(Params.class);
	}
	
	@Override
	public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory){
		//to do
	}
}

3.注册自定义参数解析器

@Configuration
public class ParamsResolverConfig implements WebMvcConfigurer{
	@Resource
	private ParamsResolver paramsResolver;
	
	@Override
	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers){
		resolvers.add(paramsResolver);
	}
}

4.使用注解

@RestController
public class TestController{
	@PostMapping("/test")
	public Result<String> test(@Params ParamA a, @Params ParamB b){
		//to do
	}
}