Spring MVC @PathVariable getting truncated

JavaSpringRestSpring MvcGet

Java Problem Overview

I have a controller that provides RESTful access to information:

@RequestMapping(method = RequestMethod.GET, value = Routes.BLAH_GET + "/{blahName}")
public ModelAndView getBlah(@PathVariable String blahName, HttpServletRequest request,
                            HttpServletResponse response) {

The problem I am experiencing is that if I hit the server with a path variable with special characters it gets truncated. For example: http://localhost:8080/blah-server/blah/get/blah2010.08.19-02:25:47

The parameter blahName will be blah2010.08

However, the call to request.getRequestURI() contains all the information passed in.

Any idea how to prevent Spring from truncating the @PathVariable?

Java Solutions

Solution 1 - Java

Try a regular expression for the @RequestMapping argument:

RequestMapping(method = RequestMethod.GET, value = Routes.BLAH_GET + "/{blahName:.+}")

Solution 2 - Java

This is probably closely related to SPR-6164. Briefly, the framework tries to apply some smarts to the URI interpretation, removing what it thinks are file extensions. This would have the effect of turning blah2010.08.19-02:25:47 into blah2010.08, since it thinks the .19-02:25:47 is a file extension.

As described in the linked issue, you can disable this behaviour by declaring your own DefaultAnnotationHandlerMapping bean in the app context, and setting its useDefaultSuffixPattern property to false. This will override the default behaviour, and stop it molesting your data.

Solution 3 - Java

Spring considers that anything behind the last dot is a file extension such as .jsonor .xml and truncate it to retrieve your parameter.

So if you have /{blahName}:

  • /param, /param.json, /param.xml or /param.anything will result in a param with value param
  • /param.value.json, /param.value.xml or /param.value.anything will result in a param with value param.value

If you change your mapping to /{blahName:.+} as suggested, any dot, including the last one, will be considered as part of your parameter:

  • /param will result in a param with value param
  • /param.json will result in a param with value param.json
  • /param.xml will result in a param with value param.xml
  • /param.anything will result in a param with value param.anything
  • /param.value.json will result in a param with value param.value.json
  • ...

If you don't care of extension recognition, you can disable it by overriding mvc:annotation-driven automagic:

<bean id="handlerMapping"
    <property name="contentNegotiationManager" ref="contentNegotiationManager"/>
    <property name="useSuffixPatternMatch" value="false"/>

So, again, if you have /{blahName}:

  • /param, /param.json, /param.xml or /param.anything will result in a param with value param
  • /param.value.json, /param.value.xml or /param.value.anything will result in a param with value param.value

Note: the difference from the default config is visible only if you have a mapping like /something.{blahName}. See Resthub project issue.

If you want to keep extension management, since Spring 3.2 you can also set the useRegisteredSuffixPatternMatch property of RequestMappingHandlerMapping bean in order to keep suffixPattern recognition activated but limited to registered extension.

Here you define only json and xml extensions:

<bean id="handlerMapping"
    <property name="contentNegotiationManager" ref="contentNegotiationManager"/>
    <property name="useRegisteredSuffixPatternMatch" value="true"/>

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false"/>
    <property name="favorParameter" value="true"/>
    <property name="mediaTypes">

Note that mvc:annotation-driven accepts now a contentNegotiation option to provide a custom bean but the property of RequestMappingHandlerMapping has to be changed to true (default false) (cf. https://jira.springsource.org/browse/SPR-7632).

For that reason, you still have to override all the mvc:annotation-driven configuration. I opened a ticket to Spring to ask for a custom RequestMappingHandlerMapping: https://jira.springsource.org/browse/SPR-11253. Please vote if you are interested in.

While overriding, be careful to consider also custom Execution management overriding. Otherwise, all your custom Exception mappings will fail. You will have to reuse messageCoverters with a list bean:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />

<util:list id="messageConverters">
    <bean class="your.custom.message.converter.IfAny"></bean>
    <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.StringHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>

<bean name="exceptionHandlerExceptionResolver"
    <property name="order" value="0"/>
    <property name="messageConverters" ref="messageConverters"/>

<bean name="handlerAdapter"
    <property name="webBindingInitializer">
        <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="conversionService" ref="conversionService" />
			<property name="validator" ref="validator" />
    <property name="messageConverters" ref="messageConverters"/>

<bean id="handlerMapping"

I implemented, in the open source project Resthub that I am part of, a set of tests on these subjects: see https://github.com/resthub/resthub-spring-stack/pull/219/files and https://github.com/resthub/resthub-spring-stack/issues/217

Solution 4 - Java

Everything after the last dot is interpreted as file extension and cut off by default.
In your spring config xml you can add DefaultAnnotationHandlerMapping and set useDefaultSuffixPattern to false (default is true).

So open your spring xml mvc-config.xml (or however it is called) and add

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
	<property name="useDefaultSuffixPattern" value="false" />

Now your @PathVariable blahName (and all other, too) should contain the full name including all dots.

EDIT: Here is a link to the spring api

Solution 5 - Java

Using the correct Java configuration class :

public class WebConfig extends WebMvcConfigurerAdapter

    public void configureContentNegotiation(ContentNegotiationConfigurer configurer)

    public void configurePathMatch(PathMatchConfigurer configurer)

Solution 6 - Java

I also ran into the same issue, and setting the property to false didn't help me either. However, the API says:

> Note that paths which include a ".xxx" suffix or end with "/" already > will not be transformed using the default suffix pattern in any case.

I tried adding "/end" to my RESTful URL, and the problem went away. I'm not please with the solution, but it did work.

BTW, I don't know what the Spring designers were thinking when they added this "feature" and then turned it on by default. IMHO, it should be removed.

Solution 7 - Java

I resolved by this hack

  1. Added HttpServletRequest in @PathVariable like below

    @PathVariable("requestParam") String requestParam, HttpServletRequest request) throws Exception {

  2. Get the URL directly (At this level no truncation) in the request



Solution 8 - Java

adding the ":.+" worked for me, but not until I removed outer curly brackets.

value = {"/username/{id:.+}"} didn't work

value = "/username/{id:.+}" works

Hope I helped someone :]

Solution 9 - Java

I just ran into this and the solutions here didn't generally work as I expected.

I suggest using a SpEL expression and multiple mappings, e.g.

@RequestMapping(method = RequestMethod.GET, 
    value = {Routes.BLAH_GET + "/{blahName:.+}", 
             Routes.BLAH_GET + "/{blahName}/"})

Solution 10 - Java

The file extension problem only exists if the parameter is in the last part of the URL. Change

@RequestMapping(method = RequestMethod.GET, value = Routes.BLAH_GET + "/{blahName}")


   method = RequestMethod.GET, value = Routes.BLAH_GET + "/{blahName}/safe")

and all will be well again-

Solution 11 - Java

If you can edit the address that requests are sent to, simple fix would be to add a trailing slash to them (and also in the @RequestMapping value):


so the mapping would look like:

RequestMapping(method = RequestMethod.GET, value = Routes.BLAH_GET + "/{blahName}/")

See also Spring MVC @PathVariable with dot (.) is getting truncated.

Solution 12 - Java

//in your xml dispatcher  add this property to your default annotation mapper bean as follow
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="alwaysUseFullPath" value="true"></property>

Solution 13 - Java

Java based configuration solution to prevent truncation (using a not-deprecated class):

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

public class PolRepWebConfig extends WebMvcConfigurationSupport {

	public RequestMappingHandlerMapping requestMappingHandlerMapping() {
		final RequestMappingHandlerMapping handlerMapping = super
		// disable the truncation after .
		// disable the truncation after ;
		return handlerMapping;

[Source: http://www.javacodegeeks.com/2013/01/spring-mvc-customizing-requestmappinghandlermapping.html][1]


I realized having some problems with Spring Boot auto-configuration when I used the approach above (some auto-configuration doesn't get effective).

Instead, I started to use the BeanPostProcessor approach. It seemed to be working better.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {
	private static final Logger logger = LoggerFactory

	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;

	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		if (bean instanceof RequestMappingHandlerMapping) {
			setRemoveSemicolonContent((RequestMappingHandlerMapping) bean,
			setUseSuffixPatternMatch((RequestMappingHandlerMapping) bean,
		return bean;

	private void setRemoveSemicolonContent(
			RequestMappingHandlerMapping requestMappingHandlerMapping,
			String beanName) {
				"Setting 'RemoveSemicolonContent' on 'RequestMappingHandlerMapping'-bean to false. Bean name: {}",

	private void setUseSuffixPatternMatch(
			RequestMappingHandlerMapping requestMappingHandlerMapping,
			String beanName) {
				"Setting 'UseSuffixPatternMatch' on 'RequestMappingHandlerMapping'-bean to false. Bean name: {}",

[Inspired from: http://ronaldxq.blogspot.com/2014/10/spring-mvc-setting-alwaysusefullpath-on.html][2]

[1]: http://www.javacodegeeks.com/2013/01/spring-mvc-customizing-requestmappinghandlermapping.html "Source"

[2]: http://ronaldxq.blogspot.com/2014/10/spring-mvc-setting-alwaysusefullpath-on.html "Source2"

Solution 14 - Java

if you are sure that your text will not match any of default extensions you can use below code:

public class WebConfig extends WebMvcConfigurerAdapter {

    public void configurePathMatch(PathMatchConfigurer configurer) {

Solution 15 - Java

My preferable solution to prevent the Spring MVC @PathVariable to get truncated is to add trailing slash at the end of the path variable.

For example:

@RequestMapping(value ="/email/{email}/")

So, the request will look like:


Solution 16 - Java

The problem that you are facing is due to spring interpreting the last part of the uri after the dot (.) as a file extension like .json or .xml . So when spring tries to resolve the path variable it simply truncates the rest of the data after it encounters a dot (.) at the end of the uri. Note: also this happens only if you keep the path variable at the end of the uri.

For example consider uri : https://localhost/example/gallery.df/link.ar

public class CustomController {
    public void example(@PathVariable("firstValue") String firstValue,
      @PathVariable("secondValue") String secondValue) {
        // ...  

In the above url firstValue = "gallery.df" and secondValue="link" , the last bit after the . gets truncated when the path variable gets interpreted.

So, to prevent this there is two possible ways:

1.) Using a regexp mapping

Use a regex at the end part of mapping

public void example(
  @PathVariable("firstValue") String firstValue,
  @PathVariable("secondValue") String secondValue) {

By using + , we indicate any value after the dot will also be part of the path variable.

2.) Adding a slash at the end of our @PathVariable

public void example(
  @PathVariable("firstValue") String firstValue,
  @PathVariable("secondValue") String secondValue) {

This will enclose our second variable protecting it from Spring’s default behavior.

3) By overriding Spring's default webmvc configuration

Spring provides ways to override the default configurations that gets imported by using the annotations @EnableWebMvc.We can customize the Spring MVC configuration by declaring our own DefaultAnnotationHandlerMapping bean in the application context and setting its useDefaultSuffixPattern property to false. Example:

public class CustomWebConfiguration extends WebMvcConfigurationSupport {
    public RequestMappingHandlerMapping 
      requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping
          = super.requestMappingHandlerMapping();
        return handlerMapping;

Keep in mind that overriding this default configuration, affects all urls.

Note : here we are extending the WebMvcConfigurationSupport class to override the default methods. There is one more way to override the deault configurations by implementing the WebMvcConfigurer interface. For more details on this read : https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/EnableWebMvc.html


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionphogelView Question on Stackoverflow
Solution 1 - JavaearldouglasView Answer on Stackoverflow
Solution 2 - JavaskaffmanView Answer on Stackoverflow
Solution 3 - JavabmeurantView Answer on Stackoverflow
Solution 4 - JavaJanView Answer on Stackoverflow
Solution 5 - JavajebeaudetView Answer on Stackoverflow
Solution 6 - JavaSteve11235View Answer on Stackoverflow
Solution 7 - JavaKanagavelu SugumarView Answer on Stackoverflow
Solution 8 - JavaMartin ČejkaView Answer on Stackoverflow
Solution 9 - JavaMark ElliotView Answer on Stackoverflow
Solution 10 - JavachrismarxView Answer on Stackoverflow
Solution 11 - JavaMichał RybakView Answer on Stackoverflow
Solution 12 - JavaFareed AlnamroutiView Answer on Stackoverflow
Solution 13 - JavaburcakulugView Answer on Stackoverflow
Solution 14 - JavaBassem Reda ZohdyView Answer on Stackoverflow
Solution 15 - JavaJohnnyView Answer on Stackoverflow
Solution 16 - JavaAnanthapadmanabhanView Answer on Stackoverflow