In earlier posts we have seen How Spring MVC Path Variable work.
There is one issue with the @PathVariable. The last @PathVariable in the URL truncates the value passed after the . (dot).
In this post we will see the ways to fix the Spring MVC PathVariable truncate issue.
Spring MVC PathVariable Truncate Issue
We have a Controller method as shown below
1 2 3 4 5 6 7 8 9 10 |
@RequestMapping(value = "/employee/{id}/{email}", method = RequestMethod.GET) public String addEmployee(@PathVariable String id, @PathVariable String email) { System.out.println("*********************"); System.out.println("Employee ID : " + id); System.out.println("Employee Email Id : " + email); return "welcome"; } |
When we use the URL – http://localhost:8080/sampleproject/employee/100/kscodes@gmail.com we expect to get the output as
1 2 |
Employee ID : 100 Employee Email Id : kscodes@gmail.com |
But instead we get the output as
1 2 |
Employee ID : 100 Employee Email Id : kscodes@gmail |
As you may notice the part after .(dot) for the email is truncated by the @PathVariable.
We can fix this issue by 2 ways.
1. Using Regex
Use a regex :.+ and add it in the last PathVariable on whose values get truncated.
1 |
/employee/{id}/{email:.+} |
1 2 3 4 5 6 7 8 9 10 |
@RequestMapping(value = "/employee/{id}/{email:.+}", method = RequestMethod.GET) public String addEmployee(@PathVariable String id, @PathVariable String email) { System.out.println("*********************"); System.out.println("Employee ID : " + id); System.out.println("Employee Email Id : " + email); return "welcome"; } |
Now using http://localhost:8080/sampleproject/employee/100/kscodes@gmail.com will give us the complete value of email.
2. Using a slash at the end
Another way to handle the issue is to add a slash at the end of the URL.
1 |
/employee/{id}/{email}/ |
The only care you need to take is you will need to add the slash every request you make to the method.
http://localhost:8080/sampleproject/employee/100/kscodes@gmail.com/ , else you may get a 404 error.