Follow

Welcome to TechYari!

Tutorials on webdesign, web development and more...

Getting Started with Spring 4 MVC : Hello World Tutorial



By  Vipin Dubey     6/02/2015    Labels:,, 
In this tutorial we will create a Simple Hello World web application in Spring MVC with Anotation based Configuration. To work with this tutorial you will require few tools and jar files, refer below for requirements and details on setting up the environment for Spring MVC web application development.

Requirements

  1. Java Development Kit (JDK) 1.7 or higher
  2. Spring Source Tool Suite (STS) or Eclipse with Maven and STS Plugin
  3. Maven 3 or higher
  4. Deafult STS server (Pivotal tc server) / Apache Tomcat 7 or higher
  5. Working internet connection (for maven to download dependencies)

Spring MVC is one of the most popular MVC framework used in Java programming. In this Post we will create a very simple spring MVC app with minimal configuration.  

Setting Up Development Environment

  • Download JDK if you already don't have from http://www.oracle.com/technetwork/java/javase/downloads/index.html
  • Install JDK and configure JAVA_HOME environment variable as well as add bin directory of installed Java to your PATH variable in windows.
  • Download and install maven and configure M2_HOME environment variable with installed path, also add another environment variable called M2 and point it to bin directory of installed maven.
  • Download STS open it and create a new workspace for your projects.
  • Add Maven to STS.

Creating a new Spring MVC project using Maven

Now it's time to create a new Spring MVC project. Open STS and click on File->New->Other->Maven Project . Fill in required details. Refer below screenshot. Switch Perspective Mode to Spring or Java EE in STS.

Adding Maven Dependencies to POM.xml for Spring MVC

When you created a new Maven Project it created a POM.xml file as well, as we are going to create this project in Spring MVC we need all the required Spring MVC jar's to support the development, we are also going to use JSP and JSTL for display hence we will add those jars as well in maven as a dependency. Your pom.xml should look like below once you have added all the dependencies. If your Eclipse/STS does not contain a maven configured, you can configure it via going into Windows->Preference->Maven from Eclipse/STS toolbar.
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>in.techyari</groupId>
    <artifactId>helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>
</project>

Creating Packages and Folders to hold Java and view Files

Now create two new packages inside src folder-
  • in.techyari.helloworld.config
  • in.techyari.helloworld.controller
Also create following folder structure to hold JSP files-
  • Right click on WebContent folder and create a folder named WEB-INF. Now create a folder named views inside WEB-INF and then a folder name jsp inside views. Yo can refer the screenshot below to understand the structure of the folders.

Spring MVC Configuration

Normally a web app requires web.xml file as an initialization point to run. However we will use Java Based Configuration with Annotations to run our app which is simpler than xml based configurations. This configuration is supported in all servers with web 3.0 module. I am using Pivotal server here which came prebundled with STS, however you can install tomact 7 or higher locally and use it to run this app and it should run pretty smoothely.

Creating ApplicationInitializer class (A replacement for web.xml)

click on in.techyari.helloworld.config package and create a new class named ApplicationInitializer which extends extends AbstractAnnotationConfigDispatcherServletInitializer. Look at the code block below
package in.techyari.helloworld.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer  {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{MyAppConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

Configuring our application to use Spring WebMVC and JSP to render views

create another class named MyAppConfig which extends extends WebMvcConfigurerAdapter. See below code block. It will server following purpose :
  1. It will act as a one stop configuration point for our web app (for almost everything like dispatcher-servlet.xml file)
  2. We will configure the base packages to scan for url routes controllers ( i.e. mapping URI to controllers)
  3. It will enable SpringWebMVC for us.
  4. Provide the view resolver as JSP and define jsp folder to map to view names returned from controllers.
  5. All of this is done using Annotations.
package in.techyari.helloworld.config;

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

@Configuration
@ComponentScan(basePackages="in.techyari.helloworld.controller")
@EnableWebMvc
public class MyAppConfig extends WebMvcConfigurerAdapter{
    @Bean
    InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

Creating our HomeController

Create a new class named HomeController inside in.techyari.helloworld.controller package. This file will map our root url to welcome.jsp page and will display whatever message (data) we pass from controller. We do following things here, See code block below.
  1. We add an Annotation @controller to specify that this class is one of the controller for our web app.
  2. We create a method with name welcome and return type as String which will return our view name (welcome) and model data (Message to be passed to View). We also add one more mapping @RequestMapping to specify which url should be used to invoke this method. This can be done at controller level as well.
package in.techyari.helloworld.controller;

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

@Controller
public class HomeController {
    @RequestMapping("/")
    public String welcome(Model model){
        String message = "Welcome to Spring MVC";
        model.addAttribute("welcomeMessage", message);
        return "welcome";
    }
}

Creating JSP File to render the message

Lastly we will create a JSP file name welcome.jsp inside WEB-INF/views/jsp to render our message. Note that this file uses JSTL to print the message.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Hello World Tutorial</title>
</head>
<body>
    <h3 style="text-align: center; margin-top: 200px;">${welcomeMessage}</h3>
</body>
</html>
That's all we are done with our simple Spring MVC app. Now run the project by right clicking into project name and Run -> Run on server. You should see the home page printing our message from controller. Hope you enjoyed this post. Share your thoughts and comments below :)

About Vipin Dubey

A web developer, blogger, amateur designer and an open source enthusiast.

No comments:

Post a Comment


Contact Form

Name

Email *

Message *

Labels

Follow TechYari on

Translate

About TechYari

Tech Yari is a Technical Blog featuring articles on Web Development, Web Design, Search Engine Optimization, Social Media Marketting and Programming.