Thursday, 8 November 2018

Spring Web MVC: Hello World Application

Below step-by-step procedure explains how to run simple ‘Hello World’ application in Eclipse.

Step 1: Open Eclipse and create new ‘maven-archetype-webapp’ project.
File -> New  -> Other.

Search for maven and Select ‘Maven Project’.

Select ‘Maven Project’ and click on Next button.

Use the defaults and click on Next button.


Search for web, select ‘maven-archetype-webapp’ and click on Next button.


Give Group Id, Artifact id as ‘springdemo’ and version as 1 and click on Finish button.

Project is created like below.
Step 2: There are two problems to be addressed in step 1.
a.   We need to set the run time environment of the project, to get rid off that red cross mark.
b.   There is no src/main/java folder.

Setting the run time environment
Right click on the project ‘springdemo’. Go to Properties.

Go to Project Facets, select Runtimes and select the application server that you want to deploy the web application.

For example, I configured ‘Apache Tomcat v9.0’. Click on ‘Apply and Close’ button.

Create src/main/java folder
Create a java directory under main (i.e. src/main/java) and right-click on your project and select Maven > Update Project Configuration.
After performing above step, project structure is changed like below.

Step 3: Add spring web dependencies in pom.xml file.
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>springdemo</groupId>
 <artifactId>springdemo</artifactId>
 <packaging>war</packaging>
 <version>1</version>
 <name>springdemo Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.0.6.RELEASE</version>
  </dependency>

 </dependencies>
 <build>
  <finalName>springdemo</finalName>
 </build>
</project>

Step 4: Update web.xml file like below.

web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

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

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

</web-app>

Step 5: Create ‘HelloWorld-servlet.xml’ like below. 

HelloWorld-servlet.xml
<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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:component-scan
  base-package="com.sample.myApp" />

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

</beans>

Step 6: Create new package 'com.sample.myApp.controllers' and add the class 'HelloWorldController' to it.


HelloWorldController.java
package com.sample.myApp.controllers;

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

@Controller
@RequestMapping("/hello")
public class HelloWorldController {

 @RequestMapping(method = RequestMethod.GET)
 public String printHello(ModelMap model) {
  model.addAttribute("message", "Welcome to Spring MVC framework");

  return "hello";
 }

}

Step 7: Create a folder 'jsp' under WEB-INF, and define hello.jsp file like below.

hello.jsp
<%@ 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>Hello World Spring Web MVC</title>
</head>
<body>
 <h2>${message}</h2>
</body>
</html>


Project structure looks like below.

Step 8: Run the application on Server.


Right click on the project ‘spring demo’ -> Run As -> Run on Server


Step 9: Hit the below url.


You can able to see the response like below.

Explanation about what we did?
a. web.xml file
I added below lines to web.xml file.

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

         <servlet-mapping>
                  <servlet-name>HelloWorld</servlet-name>
                  <url-pattern>/</url-pattern>
         </servlet-mapping>
        
I submitted all the requests to 'org.springframework.web.servlet.DispatcherServlet' class. DispatcherServlet receives a web request and hand it over to the registered handlers for processing.

b. HelloWorld-servlet.xml
Since in web.xml file, I specified the <servlet-name> as 'HelloWorld', I should create 'HelloWorld-servlet.xml' and specify the configuration that is relevant for spring.

For example,

<context:component-scan base-package="com.sample.myApp" />
Above statements tells to spring 'scan the package com.sample.myApp and all its sub packages' to know about the components like Repository, Service, Controller. When you annotate any class with components like @Component, @Repository, @Service then those classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.


         <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                  <property name="prefix" value="/WEB-INF/jsp/" />
                  <property name="suffix" value=".jsp" />
         </bean>
It matches the view names to the jsp file. For example, if the controller return 'hello', then it matches to 'hello.jsp' file. In the above case, I mentioned, all my jso files are located under /WEB-INF/jsp folder.

HelloWorldController class
@Controller
@RequestMapping("/hello")
public class HelloWorldController {
         ....
         ....
         ....
}

@Controller : annotation specifies this class is a web controller.

@RequestMapping("/hello") : Maps the request url to the controllers. For example, the url '/hello' is mapped to HelloWorldController.

@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
         model.addAttribute("message", "Welcome to Spring MVC framework");

         return "hello";
}

ModelMap is a 'java.util.Map' implementation, it is used to build model data. This model data is used by views.

For example, I added an attribute 'message' to the model. 'hello.jsp' file access this model object using $ notation like '${message}'.


I hope you enjoy the basics of Spring Web MVC Hello World Application. 

Previous                                                 Next                                                 Home

No comments:

Post a Comment