Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Spring MVC DispatcherServlet to avoid url's with extensions?

I've a Spring (4.1.6.RELEASE) MVC project with a controller that is mapped to /home, but my problem is that it's also invoked for paths like /home.html or /home.do

My configuration is:

web.xml:

   <servlet>
      <servlet-name>main</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>main</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>

main-servlet.xml:

   <mvc:annotation-driven />
   <mvc:resources mapping="/resources/**" location="/resources/" />
   <!-- ... -->
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

HomeController.java:

@Controller
@RequestMapping({"/", "/home"})
public class HomeController {  
   @RequestMapping(method = RequestMethod.GET)
   public String doGet(Model model) {
        // ...
        return "home";
    }
}

As suggested in similar questions:

  • Spring MVC; avoiding file extension in url?
  • Spring MVC: Avoiding file extension in URL
  • spring mvc how to bypass DispatcherServlet for *.html files?

I've tried adding the following configurations:

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

and

   <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
      <property name="useSuffixPatternMatch" value="false" />
      <property name="useRegisteredSuffixPatternMatch" value="false" />
   </bean>

but without success.

When I debug the DispatcherServlet I can see that the instances of RequestMappingHandlerMapping and DefaultAnnotationHandlerMapping haven't set the above commented properties to false.

enter image description here

It seems that a simple configuration should do it, but I'm missing something that I'm unable to find out.

How should I properly configure the DispatcherServlet to avoid file extensions in mapped paths?

Thanks in advance.

like image 603
Tobías Avatar asked Apr 30 '15 10:04

Tobías


1 Answers

As per Spring doc the config should be under mvc:annotation-driven, e.g.

  <mvc:annotation-driven>
    <mvc:path-matching suffix-pattern="false" />
  </mvc:annotation-driven>

as explained in the docs

Whether to use suffix pattern match (".*") when matching patterns to requests. If enabled a method mapped to "/users" also matches to "/users.*". The default value is true.

like image 196
Master Slave Avatar answered Oct 31 '22 20:10

Master Slave