Monday, August 9, 2021

Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation

In your Spring Web MVC application if you are using @PathVariable annotation along with @RequestMapping annotation to retrieve the parameter from the request path, then you may come across one problem- If the passed parameter has a value with a dot in it (i.e. xxx.xx) then the portion after the last dot (.), including dot, gets truncated when the value is assigned to the variable annotated with @PathVariable annotation.

For example– If you have a handler method in your controller like below.

@RequestMapping(value = "/ip/{address}")
public void processIP(@PathVariable("address") String address) {
 ..
 ..
}

Then the URI /ip/345.67.56.45 will assign 345.67.56 to the variable address.
URI /ip/198.201.231 will assign 198.201 to the variable address.

So, you can see that the value starting from the last dot is always truncated while assigning to the variable annotated with @PathVariable annotation.

Solution to the Spring @PathVariable dot truncation problem

Solution for this truncation problem is to include a regex (.+) in the @RequestMapping URI. Here regex (.+) means- match one or more of the token given with (+). That way you are explicitly asking Spring framework to match all the tokens (. in this case) and don’t leave any.

Thus the handler method should be written as following to avoid the dot (.) truncation problem in Spring MVC application.

@RequestMapping(value = "/ip/{address:.+}")
public void processIP(@PathVariable("address") String address) {
 ..
 ..
}

That's all for this topic Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Web MVC Tutorial
  2. Spring MVC @RequestParam Annotation Example
  3. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example
  4. Spring MVC File Upload (Multipart Request) Example
  5. Spring Transaction Management Example - @Transactional Annotation and JDBC

You may also like-

  1. Connection Pooling With Apache DBCP Spring Example
  2. BeanPostProcessor in Spring Framework
  3. Excluding Bean From Autowiring in Spring
  4. Circular Dependency in Spring Framework
  5. How HashMap Internally Works in Java
  6. Executor And ExecutorService in Java With Examples
  7. instanceof Operator in Java With Examples
  8. How to Read Input From Console in Java

No comments:

Post a Comment