Open In App

Spring MVC – WebMvcConfigure

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Spring WebMvcConfigurer enables developers to customize the default MVC setups in Spring applications. By implementing this interface, users can customize several features of the MVC framework, such as interceptors, resource handling, and view controllers.

In this article, we will learn how to Customize Default MVC Configurations with WebMvcConfigure.

Default MVC Configurations in Spring

  • Request Mapping: Spring MVC maps requests to controllers using logical default patterns. Controller methods are annotated with @RequestMapping, and by default, their method names are used to match URLs.
  • DispatcherServlet: This is the main component of Spring MVC. By accepting all incoming requests and forwarding them to the relevant controllers, it serves as a front controller.
  • Model Binding: To make processing form submissions easier, Spring MVC automatically ties request parameters to method parameters.
  • View Resolution: Spring MVC’s default view resolution is intended to be adaptable. It finds the relevant view templates by combining configuration and convention.

Spring WebMvcConfigure Method

  • addViewControllers: Set up basic automated controllers that are preconfigured to display the body of the response and/or the response status code.
  • set upAsyncSupport: Set up settings for processing asynchronous requests.
  • set upContentNegotiation: Configure content negotiation options.
  • set upDefaultServletHandling: Set up a handler to pass unprocessed requests to the “default” servlet in the Servlet container.
  • addInterceptors: To pre- and post-process controller method calls and resource handler requests, add Spring MVC lifecycle interceptors.
  • addResourceHandlers: Add handlers to the classpath, the web application root, and other places to serve static resources like images, js, and css files.
  • addReturnValueHandlers: To enable custom controller method return value types, add handlers.

Customize Default MVC Configurations with WebMvcConfigure

Configure View Resolvers

We may configure view prefixes and suffixes, implement custom view resolvers, and manage the resolution process by overriding the view Resolver() function.

Java




@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
  
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/jsp/", ".jsp").cache(true);
    }
}


Configure View Mappings

This is used when we are not handling the request using @Controller handler method , rather want’s to map a URL directly to view template.

Java




@Configuration
public class WebConfig implements WebMvcConfigurer {
  
    @Override
    public void
    addViewControllers(ViewControllerRegistry registry)
    {
        registry.addViewController("/home").setViewName(
            "home");
        registry.addViewController("/about").setViewName(
            "about");
    }
}


Configure Static Resource Handling

When your web app needs static resources like CSS, JavaScript, or images, this configuration takes charge.Spring MVC delivers them directly and sets the correct Content-Type.

Java




@Configuration
public class WebConfig implements WebMvcConfigurer {
  
    @Override
    public void
    addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/resources/**")
            .addResourceLocations("/static/")
            .setCacheControl(
                CacheControl.maxAge(3, TimeUnit.DAYS)
                    .cachePublic());
    }
}


Configure Interceptors

Spring MVC Interceptors empower developers to intercept and inject custom logic at key points in the web request lifecycle. It allows developer to inject these actions before or after any request, keeping the code clean and efficient.

Java




public class LoggingInterceptor
    implements HandlerInterceptor {
  
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler)
        throws Exception
    {
        System.out.println("Request received for: "
                           + request.getRequestURI());
        return true;
    }
}


Configure Default Content Negotiation

By default, Spring MVC uses the Accept header in the HTTP request to determine the client’s media type preference. If the client doesn’t specify a preference, the server may use a default media type, such as JSON or XML, depending on the configuration.

Java




@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
  
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON); 
        configurer.favorPathExtension(true); 
        configurer.mediaType("xml", MediaType.APPLICATION_XML); 
        configurer.mediaType("json", MediaType.APPLICATION_JSON); 
    }
      
}


Configure Message Converters

Common data formats are supported by a set of default message converters included with Spring MVC. These consist of converters for form data, XML, JSON, and other formats.

Java




@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
  
    @Override
    public void configureMessageConverters(
        List<HttpMessageConverter> converters)
    {
        converters.add(new MyCustomMessageConverter());
    }
}


Configure Argument Resolvers

In Spring MVC, argument resolvers offer an option to manage the resolution of method arguments prior to the invocation of a controller method. They enable programmers to add their own custom logic—like pulling data from request headers, attributes, or other sources—to resolve method parameters.

Java




public class CustomLocalDateArgumentResolver
    implements HandlerMethodArgumentResolver {
  
    private final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  
    @Override
    public boolean
    supportsParameter(MethodParameter parameter)
    {
        return parameter.getParameterType().equals(
            LocalDate.class);
    }
  
    @Override
    public Object
    resolveArgument(MethodParameter parameter,
                    ModelAndViewContainer mavContainer,
                    NativeWebRequest webRequest,
                    WebDataBinderFactory binderFactory)
        throws Exception
    {
  
        String dateStr = webRequest.getParameter("date");
        if (dateStr != null) {
            return LocalDate.parse(dateStr, dateFormatter);
        }
        return null;
    }
}


Conclusion

So, this is Spring WebMvcConfigure – Customize Default MVC Configurations. Configuring different parts of a Spring MVC application is essential to creating reliable and adaptable online applications. Application behaviour may be customised to meet unique requirements by first comprehending and modifying default MVC setups.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads