Remove parameters from spring formHow does autowiring work in Spring?What's the difference between @Component, @Repository & @Service annotations in Spring?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?how to show Run time error message or sql error message in the same jsp in spring mvc 3.0spring form validation : Unable to print errors in jspgetting null value in the controller while submitting the formSpring mvc miss id of dependent collection when combine form object from jspSpring MVC form validation does't work for nested complex typesNull values returned in Spring Controller following selection from Bootstrap list boxMultiple-Form on one page with SpringMVC

When is it ok to add filler to a story?

Peace Arch without exiting USA

Distance Matrix (plugin) - QGIS

Is it damaging to turn off a small fridge for two days every week?

Alphabet completion rate

Low-gravity Bronze Age fortifications

Can White Castle?

Why is C++ initial allocation so much larger than C's?

Require advice on power conservation for backpacking trip

Change CPU MHz from Registry

Safe to store SMTP password in wp-config.php?

MH370 blackbox - is it still possible to retrieve data from it?

What are the penalties for overstaying in USA?

How to get cool night-vision without lame drawbacks?

Do equal angles necessarily mean a polygon is regular?

Are Finite Automata Turing Complete?

Do French speakers not use the subjunctive informally?

What is the difference between and Embedding Layer and an Autoencoder?

Could Sauron have read Tom Bombadil's mind if Tom had held the Palantir?

Hot coffee brewing solutions for deep woods camping

Was there ever a name for the weapons of the Others?

Are there any vegetarian astronauts?

Do hotel cleaning personnel have any benefit from leaving empty bottles in the room as opposed to returning them to the store?

Can ADFS connect to other SSO services?



Remove parameters from spring form


How does autowiring work in Spring?What's the difference between @Component, @Repository & @Service annotations in Spring?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?how to show Run time error message or sql error message in the same jsp in spring mvc 3.0spring form validation : Unable to print errors in jspgetting null value in the controller while submitting the formSpring mvc miss id of dependent collection when combine form object from jspSpring MVC form validation does't work for nested complex typesNull values returned in Spring Controller following selection from Bootstrap list boxMultiple-Form on one page with SpringMVC






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a Spring MVC application using forms. The form contains a dynamic list of filters which can be added or removed. My form object simply looks like this:



public class RequestForm 
@Valid
List<Filter> filters = new LinkedList<>();



Filter is a base class and has other subclasses to allow custom validation of the value:



public class Filter 
String type;
String value;
boolean ignoreFilter;


public IntFilter extends Filter
@ValueIsInteger
String getValue() ...


public DateFilter extends Filter
@ValueIsDate
String getValue() ...



In my controller I am using @InitBinder to cast the Filter objects into the right subclass based on the type attribute and ignore the filter based on the other attribute. The code looks like this:



@InitBinder
public void initBinder(WebDataBinder webDataBinder, HttpServletRequest httpServletRequest)
// Filter out all request when we have nothing to do
Object nonCastedTarget = webDataBinder.getTarget();

// TODO: Better cache this in static final field instead
Pattern pattern = Pattern.compile("filters\[(\d+)]\.filterType");

Map<Integer, String> types = new HashMap<>();
Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
while (parameterNames.hasMoreElements())
String element = parameterNames.nextElement();
Matcher matcher = pattern.matcher(element);
if (!matcher.matches())
continue;


types.put(
Integer.parseInt(matcher.group(1)),
httpServletRequest.getParameter(element)
);



RequestForm target = (RequestForm) nonCastedTarget;

types.keySet().stream().sorted().forEach(key ->
//remove disabled filter if("false".equals(httpServletRequest.getParameter("filters["+key+"].ignoreFilter")))
switch (types.get(key))
case "int":
target.getFilters().add(new IntFilter(httpServletRequest.getParameter("filters["+key+"].value")));
break;
case "date":
target.getFilters().add(new DateFilter(httpServletRequest.getParameter("filters["+key+"].value")));
break;
default:
throw new IllegalStateException("Unknown type: " + types.get(key));


);



And in the controller:



 public ModelAndView postPage(@Valid @ModelAttribute("requestForm") RequestForm requestForm, BindingResult bindingResult, Locale locale) 

ModelAndView mav;

// errors in the selection
if (bindingResult.hasErrors())
mav = new ModelAndView("requestmanagement/view");
addRequestFormParameters(mav, requestForm, locale);
return mav;

...



My Problem:



The casting and validation of subfilters works. However, ignored filters are still added to the RequestForm in the controller. If my form contains an IntFilter which should be ignored, my RequestForm in the controller contains still the filter but is not casted into the subtype.



Who can I remove the filter from the RequestForm?










share|improve this question




























    0















    I have a Spring MVC application using forms. The form contains a dynamic list of filters which can be added or removed. My form object simply looks like this:



    public class RequestForm 
    @Valid
    List<Filter> filters = new LinkedList<>();



    Filter is a base class and has other subclasses to allow custom validation of the value:



    public class Filter 
    String type;
    String value;
    boolean ignoreFilter;


    public IntFilter extends Filter
    @ValueIsInteger
    String getValue() ...


    public DateFilter extends Filter
    @ValueIsDate
    String getValue() ...



    In my controller I am using @InitBinder to cast the Filter objects into the right subclass based on the type attribute and ignore the filter based on the other attribute. The code looks like this:



    @InitBinder
    public void initBinder(WebDataBinder webDataBinder, HttpServletRequest httpServletRequest)
    // Filter out all request when we have nothing to do
    Object nonCastedTarget = webDataBinder.getTarget();

    // TODO: Better cache this in static final field instead
    Pattern pattern = Pattern.compile("filters\[(\d+)]\.filterType");

    Map<Integer, String> types = new HashMap<>();
    Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
    while (parameterNames.hasMoreElements())
    String element = parameterNames.nextElement();
    Matcher matcher = pattern.matcher(element);
    if (!matcher.matches())
    continue;


    types.put(
    Integer.parseInt(matcher.group(1)),
    httpServletRequest.getParameter(element)
    );



    RequestForm target = (RequestForm) nonCastedTarget;

    types.keySet().stream().sorted().forEach(key ->
    //remove disabled filter if("false".equals(httpServletRequest.getParameter("filters["+key+"].ignoreFilter")))
    switch (types.get(key))
    case "int":
    target.getFilters().add(new IntFilter(httpServletRequest.getParameter("filters["+key+"].value")));
    break;
    case "date":
    target.getFilters().add(new DateFilter(httpServletRequest.getParameter("filters["+key+"].value")));
    break;
    default:
    throw new IllegalStateException("Unknown type: " + types.get(key));


    );



    And in the controller:



     public ModelAndView postPage(@Valid @ModelAttribute("requestForm") RequestForm requestForm, BindingResult bindingResult, Locale locale) 

    ModelAndView mav;

    // errors in the selection
    if (bindingResult.hasErrors())
    mav = new ModelAndView("requestmanagement/view");
    addRequestFormParameters(mav, requestForm, locale);
    return mav;

    ...



    My Problem:



    The casting and validation of subfilters works. However, ignored filters are still added to the RequestForm in the controller. If my form contains an IntFilter which should be ignored, my RequestForm in the controller contains still the filter but is not casted into the subtype.



    Who can I remove the filter from the RequestForm?










    share|improve this question
























      0












      0








      0








      I have a Spring MVC application using forms. The form contains a dynamic list of filters which can be added or removed. My form object simply looks like this:



      public class RequestForm 
      @Valid
      List<Filter> filters = new LinkedList<>();



      Filter is a base class and has other subclasses to allow custom validation of the value:



      public class Filter 
      String type;
      String value;
      boolean ignoreFilter;


      public IntFilter extends Filter
      @ValueIsInteger
      String getValue() ...


      public DateFilter extends Filter
      @ValueIsDate
      String getValue() ...



      In my controller I am using @InitBinder to cast the Filter objects into the right subclass based on the type attribute and ignore the filter based on the other attribute. The code looks like this:



      @InitBinder
      public void initBinder(WebDataBinder webDataBinder, HttpServletRequest httpServletRequest)
      // Filter out all request when we have nothing to do
      Object nonCastedTarget = webDataBinder.getTarget();

      // TODO: Better cache this in static final field instead
      Pattern pattern = Pattern.compile("filters\[(\d+)]\.filterType");

      Map<Integer, String> types = new HashMap<>();
      Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
      while (parameterNames.hasMoreElements())
      String element = parameterNames.nextElement();
      Matcher matcher = pattern.matcher(element);
      if (!matcher.matches())
      continue;


      types.put(
      Integer.parseInt(matcher.group(1)),
      httpServletRequest.getParameter(element)
      );



      RequestForm target = (RequestForm) nonCastedTarget;

      types.keySet().stream().sorted().forEach(key ->
      //remove disabled filter if("false".equals(httpServletRequest.getParameter("filters["+key+"].ignoreFilter")))
      switch (types.get(key))
      case "int":
      target.getFilters().add(new IntFilter(httpServletRequest.getParameter("filters["+key+"].value")));
      break;
      case "date":
      target.getFilters().add(new DateFilter(httpServletRequest.getParameter("filters["+key+"].value")));
      break;
      default:
      throw new IllegalStateException("Unknown type: " + types.get(key));


      );



      And in the controller:



       public ModelAndView postPage(@Valid @ModelAttribute("requestForm") RequestForm requestForm, BindingResult bindingResult, Locale locale) 

      ModelAndView mav;

      // errors in the selection
      if (bindingResult.hasErrors())
      mav = new ModelAndView("requestmanagement/view");
      addRequestFormParameters(mav, requestForm, locale);
      return mav;

      ...



      My Problem:



      The casting and validation of subfilters works. However, ignored filters are still added to the RequestForm in the controller. If my form contains an IntFilter which should be ignored, my RequestForm in the controller contains still the filter but is not casted into the subtype.



      Who can I remove the filter from the RequestForm?










      share|improve this question














      I have a Spring MVC application using forms. The form contains a dynamic list of filters which can be added or removed. My form object simply looks like this:



      public class RequestForm 
      @Valid
      List<Filter> filters = new LinkedList<>();



      Filter is a base class and has other subclasses to allow custom validation of the value:



      public class Filter 
      String type;
      String value;
      boolean ignoreFilter;


      public IntFilter extends Filter
      @ValueIsInteger
      String getValue() ...


      public DateFilter extends Filter
      @ValueIsDate
      String getValue() ...



      In my controller I am using @InitBinder to cast the Filter objects into the right subclass based on the type attribute and ignore the filter based on the other attribute. The code looks like this:



      @InitBinder
      public void initBinder(WebDataBinder webDataBinder, HttpServletRequest httpServletRequest)
      // Filter out all request when we have nothing to do
      Object nonCastedTarget = webDataBinder.getTarget();

      // TODO: Better cache this in static final field instead
      Pattern pattern = Pattern.compile("filters\[(\d+)]\.filterType");

      Map<Integer, String> types = new HashMap<>();
      Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
      while (parameterNames.hasMoreElements())
      String element = parameterNames.nextElement();
      Matcher matcher = pattern.matcher(element);
      if (!matcher.matches())
      continue;


      types.put(
      Integer.parseInt(matcher.group(1)),
      httpServletRequest.getParameter(element)
      );



      RequestForm target = (RequestForm) nonCastedTarget;

      types.keySet().stream().sorted().forEach(key ->
      //remove disabled filter if("false".equals(httpServletRequest.getParameter("filters["+key+"].ignoreFilter")))
      switch (types.get(key))
      case "int":
      target.getFilters().add(new IntFilter(httpServletRequest.getParameter("filters["+key+"].value")));
      break;
      case "date":
      target.getFilters().add(new DateFilter(httpServletRequest.getParameter("filters["+key+"].value")));
      break;
      default:
      throw new IllegalStateException("Unknown type: " + types.get(key));


      );



      And in the controller:



       public ModelAndView postPage(@Valid @ModelAttribute("requestForm") RequestForm requestForm, BindingResult bindingResult, Locale locale) 

      ModelAndView mav;

      // errors in the selection
      if (bindingResult.hasErrors())
      mav = new ModelAndView("requestmanagement/view");
      addRequestFormParameters(mav, requestForm, locale);
      return mav;

      ...



      My Problem:



      The casting and validation of subfilters works. However, ignored filters are still added to the RequestForm in the controller. If my form contains an IntFilter which should be ignored, my RequestForm in the controller contains still the filter but is not casted into the subtype.



      Who can I remove the filter from the RequestForm?







      spring-mvc spring-form spring-mvc-initbinders






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 25 at 10:21









      ThanthlaThanthla

      12816 bronze badges




      12816 bronze badges






















          0






          active

          oldest

          votes














          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55335604%2fremove-parameters-from-spring-form%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55335604%2fremove-parameters-from-spring-form%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript