By default in JAX-RS, all URLs specified in @Path annotations are CASE-SENSITIVE. In this tutorial, I am giving a simple example of CASE-INSENSITIVE URLs that can be used inside @Path annotation on any Jersey JAX-RS REST API.
1. How to Make URLs Case-Insensitive?
Jersey @Path annotation can accept regular expressions to define case-insensitive patterns directly. We can use the regular expressions in the @Path URLs to make URLs case-insensitive. Consider the following request mapping.
@Path("/{employees}")
public class JerseyService {
//Code
}
We can change the URL and use the (?i)
regex flag to make the path case-insensitive. This flag makes the pattern match both upper and lower-case variations of the specified path segment. After this change, Jersey will match all variations such as “employees“, “Employees“, “EMPLOYEES“, etc.
@Path("/{employees : (?i)employees}")
public class JerseyService {
//Code
}
Now the above @Path annotation will be able to match any variation of lowercase and UPPERCASE letters in employees
.
Please note that for this example, I am using Jersey 2.19.
2. Using Jersey’s ResourceConfig
We can also override Jersey’s default ApplicationHandler to handle case-insensitivity in all incoming requests. We start with creating a custom ApplicationHandler to transform all paths to lowercase.
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ResourceConfig;
public class CaseInsensitiveApplicationHandler extends ApplicationHandler {
public CaseInsensitiveApplicationHandler(ResourceConfig resourceConfig) {
super(resourceConfig);
}
@Override
public void handleRequest(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
String path = requestContext.getUriInfo().getPath().toLowerCase();
requestContext.setRequestUri(URI.create(path), URI.create(path));
super.handleRequest(requestContext, responseContext);
}
}
Next, in the ResourceConfig setup, register this custom handler.
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;
@ApplicationPath("api")
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("com.example.demo");
// Register custom ApplicationHandler
register(new CaseInsensitiveApplicationHandler(this));
}
}
3. Demo
Here, I have modified the source code of my previous Jersey RESTful Client example.
I sent the following requests to the HTTP GET /{employees : (?i)employees} path, and all paths match correctly.
http://localhost:8080/JerseyDemos/rest/EMPLOYEES

http://localhost:8080/JerseyDemos/rest/EmPlOyEEs

http://localhost:8080/JerseyDemos/rest/employees
Feel free to contact if you find any problem in this example.
Happy Learning !!
Comments