Spring MVC : Basics and Setup

The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. he Model-view-controller design pattern helps in seperating the business logic, presentation logic and navigation logic. Models are responsible for encapsulating the application data. The Views render response to the user with the help of the model object . Controllers are responsible for receiving the request from the user and calling the back-end services.

In our example we will have registration web app. We will be buiding it step by step in this and following posts.

Make a ‘Dynamic web Project’ in Eclipse. Right click the project -> Configure – > Convert to Maven project

The project is now maven web project. Add dependencies in your 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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MyNotes_Spring_MVC</groupId>
<artifactId>MyNotes_Spring_MVC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<properties>
<spring.version>3.2.5.RELEASE</spring.version>
</properties>

<dependencies>

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

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

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

</dependencies>
</project>

Maven will automatically download all the required and related jars. Our final project will have final struture like below:

Springmvc_projectStructure1

We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in web.xml file:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MyNotes_Spring_MVC</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

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

</web-app>

We have given the name ‘dispatcher’ to the servlet with load-on-startup as one i.e load on startup on first priority. Upon initialization of dispatcher, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application’s WebContent/WEB-INF directory. In this case our file will be dispatcher-servlet.xml. Notice the url pattern  ‘/’ , i.e it will mapp all kind of request to spring. (for specific type use *.html etc.).

A front controller is defined as a controller which handles all requests for a Web Application. DispatcherServlet (actually a servlet) is the front controller in Spring MVC that intercepts every request and then dispatches/forwards requests to an appropriate controller.

As said above, spring will search for dispatcher-servlet.xml. You load other configuration  by adding the servlet listener ContextLoaderListener in your web.xml file as follows:


<!-- servlet and mapping above -->

<!-- Optional -->

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application.xml</param-value>
</context-param>

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

There is difference between these 2 – DispatcherServlet and ContextLoaderListener

In Spring MVC, there are two context. One is the application context or global context which is booted up by ContextLoaderListener. It takes all the configuration file mentioned in contextConfigLocation parameter.  Now if you are are using Spring MVC (web layer) also than Dispatcher servlet is required, which boots up another container which is also known as web application container. This container takes the global container as a parent. If you are using Spring in the backend only, then the global context is good enough. However if you are using Spring MVC also for front end than you need Dispatcher Servlet also. ContextLoaderListener is generally used to keep your services, repository/dao middle tier beans seperate along with third party configuration like to add Struts,JSF weblayer etc.

For now we are not adding above to our code in web.xml.

Our dispatcher-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="mynotes.springmvc.*" />
<context:annotation-config />

<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames"
value="classpath:mynotes/springmvc/properties/ApplicationResource" />
</bean>

</beans>

Following are the important points about dispatcher-servlet.xml file:

  • The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
  • The <context:component-scan…> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc.
  • The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at/WEB-INF/jsp/ registration_intro.jsp
  • The ReloadableResourceBundleMessageSource.is used to load properties file for labels, messages etc.

DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The@Controller annotation indicates that a particular class serves the role of a controller. The@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

RegistrationController.java:


package mynotes.springmvc.controller;

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

@Controller
public class RegistrationController {

@RequestMapping(value = "/registrationIntro", method = RequestMethod.GET)
public String registrationIntro() {

System.out.println("Inside registrationIntro");

return "registration_intro";
}

}

The @Controller annotation indicates that a particular class serves the role of a controller. It can only be used at class level.

The @RequestMapping annotation to map URLs onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping for a specific HTTP method request method (“GET”/”POST”) or specific HTTP request parameters. Here we are using this onto a method only. The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle HTTP GET request.

ApplicationResource.properties


registration.intro1=Welcome to Spring MVC Registration Demo
registration.intro2=Click 'Register' button to start

registration_intro.jsp:


<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Intro</title>
</head>
<body>
<form>
<table>
<tr><td colspan="2"><spring:message code="registration.intro1"/></td></tr>
<tr><td><spring:message code="registration.intro2"/></td><td>Register</td></tr>
</table>
</form>
</body>
</html>

Notice above that we have used 2 spring framework tags – form and spring.

Adding the project to tomcat and running – http://localhost:8080/MyNotes_Spring_MVC/registrationIntro

Springmvc_registrationResultView1

If you are getting following error:

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

You need to add the “Maven Dependency” in the Deployement Assembly

  • right click on your project and choose properties.
  • click on Deployement Assembly.
  • click add
  • click on “Java Build Path Entries”
  • select Maven Dependencies”
  • click Finish.

The requesting processing workflow in Spring Web MVC (high level)

springmvc

 

 

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: