Sunday, November 23, 2014

Hello Spring MVC

In this blog I will create a very simple Spring MVC demo to get started with Spring MVC. A prior exposure to any MVC framework will be handy to understand Sprig MVC. I will be using Tomcat 7.0 as web server and Spring3.2 release.

Lets create a dynamic web project in eclipse and name it Spring MVC. This is how the folder structure will look like-










At his moment its simple web project with no spring related  capabilities. First we will create a simple web application with welcome.html as the welcome file to get going and then we will add Spring MVC features to it. Below is the content of my wlecome.html page.

<!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>Welcome Page</title>
</head>
<body>
<h3>Welcome to Spring MVC</h3>
</body>
</html>

Just run the html page and you will get the output like below:-









Now lets start adding Spring MVC  realted stuff to the application. The first thing that we will do is to add spring-webmvc.jar to the classpath as we are going to use the classes/interfaces from spring-webmvc. Right click on the project->properties->java build path and then add the spring-webmvc.jar by browsing to the location where you have downloaded it.Apart from spring-webmvc.jar we also need the follwing jars in the WEB-INF/lib directory or you can also copy them directly in your Tomcat/lib folder but not on both places else you will get linkage error at run time.Below is the list of jars-






Now that we have got all the required jars, lets configure the front controller component. Every MVC framework has a front controller which is responsible to to handle all the incoming request and route it to the controller that will be responsible for handling the request. In sturts its the ActionServlet, but in spring its DispatcherServlet. Lets configure the front controller of the Spring MVC in the web.xml file by making the following entry-

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/springmvc-config.xml</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

The contextConfigLocation init  parameter tells spring about the configuration file where we define out applicaiton related controller and view components.The default name for this file is the name of ur DispatcherServlet(springmvc)-servlet.xml file. If we use the default file name then there is no need to define contextConfigLocation parameter. Here i am not using the default. If i had used the default the name of file would have been springmvc-servlet.xml. The url-pattern tells that any request ending with .htm will be routed to the DispatcherServlet to route it further to the controller. The url-pattern can be any url pattern that you wish, its a spring convention to user *.htm. You can choose whatever you like.

Next we need to define our controller component that will handle our request. In our sample application we will direclty invoke /hello.htm from the broswer. So we need one Controller that will handle this request. Lets call this Controller HelloController-

package com.sanjiv.spring.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloController implements Controller {
   
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        return new ModelAndView("hello","message",message);
    }

}

Now that we have created the controller lets configure this controller in springmvc-config.xml file-

  <bean name="/hello.htm" class="com.sanjiv.spring.mvc.controller.HelloController">
      <property name="message">
          <value>Welcome to Spring MVC</value>
      </property> 
  </bean>

The name of the bean is the url that we will hit from the browser.HelloController has one simple message property which i am populating here using setter injection with value "Welcome to Spring MVC". Our HelloController implements Controller interface and overrides its handleRequet() method which returns a ModelAndCView() object. I will not explain all the details of all components here as our target here is to just get started with spring MVC. Based upon this ModelAndView object the DispatcherServelt decides whihc view to call and for this it contacts ViewResolver. So we need to configure view resolver as well which will route the request to the jsp which will render the final output to the user. hello is the logical name of our jsp page which is used by the View Resolver to generate the physical view which will be /jsp/hello.jsp page. lets configure view resolver in springmvc-config.xml file-

 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>
All our jsp files are inside the jsp folder in webcontent directory.

Now lets create hello.jsp inside the jsp folder that will render the final output with the message string parameter that we are passing from the controller-

<%@page import="java.util.Date"%>
<html>
  <head><title>Hello :: Spring Application</title></head>
  <body>
<h1><%= request.getAttribute("message") %></h1>
<%= new java.util.Date() %>
  </body>
</html>

So we are all set to go now. Lets run the application by hitting the url-http://localhost:8080/SpringMVC/hello.htm. and you can see the below output-


Thats it we have created our first Hello Spring MVC application.

Below is the flow of control:-

1 DispatcherServlet receives a request whose URL pattern is “/hello.htm”.
2 DispatcherServlet consults HandlerMapping to find a controller
whose bean name is “/hello.htm”, finding the HelloController bean
3 DispatcherServlet dispatches the request to HelloController for processing.
4 HelloController returns a ModelAndView object with a logical view name
of hello.
5 DispatcherServlet consults its view resolver (configured as InternalResourceViewResolver)
to find a view whose logical name is hello. Internal-
ResourceViewResolver returns the path to /jsp/hello.jsp.
6 DispatcherServlet forwards the request to the JSP at /jsp/
home.jsp to render the hello page to the user.

This was the very basic demo to get going. In my coming blogs I will explain each and every componnent of spring MVC in details.

Thanks for reading.










3 comments:

  1. Java applications — a loose term that runs the
    gamut from constrained applets to n-tier server-side
    enterprise applications — typically consist of objects
    that collaborate to form the application proper. Thus
    the objects in an application have dependencies on
    each other.
    Although the Java platform provides a wealth of
    application development functionality, it lacks the
    means to organize the basic building blocks into a
    coherent whole, leaving that task to architects and
    developers. True, you can use design patterns such
    as Factory, Abstract Factory, Builder, Decorator, and
    Service Locator to compose the various classes and
    object instances that make up an application.
    However, these patterns are simply that: best practices given a name, with a description of
    what the pattern does, where to apply it, the problems it addresses, and so forth. Patterns
    are formalized best practices that you must implement yourself in your application.
    The Spring Framework Inversion of Control (IoC) component addresses this concern by
    providing a formalized means of composing disparate components into a fully working
    application ready for use. The Spring Framework codifies formalized design patterns as
    first-class objects that you can integrate into your own application(s). Numerous organizations
    and institutions use the Spring Framework in this manner to engineer robust, maintainable
    applications.

    ReplyDelete
  2. Q) How are create IOC (Inversion of Control) program in spring?

    package com.spring;

    public class Student {

    private String name;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public void displayInfo(){
    System.out.println("Hello: "+name);
    }

    }
    --------









    --------------
    package com.spring;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class Test {
    public static void main(String[] args) {
    // Resource resource=new ClassPathResource("applicationContext.xml");
    // BeanFactory factory=new XmlBeanFactory(resource);
    ApplicationContext context = new ClassPathXmlApplicationContext(
    "applicationContext.xml");

    Student student = (Student) context.getBean("studentbean");

    student.displayInfo();
    }
    }

    ReplyDelete
  3. I assume that you know the spring core before going into other layers of spring including spring MVC

    ReplyDelete