How to accept GET argument as complex object

时间:2018-06-04 16:41:01

标签: java spring spring-mvc get

My input parameter looks like this:

2Y - (2 years)
28D - (28 days)
3M - (3 months)

I want to accept argument like this:

public class InputDateInterval {
    private int count;
    private IntervalType intervalType;
    ...
}

public enum IntervalType {
    DAY("D"),
    MONTH("M"),
    YEAR("Y");

    private String sign;

    IntervalType(String sign) {
        this.sign = sign;
    }

Controller should look like this:

@GetMapping(...)
public Object(InputDateInterval idi, String anotherArgument, String...) {
    ....
}

How can I achieve it in spring mvc?

3 个答案:

答案 0 :(得分:0)

You should combined all arguments into one Object rather different arguments. You should use POST method for this.

   @PostMapping("/someUri")
    public Object complexObjectMapping(RequestObject request) {
       //do processing for request object as needed
       return something;
    }

You should define a class for your complex request object which will consists all the possible arguments.

public class RequestObject{
      private InputDateInterval idi;
      private String anotherArgument;


      //getter and setter
    }

答案 1 :(得分:0)

您应该使用RequestBody

@GetMapping
public void goGetStuff(@RequestBody InputDateInterval inputDateInterval) {
    ...
}

不过,我建议您检查一下您的API设计。我不会有超过几个参数的GET

答案 2 :(得分:0)

标准方法是实现并注册MvcArgumentResolver接口。您可以在实现中访问http请求对象,然后实现自定义逻辑以将请求参数映射到自定义参数类型。