讯飞AI开发者社区 java后端请求想接收多个对象入参的数据

java后端请求想接收多个对象入参的数据

在 Java 后端开发中,特别是使用 Spring Boot 框架时,经常需要处理来自前端的请求,这些请求可能包含多个对象的入参。处理这些参数的方式有多种,下面详细介绍几种常见的方法。1. 使用自定义 DTO 对象这是最常见的方法之一。创建一个包含所有需要传递对象的自定义 DTO(数据传输对象)类,然后使用 @Reques...

在 Java 后端开发中,特别是使用 Spring Boot 框架时,经常需要处理来自前端的请求,这些请求可能包含多个对象的入参。处理这些参数的方式有多种,下面详细介绍几种常见的方法。

1. 使用自定义 DTO 对象

这是最常见的方法之一。创建一个包含所有需要传递对象的自定义 DTO(数据传输对象)类,然后使用 @RequestBody 注解接收整个 DTO 对象。

示例代码

假设我们需要接收用户和地址两个对象:

// 用户对象
public class User {
    private String name;
    private String email;
    // getters and setters
}

// 地址对象
public class Address {
    private String street;
    private String city;
    // getters and setters
}

// 自定义 DTO 对象
public class UserAddressDTO {
    private User user;
    private Address address;
    // getters and setters
}

// 控制器
@RestController
public class UserController {

    @PostMapping("/user")
    public String createUser(@RequestBody UserAddressDTO userAddressDTO) {
        User user = userAddressDTO.getUser();
        Address address = userAddressDTO.getAddress();
        // 处理业务逻辑
        return "User and address created successfully";
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.

2. 使用 Map 接收多个对象

另一种方法是使用 Map 作为 @RequestBody 的参数类型,然后在控制器中手动解析这些参数。

示例代码
@RestController
public class UserController {

    @PostMapping("/user")
    public String createUser(@RequestBody Map<String, Object> params) {
        User user = (User) params.get("user");
        Address address = (Address) params.get("address");
        // 处理业务逻辑
        return "User and address created successfully";
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

3. 使用多个 @RequestBody 注解

虽然 Spring MVC 不支持在一个方法中使用多个 @RequestBody 注解,但可以通过自定义参数解析器来实现类似的功能。

示例代码
3.1 创建自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface MultiRequestBody {
    String value() default "";
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
3.2 创建自定义参数解析器
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.io.IOException;
import java.util.Map;

public class MultiRequestBodyArgumentResolver implements HandlerMethodArgumentResolver {

    private final ObjectMapper objectMapper;

    public MultiRequestBodyArgumentResolver(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(MultiRequestBody.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String json = webRequest.getNativeRequest(HttpServletRequest.class).getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        Map<String, Object> map = objectMapper.readValue(json, Map.class);
        String key = parameter.getParameterAnnotation(MultiRequestBody.class).value();
        return objectMapper.convertValue(map.get(key), parameter.getParameterType());
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
3.3 注册自定义参数解析器
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final ObjectMapper objectMapper;

    public WebConfig(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new MultiRequestBodyArgumentResolver(objectMapper));
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
3.4 使用自定义注解
@RestController
public class UserController {

    @PostMapping("/user")
    public String createUser(@MultiRequestBody("user") User user, @MultiRequestBody("address") Address address) {
        // 处理业务逻辑
        return "User and address created successfully";
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

4. 使用 @RequestParam 注解

如果前端传递的是表单数据,可以使用 @RequestParam 注解来接收多个对象。

示例代码
@RestController
public class UserController {

    @PostMapping("/user")
    public String createUser(@RequestParam("user") String userJson, @RequestParam("address") String addressJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            User user = objectMapper.readValue(userJson, User.class);
            Address address = objectMapper.readValue(addressJson, Address.class);
            // 处理业务逻辑
            return "User and address created successfully";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to create user and address";
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

总结

以上介绍了几种在 Java 后端接收多个对象入参的方法。每种方法都有其适用场景和优缺点,可以根据具体需求选择合适的方法。使用自定义 DTO 对象是最简单和推荐的方法,而使用自定义参数解析器则提供了更高的灵活性。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐

  • 浏览量 1161
  • 收藏 0
  • 0

所有评论(0)

查看更多评论 
已为社区贡献24条内容