Getting started with Spring MVC

Let me introduce you to setup a very basic Spring 4 web application. I will demonstrate it in step-by-step:

  • Step 1 : We will use maven as build tool for our project. I have 3.3.9 installed in my machine and Java version is 1.8. To create a web template, type this in command line:

mvn archetype:generate -DgroupId=com.naveenlabs -DartifactId=SimpleWebApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

  • Step 2 : Now, go inside the folder SimpleWebApp, and edit pom.xml file. I imported the project into IntelliJ Idea. We will use light weight Jetty web server plugin as well. Update your pom file to this,
<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>com.naveenlabs</groupId>
  <artifactId>SimpleWebApp</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SimpleWebApp Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <jdk.version>1.8</jdk.version>
    <spring.version>4.2.2.RELEASE</spring.version>
    <jstl.version>1.2</jstl.version>
    <servletapi.version>3.1.0</servletapi.version>
  </properties>


  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- JSTL for views -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <!-- compile only, runtime container will provide this -->
    <!-- Need this for config annotation -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servletapi.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
  <build>
    <finalName>SimpleWebApp</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>${jdk.version}</source>
          <target>${jdk.version}</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.2.11.v20150529</version>
        <configuration>
          <scanIntervalSeconds>10</scanIntervalSeconds>
          <webApp>
            <contextPath>/myapp</contextPath>
          </webApp>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

  • Step 3 : Now, run the command :
    mvn dependency:resolve
  • Step 4 : After all the dependencies are there, you can run the command :
    mvn jetty:run

    The above command will allow you to test if the web application and web server is running fine on your local system. If the web server starts properly, then it will show something like this on command line

screen-shot-2016-09-29-at-8-17-35-pm

Now, the above screen shows us that if we go to http://localhost:8080/myapp, it will show the default Hello World. So, that will make sure that our initial setup is alright. Let us move to make this spring application.

  • Step 5 : At this moment we need to add few files and folders to the existing app, such as java/com/naveenlabs/controllers etc. , and the whole folder structure should look like this, ( you can compare the folders and files and just add it to your app):

screen-shot-2016-09-29-at-8-34-35-pm

  • Step 6 : Let us edit our web.xml and update it with this:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

  <display-name>Counter Web Application</display-name>

  <servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
  </context-param>

  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
</web-app>


  • Step 7 : Edit your spring-mvc-servlet.xml file and update it with this contents:

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

<context:component-scan base-package=”com.naveenlabs.controllers” />

<bean
class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”prefix”>
<value>/WEB-INF/templates/</value>
</property>
<property name=”suffix”>
<value>.jsp</value>
</property>
</bean>

</beans>

  • Step 8 : In your HomeController.java, edit it with the following content:

package com.naveenlabs.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {

private static int counter = 0;
private static final String VIEWNAME = “home”;

@RequestMapping(value = “/”, method = RequestMethod.GET)
public String welcome(ModelMap model) {

model.addAttribute(“message”, “Welcome”);
model.addAttribute(“counter”, ++counter);
// logger.debug(“[welcome] counter : {}”, counter);

// Spring uses InternalResourceViewResolver and return back index.jsp
return VIEWNAME;

}

@RequestMapping(value = “/{name}”, method = RequestMethod.GET)
public String welcomeName(@PathVariable String name, ModelMap model) {

model.addAttribute(“message”, “Welcome ” + name);
model.addAttribute(“counter”, ++counter);
// logger.debug(“[welcomeName] counter : {}”, counter);
return VIEWNAME;

}

}

 

  • Step 9 : And, finally your home.jsp should be :
<html>
<body>
<h1>Maven + Spring MVC Web Project Example</h1>

<h2>Message : ${message}</h2>
<h2>Counter : ${counter}</h2>
</body>
</html>
  • Step 10 :  Do,  mvn package and then mvn jetty:run to run the application, Now, if you go to http://localhost:8080/myapp/, it will show :

screen-shot-2016-09-29-at-9-17-34-pm