Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringMVC @PathVariable is truncated

I am using SpringMVC 3.1.3. @PathVariable is truncated/trimmed if it has whitespaces in the end. Is there a way so prevent the trimming

 @RequestMapping(value="deleteConfig/{id}/", method=RequestMethod.DELETE)
 public @ResponseBody JsonResponse<?> deleteConfig(@PathVariable("id") String id) 

If the id from the client has a space in the end like - "abc " or even "abc%20" then the variable id I get in the controller is just "abc" instead of "abc "

Can you advise a way to fix this

like image 843
dogfish Avatar asked Oct 31 '22 23:10

dogfish


1 Answers

The problem is in the AntPatternMatcher class of Spring Framework. The MVC use this class to find what method and controller must be call based on the pattern but its responsable to extract path variables too.

If you looking inside this class you can see:

    String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator);
    String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator);

This calls tokenizen the url in tokens separated by "/", but trim the string also. The simple way is to change the second line to:

    String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator, false, true);

This call the 'false' indicate that you don't want to trim the strings.

But the bad new is that this class is in spring framework. Then you need to extend this class or copy and change this and indicate to spring that use your own class instead the spring class.

You need to change the DefaultAnnotationHandler in your web context like this:

<bean
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="pathMatcher">
        <bean class="practica1.impl.OwnAntPathMatcher" />
    </property>
</bean>

Whith this lines you explicit create the 'DefaultAnnotationHandlerMapping' and establish the PathMatcher to your modified version of AntPathMatcher.

Be carefully because if you create one handler mapping explicitly in the context, all other default handlers are not created.

like image 193
Fernando Rincon Avatar answered Nov 15 '22 05:11

Fernando Rincon