Monday, 12 November 2018

Spring: Working with WebApplicationInitializer

WebApplicationInitializer is used to configure ServletContext programatically. SpringServletContainerInitializer detect the classes that implements WebApplicationInitializer interface on application start up time.

Traditional XML based approach
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>

  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/myWebAppConfigurations.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

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

</web-app>

We can rewrite above web.xml file programmatically like below.

ApplicationInitializer.java
package com.sample.myApp.initializers;

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

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class ApplicationInitializer implements WebApplicationInitializer {

 public void onStartup(ServletContext servletContext) throws ServletException {
  XmlWebApplicationContext appContext = new XmlWebApplicationContext();
  appContext.setConfigLocation("/WEB-INF/myWebAppConfigurations.xml");

  ServletRegistration.Dynamic dispatcher = servletContext.addServlet("HelloWorld",
    new DispatcherServlet(appContext));
  dispatcher.setLoadOnStartup(1);
  dispatcher.addMapping("/");
 }

}

Find the below working application.

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

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

@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";
 }

}


Create ‘hello.jsp’ file under WEB-INF/jsp folder.

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>


Create ‘myWebAppConfigurations.xml’ file under WEB-INF.

myWebAppConfigurations.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>


index.jsp
<html>
<body>
 <h2>Hello World!</h2>
</body>
</html>

Project structure looks like below.

Run above application and hit the url http://localhost:8080/springdemo/hello.



Previous                                                 Next                                                 Home

Saturday, 10 November 2018

Spring Web MVC: ModelAndView tutorial

ModelAndView class used to hold both the data (Model) and view in MVC framework.

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

         @RequestMapping(method = RequestMethod.GET)
         public ModelAndView printHello() {
                  ModelAndView modelAndView = new ModelAndView("hello");
                 
                  modelAndView.addObject("message", "Welcome to Spring MVC framework");
                  return modelAndView;
         }

}

For example, as you see above snippet, ‘printHello’ method return a ModelAndView instance and it holds the view ‘hello’ and a message "Welcome to Spring MVC framework". The value returned by ‘printHello’ method is resolved by DispatcherServlet.

ModelAndView class provides below constructors


public ModelAndView()
public ModelAndView(String viewName)
public ModelAndView(View view)
public ModelAndView(String viewName, @Nullable Map<String, ?> model)
public ModelAndView(View view, @Nullable Map<String, ?> model)
public ModelAndView(String viewName, HttpStatus status)
public ModelAndView(@Nullable String viewName, @Nullable Map<String, ?> model, @Nullable HttpStatus status)
public ModelAndView(String viewName, String modelName, Object modelObject)
public ModelAndView(View view, String modelName, Object modelObject)

Find the below working application.

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.web.servlet.ModelAndView;

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

 @RequestMapping(method = RequestMethod.GET)
 public ModelAndView printHello() {
  ModelAndView modelAndView = new ModelAndView("hello");
  
  modelAndView.addObject("message", "Welcome to Spring MVC framework");
  return modelAndView;
 }

}


index.jsp
<html>
<body>
 <h2>Hello World!</h2>
</body>
</html>


Create web.xml, HelloWorld-servlet.xml files under WEB-INF directory.

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>


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>

Create hello.jsp under WEB-INF/jsp folder.

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.


Run the application springdemo and hit the url  ‘http://localhost:8080/springdemo/hello’, you can able to see the message ‘Welcome to Spring MVC framework’.





Previous                                                 Next                                                 Home

Friday, 9 November 2018

Spring web mvc: Specify context configuration location to dispatcher servlet

This is continuation to my previous post. As you see web.xml file from my previous post, I am redirecting all my requests to org.springframework.web.servlet.DispatcherServlet.

<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>

As you see above configuration, I do not specify any config file location there. If you do not specify any config file location, then spring will check for the file {servlet-name}-servlet.xml in WEB-INF directory.

Suppose if you want to specify the config file location manually, (or) if you have configurations split across multiple files, then you need to specify them using the init parameter contextConfigLocation.

<servlet>
         <servlet-name>HelloWorld</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

         <init-param>
                  <param-name>contextConfigLocation</param-name>
                  <param-value>/WEB-INF/myWebAppConfigurations.xml</param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
</servlet>

At the time of application startup, spring reads the context file specified by the <init-param> contextConfigLocation.

Find the below working example.

HelloWorldController.java

package com.sample.myApp.controllers;

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

@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";
 }

}

Create ‘hello.jsp’ file under WEB-INF/jsp folder.

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>

Define myWebAppConfigurations.xml file under WEB-INF directory.


myWebAppConfigurations.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>

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>

  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/myWebAppConfigurations.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

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

</web-app>

index.jsp

<html>
<body>
 <h2>Hello World!</h2>
</body>
</html>

Complete project structure looks like below.


Run the application on server and hit the url http://localhost:8080/springdemo/hello.

You can able to see the message 'Welcome to Spring MVC framework' in the browser.

Can I specify multiple configuration files?
Yes, you can specify by comma separating them.

Previous                                                 Next                                                 Home

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