Spring MVC Servlet.xml To Java Config


I was trying to migrate from the good old servlet.xml to the new Java based configuration for one of my projects. It is quite simple and easy to pick up with all the annotations that are in use. Let's see how do we convert the servlet.xml to a java configuration class.

Below is a simple servlet.xml file which will be used as a reference to convert to corresponding Java configuration class:


<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 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-4.2.xsd http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

 <mvc:resources location="classpath:/META-INF/resources/"
  mapping="swagger-ui.html"></mvc:resources>
 <mvc:resources location="classpath:/META-INF/resources/webjars/"
  mapping="/webjars/**"></mvc:resources>

 <mvc:default-servlet-handler />
 <mvc:annotation-driven />
 <context:component-scan base-package="com.tgc.controller" />
 
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/pages/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 
 <bean
   id="testBean" class="com.tgc.TestBean">
 </bean>
</beans> 

Now follow the simple steps mentioned below to migrate to this servlet.xml to Java config class:

1. Create a new class named AppConfig under the package com.yourDomain.config (I've created mine under com.tgc.config)

Paste the following Java code

package com.tgc.config;
package com.tgc.config;

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.tgc.TestBean;

@Configuration // lets spring know that this is a configuration class
@EnableWebMvc // replacement for <mvc:annotation-driven/>
@ComponentScan(basePackages = { "com.tgc.controller" }) /* enables the scanning of packages for 
stereotyped annotations*/

/*we extend WebMvcConfigurerAdapter so that we can override the Resource handler methods, 
 * for instance, and configure the resources*/
public class AppConfig extends WebMvcConfigurerAdapter {

 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
                registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
                registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
 }

 // set default servlet handlers, same as <mvc:default-servlet-handler />
 @Override
 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
  configurer.enable();
 }

 @Override
 public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
  // TODO Auto-generated method stub
  super.configureHandlerExceptionResolvers(exceptionResolvers);
 }

 @Bean
 public InternalResourceViewResolver getInternalResourceViewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/pages/");
  resolver.setSuffix(".jsp");
  return resolver;
 }
 
 @Bean 
 public TestBean testBean(){
      return new TestBean();
   }
}

I believe the above java code is commented enough to make you guys understand the migration.
Comment below in case anything is not clear.

2. To enable spring to be aware of the usage of the @Configuration annotaion, we will have to make some additions to the web.xml file (I'll maybe write a post on how to get rid of the web.xml in favor of a java class). Check the comments in the below web.xml file to see what are the changes to be made. You basically got to add two init-param to define the config class and location where it is extended


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

 <display-name>Archetype Created Web Application</display-name>
 <servlet>
  <servlet-name>springrest</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
  
  <!-- add this to make spring aware of the usage of @Configuration annotation -->
  <!-- start -->
  <init-param>
   <param-name>contextClass</param-name>
   <param-value>
    org.springframework.web.context.support.AnnotationConfigWebApplicationContext
   </param-value>
  </init-param>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>
    com.tgc.config
   </param-value>
  </init-param>
  <!-- end -->
  
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>springrest</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

That was pretty much it. Try running your app now and let me know in case you need any help regarding this.

See you around.

Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

1 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete