user3386700
user3386700

Reputation: 31

Is there any way we make PathVariable name case insensitive in Spring?

I have an URI https://localhost/Message/message?id=10 and it will give the message details with id=10.

I want to get the same response when I entered the URI as below (here path variable is with different case)

 https://localhost/Message/message?id=10 
 https://localhost/Message/Message?ID=10 
 https://localhost/Message/mEssage?Id=10 
 https://localhost/Message/MESSAGE?iD=10 

Upvotes: 3

Views: 3407

Answers (2)

Kevin O.
Kevin O.

Reputation: 448

For Spring Boot 3.2.4 use the following code:

package com.mycompany.homepage.security;

import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.util.pattern.PathPatternParser;

@Configuration
@ComponentScan(basePackages = "com.mycompany.homepage.security")
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // Set URLs not-case-sensitive.
        PathPatternParser parser = new PathPatternParser();
        parser.setCaseSensitive(false);
        configurer.setPatternParser(parser);
    }
}

Upvotes: 1

hovanessyan
hovanessyan

Reputation: 31473

For the URI/PathVariable (Message) name: Spring 4.2+ supports configuration of case-insensitive path matching. You can configure it as follows:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher matcher = new AntPathMatcher();
        matcher.setCaseSensitive(false);
        configurer.setPathMatcher(matcher);
    }
}

For the @RequestParam/request parameters (ID) part:

You have to do it manually - there's no support in Spring Boot for this out of the box. The base concept is that you have to implement a custom servlet filter, which standardizes the params in HttpServletRequest - e.g. you can apply to all of them String.toLowerCase() before passing them down to your @RestController, where you have all the request parameter binding defined as lower-cased values.

Upvotes: 3

Related Questions