Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of mvc:default-servlet-handler in Spring annotation-based configuration?

Is it possible to have the equivalent of <mvc:default-servlet-handler/> defined in an AnnotationConfig(Web)ApplicationContext? Right now I have:

@Configuration
@ImportResource("classpath:/mvc-resources.xml")
class AppConfig {
  // Other configuration...
}

with just the following in my resources/mvc-resources.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:default-servlet-handler/>
</beans>

And it works as expected. Is it possible to do this without importing an XML file? It would be a nice way to cut down on some boilerplate.

like image 388
haxney Avatar asked Feb 21 '11 05:02

haxney


People also ask

What is a handler in Spring MVC?

What Is a Handleradapter? The HandlerAdapter is basically an interface which facilitates the handling of HTTP requests in a very flexible manner in Spring MVC. It's used in conjunction with the HandlerMapping, which maps a method to a specific URL. The DispatcherServlet then uses a HandlerAdapter to invoke this method.

What is true about @RequestMapping annotation in Spring MVC?

The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.


2 Answers

If you are using Spring 3.1 with WebMvc, you can configure default servlet handling like this:

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
like image 98
Olegs Briska Avatar answered Oct 10 '22 15:10

Olegs Briska


After digging a bit deeper, I found out that this is a known problem and is addressed by annotation features in the upcoming Spring 3.1.

I solved my problem with the following code:

@Configuration
@Import(FeatureConfig.class)
class AppConfig {
   ...
}

@FeatureConfiguration
class FeatureConfig {
  @Feature
  public MvcDefaultServletHandler defaultHandler() {
    return new MvcDefaultServletHandler();
  }
}

This does require using the milestone version of spring, though, but it seems to be the cleanest and preferred way of handling this.

like image 44
haxney Avatar answered Oct 10 '22 16:10

haxney