Skip to content

Step by step spring mvc app using java config

July 1, 2013

Spring 3.0 provides option of configuration via java code. With out going into theory or advantages or disadvantages I will get into steps directly.

Step 1 : Create simple web  application using maven


mvn archetype:generate -DgroupId=org.opencab
    -DartifactId=cabms -DarchetypeArtifactId=maven-archetype-webapp
    -DinteractiveMode=false

Step 2: Convert solution to eclipse project

mvn eclipse:clean eclipse:eclipse -DdownloadSources=true
    -DdownloadJavadocs=true -Dwtpversion=2.0

Step 3: Create directory structure under src\main\java folder. rest is created by maven.

── pom.xml
── src
├── main
│   ├── java
│   │   └── org
│   │       └── opencab
│   │           ├── config
│   │           │   ├── Initializer.java
│   │           │   └── WebAppConfig.java
│   │           └── controller
│   │               └── HelloController.java
│   ├── resources
│   │   └── database.properties
│   └── webapp
│       ├── index.jsp
│       └── WEB-INF
│           └── web.xml
└── test

Step 4: Modify pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.opencab</groupId>
<artifactId>cabms</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>cabms Maven Webapp</name>
<url>http://maven.apache.org</url>

<properties>
<spring.version>3.2.3.RELEASE</spring.version>
<jdk.version>1.6</jdk.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- Servlet -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>cabms</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

Step 5 : Implement WebApplicationInitializer in your class and override onStartup method.

package org.opencab.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class Initializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
servletContext.addListener(new ContextLoaderListener(ctx));

ctx.setServletContext(servletContext);

Dynamic servlet = servletContext.addServlet("dispatcher",
new DispatcherServlet(ctx));
servlet.addMapping("/");

servlet.setLoadOnStartup(1);
}

}

Step 6 : Write webconfig

package org.opencab.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.opencab")
@PropertySource({ "classpath:database.properties" })
public class WebAppConfig {
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}

Step 7 : Write simple hello controller

package org.opencab.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

@RequestMapping(value = "/")
public String home() {
System.out.println("HomeController: Passing through...");
return "home";
}
}

That’s all you need to bring up simple application using spring javaConfig.
Note that web.xml file will to empty, since all the configuration are moved into java classes.
Full source code is available at https://github.com/rajendersaini/javaCfg

Advertisements

From → Tech

12 Comments
  1. alberto permalink

    hi,
    thanks for your tuto. When I setup a project using xml files, I have web.xml and servlet-xxx.xml .
    which file (Initializer.java and WebAppConfig.java) is equivalent of web.xml et servlet-xxx.xml ?
    and how can I map a ressource ( css and js files) like this in xml file ?

    Thanks

  2. Correct

    Initializer.java — web.xml
    WebAppConfig.java- servlet-xxx.xml

    for resource config
    refer to – http://stackoverflow.com/questions/14861720/annotation-configuration-replacement-for-mvcresources-spring

    • alberto permalink

      thanks
      I had in WebAppConfig.java:
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler(“/css/**”).addResourceLocations(“/css/”);
      }

      folder:
      webapp
      -css
      -WEB-INF

      In jsp file:

      style.css file doesn’t found again

      • can post your jsp file, I hope you are using /css/style.css ? enable debug logs in server and see what path it is looking while trying to display your jsp .

    • alberto permalink

      this is my jsp file:

      Home page

      Home page

      ${message}
      <!– Add new contact –>
      Les flux

  3. alberto permalink

    head

    Home page
    head

    body
    Home page

    ${message}
    <!– Add new contact –>
    Les flux

    body

  4. alberto permalink

    hi I can’t paste correctly html code here.

    I fix this issue using :
    – WebAppConfig extends WebMvcConfigurerAdapter
    – in WebAppConfig
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
    }

  5. Hey Rajender,

    thanks for this tutorial!

    I have – maybe a stupid – question (I am a J2EE/Spring beginner):
    I can deploy it on a tomcat but how i can test if it works?

    Thanks!

    Best Regards
    MK

  6. Just create the project in eclipse and configure eclipse to run with tomcat. Try these steps to configure your eclipse with tomcat.

    http://www.eclipse.org/webtools/jst/components/ws/M4/tutorials/InstallTomcat.html

  7. how configure filters for specific URLs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: