How to prevent parameter binding from interpreting commas in Spring 3.0.5?

后端 未结 6 1865
抹茶落季
抹茶落季 2020-11-28 06:37

Consider the following controller method:

@RequestMapping(value = \"/test\", method = RequestMethod.GET)
public void test(@RequestParam(value = \"fq\", requi         


        
6条回答
  •  生来不讨喜
    2020-11-28 07:18

    The following is my journey of bypassing comma delimiting in a MVC request

    This is my understanding of Springs evolution of these type of solutions: The documentation is very vague about what is the latest solution.

    First was WebMvcConfigAdapter implementing the interface WebMvcConfig. This was eventually deprecated

    That was replaced by WebMvcConfigSupport. This was eventually deprecated but it was better than the first solution. The main issued was that it turned off the MVC auto-configuration and had side issues like swagger.html not working and actuator info being missing pretty format and the date became a large decimal

    The latest is a revised interface WebMvcConfig that implements default methods using Java 8 features.

    Create a class in my case, WebConfigUUID could be AnyClass, that implements the later version of WebMvcConfig

    This allows you to change what you need, in our case a custom converter, without impacting anything else or having to override another to get swagger to work, or deal with actuator info output

    The following are the two classes that implemented my change to bypass comma delimiting of strings to a list in processing the MVC request:
    It still produces a list of strings but with only one value.

    import java.util.Collection;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.format.FormatterRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    @Configuration
    public class WebConfigUUID implements WebMvcConfigurer {
      @Override
      public void addFormatters(FormatterRegistry registry)  {
        registry.removeConvertible(String.class,Collection.class);
        registry.addConverter(String.class,Collection.class,BypassCommaDelimiterConfiguration.commaDelimiterBypassedParsingConverter());
      }
    }
    
    import java.util.ArrayList;
    import java.util.List;
    import org.springframework.core.convert.converter.Converter;
    
    public class BypassCommaDelimiterConfiguration  {
        public static Converter> commaDelimiterBypassedParsingConverter() {
            return new Converter>() {
                @Override
                public List convert(final String source) {
                    final List classes = new ArrayList();
                    classes.add(source);
                    return classes;
                }
            };
        }
    }
    

提交回复
热议问题