Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring - Add New Query Parameters in GET Call Through Configurations

If you're looking to add new query parameters to all GET calls in your Spring application using configurations, a common approach is to use an interceptor. An interceptor allows you to perform operations before or after sending a request to the controller, which makes it ideal for manipulating request parameters.

Here's how you can achieve this:

  • Define an Interceptor:

    Implement HandlerInterceptor to modify the request URI before it reaches the controller.

@Component
public class QueryParameterAddingInterceptor implements HandlerInterceptor {

    @Value("${query.param.name}")
    private String queryParamName;

    @Value("${query.param.value}")
    private String queryParamValue;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            String oldUri = request.getRequestURI();
            String separator = (oldUri.contains("?")) ? "&" : "?";
            String newUri = oldUri + separator + queryParamName + "=" + queryParamValue;
            request.getRequestDispatcher(newUri).forward(request, response);
            return false;
        }
        return true;
    }
}
  • Register the Interceptor:

    Create a configuration class that extends WebMvcConfigurer to register your interceptor.

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private QueryParameterAddingInterceptor queryParameterAddingInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(queryParameterAddingInterceptor);
    }
}
  • Add the Configuration Properties:

    You can define your query parameters in your application.properties or application.yml file.

query.param.name=newParamName
query.param.value=newParamValue

By setting up this interceptor, every GET request that comes into your application will have the new query parameters appended to the request URI. Note that this example adds a single query parameter, but you can extend it to add multiple parameters based on your needs.

Remember, modifying incoming requests can have unintended side effects and might confuse other developers if they're unaware of this behavior, so it's crucial to document and communicate these changes well.

  1. Spring RestTemplate add query parameters dynamically:

    • You can add query parameters dynamically using the UriComponentsBuilder class.
    public String getRequestWithParams(String url, Map<String, String> queryParams) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
    
        for (Map.Entry<String, String> entry : queryParams.entrySet()) {
            builder.queryParam(entry.getKey(), entry.getValue());
        }
    
        String finalUrl = builder.toUriString();
    
        // Use RestTemplate to make a GET request with the final URL
        // ...
        return result;
    }
    
  2. Modify GET request parameters in Spring RestTemplate:

    • You can modify parameters by updating the UriComponentsBuilder object.
    public String modifyGetRequestParameters(String url, String key, String value) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
    
        builder.queryParam(key, value);
    
        String finalUrl = builder.toUriString();
    
        // Use RestTemplate to make a GET request with the final URL
        // ...
        return result;
    }
    
  3. Adding query parameters to Spring WebClient GET request:

    • In WebClient, you can use the uri method to build a URI with query parameters.
    WebClient.builder()
        .baseUrl(baseUrl)
        .uri(uriBuilder -> uriBuilder
            .path("/endpoint")
            .queryParam("param1", "value1")
            .queryParam("param2", "value2")
            .build())
        .build()
        .get()
        .retrieve()
        .bodyToMono(String.class);
    
  4. Customizing GET request parameters in Spring RestTemplate:

    • Customize parameters based on certain conditions or logic.
    public String customizeGetRequestParameters(String url, boolean condition) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
    
        if (condition) {
            builder.queryParam("customParam", "customValue");
        }
    
        String finalUrl = builder.toUriString();
    
        // Use RestTemplate to make a GET request with the final URL
        // ...
        return result;
    }
    
  5. Dynamic query parameters in Spring RestTemplate GET call:

    • Dynamically generate and add query parameters.
    public String dynamicQueryParameters(String url, String... params) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
    
        for (int i = 0; i < params.length; i += 2) {
            builder.queryParam(params[i], params[i + 1]);
        }
    
        String finalUrl = builder.toUriString();
    
        // Use RestTemplate to make a GET request with the final URL
        // ...
        return result;
    }
    
  6. Configuring additional parameters for GET request in Spring:

    • Configure additional parameters as needed.
    public String configureAdditionalParameters(String url, String apiKey) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
    
        builder.queryParam("api_key", apiKey);
    
        String finalUrl = builder.toUriString();
    
        // Use RestTemplate to make a GET request with the final URL
        // ...
        return result;
    }
    
  7. How to append query parameters in Spring RestTemplate GET call:

    • Use UriComponentsBuilder to append parameters.
    public String appendQueryParameters(String url, String key, String value) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
    
        builder.queryParam(key, value);
    
        String finalUrl = builder.toUriString();
    
        // Use RestTemplate to make a GET request with the final URL
        // ...
        return result;
    }
    
  8. Spring WebClient modify query parameters in GET request:

    • Modify parameters in WebClient using the uri method.
    WebClient.builder()
        .baseUrl(baseUrl)
        .uri(uriBuilder -> uriBuilder
            .path("/endpoint")
            .queryParam("param1", "newValue")
            .build())
        .build()
        .get()
        .retrieve()
        .bodyToMono(String.class);
    
  9. Injecting new parameters into Spring RestTemplate GET call:

    • Inject new parameters into the URI using UriComponentsBuilder.
    public String injectNewParameters(String url, String newParam, String value) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
    
        builder.queryParam(newParam, value);
    
        String finalUrl = builder.toUriString();
    
        // Use RestTemplate to make a GET request with the final URL
        // ...
        return result;