Search This Blog

Thursday, December 9, 2010

Struts 2, Spring 3, Hibernate - The Big Picture

Today, we will get a java web application running using these three master frameworks -> Struts, Spring and Hibernate. Each one has its own speciality, that overcome some of the drawbacks of the underlying platform. Spring framework allows you to create and pass objects( java beans) at runtime using constructors or setters rather than doing it implicitly in the host class, the concept being known as Dependency Injection or Inversion of Control (IOC). This makes the classes independent, which indeed helps in testing. Spring also has other components but we wont use it here. Struts provides a Model View Controller (MVC) framework. It helps in separating your logic from the view. The controllers handle the requests, the views generate output and model represents an entity. Hibernate lets us save Persistence Java Objects/POJOs into the database and also retrieve them. All these components have their own configuration xml files. I will break up this topic into 4 parts, in 3 of them we will see how we can get these components running independently and at last using these into one application. ======================================== AN APPLICATION IN SPRING The IDE i prefer for java is IntelliJ Idea, so the initial project settings may differ based on the IDE you use. Download Spring 3 Framework here The structure of the application goes like this : Extract the Spring archive to a folder, import the jar files in dist folder to the lib folder of your project and make sure they are added to the build path. Actually all files are not required, and in Spring you get the freedom to choose only the components you need. The jar file that i have included are : commons-logging, spring-web, spring-webmvc, spring-beans, spring-context, spring-core, spring-asm, spring-expression. commons-logging jar is needed and can be found in projects/spring-build/lib/ivy of the Spring framework extracted folder. Don't forget to include Java EE library. The src folder will contain my source, within which i have defined a package in.codeconnect, my java files will go in here. The web directory contains a sub directory 'pages' where i will keep my views/jsp files. WEB-INF will contain 2 Spring configuration files : applicationContext.xml and dispatcher-servlet.xml and one server config file : web.xml. I have created 2 classes in my package : This is a simple class with getter and setter,that will contain my greeting message :

package in.codeconnect;

public class MessageClass {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
This is the Controller :

package in.codeconnect;

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

public class HelloWorldController implements Controller {
    private MessageClass messageObject;

    public MessageClass getMessageObject() {
        return messageObject;
    }

    public void setMessageObject(MessageClass messageObject) {
        this.messageObject = messageObject;
    }

    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
           ModelAndView modelAndView = new ModelAndView("pages/say_hello.jsp");
           modelAndView.addObject("message",messageObject.getMessage());
           return modelAndView;
    }
}
Note this class has a MessageClass object defined along with its getter and setter. handleRequest() is the function called when request comes to this contoller. Here we create a new view whose jsp is located in /pages with name say_hello.jsp. Then we add a variable that will contain our greeting message using addObject(), whose value will be equal to messageObject's message property. Lets go through the configuration files. web.xml is the main file and this is how it will look :

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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" version="2.5"> 
<context-param> <param-name>contextConfigLocation</param-name> 
<param-value>/WEB-INF/applicationContext.xml
</param-value> 
</context-param> <listener> 
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class> 
</listener> <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>*.html</url-pattern> </servlet-mapping> </web-app>
It states that any request coming with .html suffix should be directed to Springs dispatcher, and this is where the action starts. applicationContext.xml can contain all beans definitions except the controller bean definition. dispatcher-servlet.xml should basically contain controller bean definition, but anything can go here. Blank applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 
</beans>
dispatcher-servlet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 
<bean name="messageObject" class="in.codeconnect.MessageClass"> 
<property name="message" value="Hello World" /> </bean> 
<bean name="/sayHello.html" class="in.codeconnect.HelloWorldController"> 
<property name="messageObject" ref="messageObject" /> 
</bean> </beans>
We can see above , we define a bean messageObject of type MessageClass and set its message using "value='Hello World'" (Dependency Injection).Here the setmessage() method of this object will be called to set message value. Next we define another bean, our controller that will be looked upon when request comes to /sayHello.html . We then specify its messageObject to be equal to the previous bean defined above using 'ref' . What is in my say_hello.jsp :

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html> <head><title>Simple jsp page</title></head> 
<body>${message}</body> </html>
So When the application starts, the beans are created and then injected in order of dependency. You should see Hello World message when page loads in the browser. ${message} is one that was added using modelAndView.addObject().

2 comments:

  1. why there is need of dispatcher-servlet.xml and why
    we keep empty applicationcontext.xml

    ReplyDelete
  2. Nice info regarding strut,spring and hibernate My sincere thanks for sharing this post Please Continue to share this post
    Java Training in Chennai

    ReplyDelete