Wednesday, April 2, 2014

Spring Mvc Hello World Example With Annotation

We are going to create a spring mvc base example with annotations in eclipce.
In this example we will print a message "Hello World" on screen and will handle some common errors like 404 (URL not found) or 500 (internal server error).




Step 1 : Create a new project
    Click on File -> New and select Dynamic Web project.


    Add project name "HelloWorldExample" and click on finish.
  

Step 2 : Add jar files to lib folder

    commons-logging-1.1.1.jar
    jstl-1.2.jar
    spring-asm-3.0.3.RELEASE.jar
    spring-beans-3.0.3.RELEASE.jar
    spring-context-3.0.3.RELEASE.jar
    spring-context-support-3.0.3.RELEASE.jar
    spring-core-3.0.3.RELEASE.jar
    spring-expression-3.0.3.RELEASE.jar
    spring-web-3.0.3.RELEASE.jar
    spring-webmvc-3.0.3.RELEASE.jar

    To download whole project including jar files click here
  
Steps 3 : Web.xml
    Spring's web MVC framework is a request-driven framework, designed around a central
    servlet that dispatches requests to controllers and offers other functionality facilitating
    the development of web applications.Spring's DispatcherServlet does that.

    The DispatcherServlet is an actual Servlet and declared in the web.xml of your web application.
    Requests that you want the DispatcherServlet to handle will have to be mapped using a
    URL mapping in the same web.xml file.
  
    In our example we mapped the DispatcherServlet with URL "/". All request with URl "/"
    will be  handled by DispatcherServlet.

web.xml

<?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" 
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
 id="WebApp_ID" version="2.5">

  <display-name>SpringHelloWorldExample</display-name>

  <servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/app-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <error-page>
    <error-code>404</error-code>
    <location>/pageNotFound.jsp</location>
  </error-page>

  <error-page>
    <error-code>500</error-code>
    <location>/error.jsp</location>
  </error-page>

  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>

</web-app>


  We also mapped jsp error pages with some specific errors. Whenever a error occured in
  our example, specific error page will show on screen.

error.jsp

<html>
    <body>
        <h1 style="color: red;">Some Error On server</h1>
    </body>
</html>

pageNotFound.jsp

<html>
    <body>
 <h1 style="color: red;">Page Not Found</h1>
    </body>
</html>
  
    We also defined a welcome page "home.jsp" in web.xml. This page show on startup of
    our example.
  
home.jsp

<a href="/HelloWorldExample/helloWorld">say hello</a>

<a href="/HelloWorldExample/serverError">serverError 500</a>

<a href="/HelloWorldExample/wrongUrl">wrongUrl error 404</a>

  
Step 4 : app-config.xml (Configuration file)
    The framework will look for a configuration file named [servlet-name]-servlet.xml on
    initialization of a DispatcherServlet.
    We defined a configuration file name and position as a init-param with
    name “contextConfigLocation“ in web.xml
    The configuration file will contain information about controller class, view resolvers etc.

    To enable autodetection of such annotated controllers, you have to add component
    scanning to your configuration.
    This is easily achieved by using the spring-context schema as shown in the following
    XML snippet:

    <mvc:annotation-driven /> : To enable autodetection of such annotated controllers
    <context:component-scan base-package="com.example" /> : Add component scanning path
      
    We also registered an viewResolver of
    type  “org.springframework.web.servlet.view.InternalResourceViewResolver“.
    Spring will automatically configure it as a view resolver component and when any
    spring controller will return a view name
  
   it will check for the view definition with the
   class  “org.springframework.web.servlet.view.InternalResourceViewResolver“.
   InternalResourceViewResolver class takes two special parameters prefix and suffix. The value of
   these parameters are applied to the view name to get actual location of the view.

    For example -
    spring controller returns the view name as "helloWorld" and prefix is defined as
     “/WEB-INF/jsp/” and suffix is defined as “.jsp” the InternalResourceViewResolver will
     return the jsp “/WEB-INF/jsp/helloWorld.jsp”  to the browser.

app-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 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
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!--Scans the classpath of this application for @Components to deploy as beans-->
 <context:component-scan base-package="com.example" />

 <!-- Configures the @Controller programming model -->
 <mvc:annotation-driven />

 <!-- Resolves view names to protected .jsp resources within the /WEB-INF/jsp directory -->
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/"/>
  <property name="suffix" value=".jsp"/>
 </bean>

</beans>

  
Step 5 : HelloWorld.java (Spring controller)
    The @Controller annotation indicates that a particular class serves the role of a controller.
    There are several important things to point out here. First, the HelloWorld class is annotated
    with @Controller so that it will be autoregistered as a bean by <mvc:annotation-driven />. 
    methods are also annotated with @RequestMapping, @RequestMapping indicates
    that HTTP GET respond to requests for “/helloWorld” or "/serverError".
  
    In our controller helloWorld() method return a ModelAndView object.    The ModelAndView class is essentially a glorified Map that can
    make adding objects that are to be displayed in (or on) a View adhere to a common naming convention.
    ModelAndView stores values that we want to carry to the view. we added an value of key "message" and value “Hello World”.
  
    We create a  add a ModelAndView object with view name "helloWorld". Spring viewResolver will add prefix and suffix parameter with view name.
    In final view name "helloWorld" will change to “/WEB-INF/jsp/helloWorld.jsp” and we will see "helloWorld.jsp" on screen.

HelloWorld.java

package com.example;

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
public class HelloWorld {

 @RequestMapping(value = "/helloWorld", method = RequestMethod.GET)
 public ModelAndView helloWorld() {
  ModelAndView modelAndView = new ModelAndView("helloWorld");
  modelAndView.addObject("message", "Hello World");
  return modelAndView;
 }

 @RequestMapping(value = "/serverError", method = RequestMethod.GET)
 public int serverError() {
  Integer test = null;
  return test + 1;
 }
}


Step 6 : helloWorld.jsp (Spring View)
    In "helloWorld.jsp" we just will show the message return by controller.

helloWorld.jsp
<html>
    <head>
        <title>Hello World Example</title>
    </head>
    <body>
        <h1>${message}</h1>
    </body>
</html>

  
    Our example is complete now. Final structure of our example will look like this :

  
Step 7 : Run Example in Tomcate
    Export War file (HelloWorldExample.war) from eclipce and copy it to tomcat webapp folder, start tomcat.
  
    Now hit the url : localhost:8080/HelloWorldExample You will see welcome page (home.jsp) of our example.


    Click on first link "say hello" ("/HelloWorldExample/helloWorld"). You will see message "Hello World" on screen.


    Click on second link "serverError 500" ("/HelloWorldExample/serverError"). This will send a request on controller and a "Null Pointer Exception"
    Will ocuur on server and you will redirect to error page.


    Click on third and final link "wrongUrl error 404" ("/HelloWorldExample/wrongUrl"). This will send a request on controller, But will not found
    any mapping with this url and you will be redirect to "page not found" page.




To download whole project including jar files click here


Related posts :-
Maven introduction
Spring mvc example with maven using eclipse

No comments:

Post a Comment