Tuesday, December 7, 2010

Spring MVC Annotation based Helloworld Example with LOG4J logging support

Today we will look at how to write Spring MVC hello world application using Spring Annotations. This tutorial will be completely different from other available tutorials in the web because, I have tried to show how to externalize property values from the BeanFactory definition and how to place them in a separate standard files called properties files. In addition, I will be using apache log4j framework to make the required logs for this application. Therefore you will be having the chance to investigate more on these technologies throughout this article. The overall directory and the file structure of the project is as follows.

I have used the following technologies and frameworks to make this simple example.

Apache Maven as the building tool
Apache Log4J as the logging framework
Spring MVC framework
Apache Tomcat for running this Application
Intelli J IDEA as the Development IDE

you can see the content of the each file as below.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


            <id>JBoss repository</id>



        <!-- spring dependency starts-->
        <!-- Spring Framework -->

        <!-- Spring MVC Framework -->
        <!-- spring dependency ends-->

        <!-- JSTL Dependencies start -->

        <!-- JSTL Dependencies ends -->

        <!--Logging Dependencies Starts-->

        <!--Logging Dependencies Ends-->



            <!-- Maven compiler plugin that says to use JDK 1.6 version for compiling the project -->



            <!-- Maven WAR  plugin -->



        <!-- Final project build name -->



this is the main(core) controller of this simple web application. You can see that we have used annotations for request mappings and other required configurations. As you can see the developer.name and developer.email properties have been defined in a external property file and they are accessed in the controller using the special annotations dedicated for that. The property values will be injected to the relevant variables using the @Value annotation.

package org.convey.example.Controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

Author: Chathuranga Tennakoon
Email: chathuranga.t@gmail.com


public class HelloWorldController {

    private static final Logger logger = Logger.getLogger(HelloWorldController.class);

    private String developerName;

    private String developerEmail;

    public ModelAndView helloWorldMethod(){

        logger.debug(" invoking the helloWorldMethod method ");

        ModelAndView model=new ModelAndView("SayHelloView");


        return model;




this file is located inside the resources/properties/ directory. The content of this file is as follows.

#Sample Screen Message values
developer.name=chathuranga tennakoon



you will see that the Spring MVC Dispatcher servlet is mapped and configured inside the web.xml file.
In additon, the log4j configuration is also done inside the web.xml file.(furthermore you can define and configure Filters and Listeners inside the web.xml file if required.)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">

<!-- LOG4J Configuration -->

<!-- Spring MVC Dispatcher Servlet Mapping start -->

<!-- Spring MVC Dispatcher Servlet Mapping ends -->


this represents the Dispatcher servlet of your web application. As you can see in the web.xml , you have named the dispater servlet as hello. Therefore your dispatcher servlet will be named as hello-servlet.xml. The beans that are declared in this servlet will be initiated when the Dispatcher servlet loading time. All the declared beans will be created in the Spring bean container.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<import resource="applicationContext.xml"/>

<bean id="handlerMappingC" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">


<bean id="HelloController" class="org.convey.example.Controller.HelloWorldController"/>



<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<h1>Spring MVC Hello World Annotation Example</h1>

<!-- JSTL Tag libraries are required for the EL(Expression Language) -->
<h5>developed by : ${developer_name}</h5>
<h5>Email : ${developer_email}</h5>



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="org.convey.example.Controller" />
<!-- actual view is resolved with the prefix + resolverName + suffix . if the resolverName is sayHelloView, then the actual resolved view will be /WEB-INF/view/sayHelloView.jsp ( /WEB-INF/view/ + sayHelloView + .jsp ) -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >

<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />

<!-- the below bean is configured to define external property file for defining property values for the application -->
<bean id="placeholderConfig"
<property name="locations">
<!-- messages have been defined inside the resources/properties/messages.properties file -->



<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%x] %c{1} %m%n" />

<appender name="FileAppender" class="org.apache.log4j.FileAppender">
<!-- the log file will be available inside the logs directory of the tomcat installation. the name of the log file is sample.log -->
<param name="File" value="../logs/sample.log"/>
<!-- the log will contains the log messages started from the INFO level..(info or less) -->
<param name="Threshold" value="INFO"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%x] %c{1} %m%n" />

<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />


How to run the project?

After placing the all required files in the relevant locations, you can use maven building tool to build your application. The following command can be used in your terminal to build the web application.

mvn clean install

once the project is build, you will see the war file (SpringMVC.war) inside the directory called target in your project source location. You can deploy the SpringMVC.war file in the tomcat server and see the output. It will display as below.

Browse the following URL to see the output.


Please remember to check the logs directory of your tomcat server installation and see whether there is a file called sample.log. This file should contains the log records which were generated during the execution of this web application. In additon, check whether the console appenders. In order to check the console appenders, you can use the following command in your terminal.(i assume that you are using a linux operating system.)

tail -f logs/catalina.out

Chathuranga Tennakoon

Monday, December 6, 2010

Maven 2 Repository delcaration in pom.xml

    the following repository declaration can be placed in your pom.xml file for downloading required dependencies when your application is built.
          <name>Java.net Repository for Maven</name>


then it will search the given repository for downloading the the required dependencies when building your project.

hope this will help for you!

Chathuranga Tennakoon

Servlet Life Cycle

As we know the conventional J2EE application consists of set of Servlet and JSP files. therefore it is good to get a proper understanding of the servlet and jsp including their role and lifecycle. today i am going to discuss the servlet life cycle and hope to discuss the JSP in the future post. therefore we will briefly look at the Lifecycle and the role of the servlet in this post.

The Responsibility of the Servlet

the major responsibility of the servlet is to take the client request and send back the response.that means the servlet will be responsible for implementing and the processing business logics. In traditional MVC based J2EE web applications, the servlet act as the Controller.

M (Model) :- contains of POJO classes/core java classes to represent real word entities.

V (View) :- contains a set of JSP pages to implement presentation logic for the user.

C (Controller) :- contains the servlets to implement and process business logics.

The lifecycle of the Servlet

the servlet lives in the servlet container. that means the life cycle of the servlet is handled by the servlet container.servlet container provide necessary services for the servlet from born to dead.Apache tomcat is one of the well known servlet/web container.

i will explain the life cycle of the servlet using the following example.

suppose user clicks the following URL in the web application.


1.) this request will initially come to the web container. then the web container will identify that the request is to invoke a servlet. Then the web container will create two seperate objects known as HttpServletRequest and HttpServletResponse Objects for that request (in this case the web container doesn't know the what the actual servlet is).

2.) after creating the HttpServletRequest and HtppServletResponse objects, the web container will figure out the actual servlet based on the request URL.then it will check whether the Servlet is initialized. if it is not initialized, the container will initialize the servlet first.(the servlet initialization process will bemethod parameters) discussed later)Assume that the servlet is initialized at the moment.the web container will invoke the service() method of the servlet by providing(as the HttpServletRequest and HttpServletResponse Objects created. finally the web container will create and allocate a seperate thread to serve for that particular request.

3.) the service() method will figure out which servlet method to invoke based on the HTTP request methods.(GET or POST). if it is HTTP GET request, then it is required to invoke doGet() method. if it is HTTP POST, then doPost() method should be implemented.The service method will invoke either doGet() or doPost() methods providing the HttpServletRequest and httpServletResponse objects gained.

The servlet initialization process

the servlet must be initialized before handing client requests (invoking service() method). the servlet initialization is done by the servlet container by invoking inti() method. the init method is called(or servlet initilaization is done) only once for the life time of the servlet.servlet intilaization process can be described as follows.

1.) web container loads and instantite( create the object of the servlet) the servlet class.

2.) the created object is still not a servlet object. it is just an object cretaed from the servlet class type.In order to become a servlet, it is required to grant the servlet priviledges for that object. it is done by invoking init() method on that object. init() method is called only once throughout the life time of the servlet.

3.) after completing the init() method, servlet is initialized. therefore it is possible to invoke service() method to handle client requests.it is recommneded the developers to not to override the init() method.but if you required you can override the init() method. in such case, make sure that  you have all the initialization logic(codes) for that servlet(eg:- database connection codes, other connection and resource handling codes)


The servlet container invoke the destroy() method on the servlet object to make it eligible for garbage collection.after completing all the works with the servlet, we do not require the servlet object longer. at that time, the servlet container invoke the destroy() method on the servlet object for releasing all the resorces(de-allocating) allocated during the initialization process. the destroy() method is also called only once like the init() method.

hope this will helpful for you!

Chathuranga Tennakoon