Spring MVC Binding in a Typed Field

I have a Spring MVC controller, for example:

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @ResponseBody
    public Object grid(Search<MyFilter> search){
      ...
    }

My search object is like:

public class Search<F extends Filter> {
    private int offset;
    private int size;
    private F filter;

    //... getters/ setters
}

A filter is just an interface. MyFilterrepresents an implementation Filterwith some fields, such as name, titleetc.

I am doing an HTTP GET for this controller with: /search?offset=0&size=10&filter.name=john

But Spring cannot create an instance of MyFilter. I tried to make a Filternormal empty class and MyFilterto extend it, but this is also impossible.

Is it possible for Spring to create the right filter and then bind the values?

+4
source share
2 answers

[TL; DR] No, Spring will not create MyFilterfrom a parameterized type.

Search , . , . , Search :

class Search {

    /*
     * F is replaced by Filter since it is the most general type 
     * for <F extends Filter> parametrization. 
     * This will be the only Search class representation that compiler generates.
     */
    private Filter filter;

    //Rest of class body omitted
}

. Sicne Filter - , , . mapper Filter , , ( , ). , , . .

, , MyFilter, @DeezCashews. . , - :

public class Search {
    private int offset;
    private int size;
    private List<FieldPredicateTuple> filters;

    //getters and setters omitted
}

public class FieldPredicateTuple {
    String field;
    String value;

    //getters and setters omitted
}

: /search?offset=0&size=10&filters[0].field=name&filters[0].value=john

, , , . -.

+2

, , , , , grid . Spring , , , , . bean bean . :

public Object grid(MyFilter f, Paged p);

public class MyFilter {
  String name;
  ...
}

public class Paged {
  int offset;
  int size;
  ...
}
+1

Source: https://habr.com/ru/post/1666633/


All Articles