Springboot request controllers with Special Characters

SpringBoot can be used to send in various request inputs to the server, either as request parameters to the Spring controller or as data sent in the Request body.

SpringBoot can be used to send in various request inputs  to server. There are basically two means for this , one is you can send in request parameters to the Spring controller. The other is to send data in the Request body.

Most of the time you will have to deal with sending JSON structures also for the request in real business applications. But most of the time it would be a Request Body having a JSON structure in a POST request for your controller. Which is very simple. But still there can be cases like you will need to send in a GET request with parameters having JSON structures. Which is not going to work directly if you just send in JSON structures in the request parameters. For instance, if you send in some JSON structure in the Get request it will end up with a server error something like below.

Wrapped by: java.lang.IllegalArgumentException: Illegal character in query at index 47: http://127.0.0.1:8080/shorteners/click/RikBV?e={CLICKID}&p={PUBID} at java.net.URI.create(URI.java:852)
……
….

So if you need to allow those kind of characters in your request parameters, you need to change the configuration settings when your Springboot container is spinning up. Actually what SpringBoot spins up is a Tomcat container in a specified port. So it is another Tomcat configuration that you need to feed in to the configurations stack.


So the solution is below,

@Configuration
public class ServerRequestConfiguration {
 
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
            @Override
            public void customize(Connector connector) {
                connector.setProperty("relaxedQueryChars", "|{}[]:");
            }
        });
        return factory;
    }
}

Make sure you set it as a configuration class in the SpringBoot. (Note the @Configuration annotation). And the property you are going to change in Tomcat container is called “relaxedQueryChars”. So you set it with all characters that you foresee as possible input chars.

In the above code it gives {} braces , pipe character | and [] as valid inputs. So you can send any of those with your GET requests in the URL.