Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Path variable truncate after dot - annotation

I am trying to set up a REST endpoint that allows querying a user by their email address. The email address is the last portion of the path so Spring is treating [email protected] as the value foo@example and truncating the extension .com.

I found a similar question here Spring MVC @PathVariable with dot (.) is getting truncated However, I have an annotation based configuration using AbstractAnnotationConfigDispatcherServletInitializer and WebMvcConfigurerAdapter. Since I have no xml configuration, this solution will not work for me:

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

I have also tried this solution which uses regex but it has not worked either.

@RequestMapping(value = "user/by-email/{email:.+}")

Does anyone know how to turn off the suffix pattern truncation without xml?

like image 288
masstroy Avatar asked Dec 11 '14 09:12

masstroy


People also ask

What is difference between @PathParam and @PathVariable?

The @PathVariable annotation is used for data passed in the URI (e.g. RESTful web services) while @RequestParam is used to extract the data found in query parameters. These annotations can be mixed together inside the same controller. @PathParam is a JAX-RS annotation that is equivalent to @PathVariable in Spring.

What is PATH variable annotation in Spring boot?

The @PathVariable annotation is used to extract the value of the template variables and assign their value to a method variable. A Spring controller method to process above example is shown below; @RequestMapping("/users/{userid}", method=RequestMethod.

Can PathVariable be optional?

By design, in Spring MVC, it is not possible to have optional @PathVariable value. Still, we can use multiple path mappings to simulate this effect successfully.


3 Answers

The dot in the path variable at the end of the URI causes two unexpected behaviours (unexpected for the majority of users, except those familiar with the huge number of Spring configuration properties).

The first (which can be fixed using the {email:.+} regex) is that the default Spring configuration matches all path extensions. So setting up a mapping for /api/{file} will mean that Spring maps a call to /api/myfile.html to the String argument myfile. This is useful when you want /api/myfile.html, /api/myfile.md, /api/myfile.txt and others to all point to the same resource. However, we can turn this behaviour off globally, without having to resort to a regex hack on every endpoint.

The second problem is related to the first and correctly fixed by @masstroy. When /api/myfile.* points to the myfile resource, Spring assumes the path extension (.html, .txt, etc.) indicates that the resource should be returned with a specific format. This behaviour can also be very useful in some situations. But often, it will mean that the object returned by a method mapping cannot be converted into this format, and Spring will throw a HttpMediaTypeNotAcceptableException.

We can turn both off with the following (assuming Spring Boot):

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void configurePathMatch(PathMatchConfigurer configurer) {
    // turn off all suffix pattern matching
    configurer.setUseSuffixPatternMatch(false);
    // OR
    // turn on suffix pattern matching ONLY for suffixes
    // you explicitly register using
    // configureContentNegotiation(...)
    configurer.setUseRegisteredSuffixPatternMatch(true);
  }

  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false);
  }
}

More about Content Negotiation.

like image 188
bkjvbx Avatar answered Oct 09 '22 16:10

bkjvbx


You have to add trailing slash at the end of the path variable after name like

 @RequestMapping(value ="/test/{name}/")

The Request like

http://localhost:8080/utooa/service/api/admin/test/[email protected]/

like image 38
takeoffjava Avatar answered Oct 09 '22 15:10

takeoffjava


I've found the solution to this using the ContentNegotiationConfigurer bean from this article: http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

I added the following configuration to my WebConfig class:

@EnableWebMvc
@Configuration
@ComponentScan(basePackageClasses = { RestAPIConfig.class })
public class WebConfig extends WebMvcConfigurerAdapter {    
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }
}

By setting .favorPathExtension(false), Spring will no longer use the file extension to override the accepts mediaType of the request. The Javadoc for that method reads Indicate whether the extension of the request path should be used to determine the requested media type with the highest priority.

Then I set up my @RequestMapping using the regex

@RequestMapping(value = "/user/by-email/{email:.+}")
like image 7
masstroy Avatar answered Oct 09 '22 14:10

masstroy