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

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?