You are on page 1of 12

Spring Framework Basics with Sample

Codes

Author: Vidit Tyagi

Date written: 07/25/2006

Declaration:

I, hereby declare that this document is based on my/our personal experiences


of my/our project members. To the best of my/our knowledge, this document
does not contain any material that infringes the copyrights of any other
individual or organization including the customers of Infosys.

Project Details:

Project involved : AE61CATC


S/W Environment : Java, JSP, DB2
Application Type : Web Based
Project Type : Maintenance
Current Project : AE61CATC

Target readers : Developers, Module Leads

Keywords:

Spring Framework, Frameworks, Java, J2EE, MVC

Introduction:

Spring is a relatively new framework which provides a simpler alternative to


Struts for separating presentation layer and business logic.
Now the question arises why another framework?

There is a difference between these two frameworks – Struts is basically used


for handling presentation tier while Spring is mainly a framework used to wire
together Services (including Data Access Objects) that can change without
affecting code everywhere throughout the application. That means Spring
covers the entire web application from presentation to DAO layer. However, it
is possible to use Struts as the MVC web framework with Spring. The
terminology is also different – Action in Struts is replaced by Controller in
Spring, BD and BO classes used with Struts are Services in Spring while DAO
remains the same.

Terms used w.r.t. Spring:


IOC (Inversion of Control): THE HOLLYWOOD PRINCIPLE – DON’T
CALL ME, I WILL CALL YOU!!
The basic concept of the Inversion of Control pattern (also known as
dependency injection) is that you do not create your objects but describe how
they should be created. You don't directly connect your components and
services together in code but describe which services are needed by which
components in a configuration file. The IOC container) is then responsible for
connecting the components.

AOP (Aspect Oriented Programming):

Aspect-oriented programming, or AOP, is a programming technique that


groups the classes based upon their functionality, classes which can be a part
of different functionalities altogether. This means crosscutting behaviors which
cut across the typical divisions of responsibility, such as logging and
transaction management.

The flow in Spring is as follows:

JSP – CONFIG XML – CONTOLLER – SERVICE INTERFACE – SERVICE CLASS –


DAO INTERFACE – DAO CLASS. This flow is set in an xml file which is known
as Wiring.

Problem Statement:

To explain using a step by step process, the flow from the presentation layer
to the DAO layer, retrieve data from the database and display the retrieved
data on the presentation layer using Spring framework.

Solution:

Please follow the following steps:

Note: Sample code is given to this functionality; please make the changes
according to your requirement.

Assumptions:

A.) The reader is familiar with the MVC architecture.

1. Create a JSP (say indexNew.jsp) which takes Username and Password as


input.

Sample Code for the solution: (indexNew.jsp)


<html>
<title>Example :: Spring Application</title>
<head>
<center><h3>SPRING APPLICATION</h3></center>
<script language="Javascript" src="js/common.js">
</script>
</head>
<body>
<form name="sampleForm" method="post">
<table border =1 width="40%" align=center>
<tr><th bgcolor="#A5D6F7" colspan=2>Login</th></tr>
<tr><td>User Name</td><td><input type="text" name="userName"></td></tr>
<tr><td>Password</td><td><input type="password" name="password"></td></tr>
<tr><td colspan=2 align=center><input type="button" name="btSubmit"
value="Submit" onClick="Validate()"></td></tr>
</table>
</form>
</body>
</html>

2. On click of “Submit” button on this JSP, a javascript function (Validate) is


called which checks for the mandatory fields and submits the form.

Sample Code for the solution: (common.js)

function Validate()
{
var uName = document.sampleForm.userName.value;
var password = document.sampleForm.password.value;

if(uName=="" || password=="")
{
alert("Please enter both values to submit");
if(uName=="")
{
document.sampleForm.userName.focus();
return false;
}
else
{
document.sampleForm.password.focus();
return false;
}
}
else{
document.sampleForm.submit();
}
}
3. Now comes the main part – where is this JSP submitted to? There is no
action defined in the form. For this we will have to create an entry in the
web.xml file. (In terms of Struts - It is as good as creating our own
Struts-Config.xml file)

Sample Code for the solution: (web.xml)

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE web-app PUBLIC '-//Sun


Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-
app_2_3.dtd'><web-app> <servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>

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

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

</web-app>

4. The next step is creating springapp-servlet.xml file which will contain the
beans and the wiring of the application. (Remember the name given here
should match exactly with the one given in the web.xml)

Sample Code for the solution: (springapp-servlet.xml)

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "spring-beans.dtd">

<!--- Application context definition for "springapp" DispatcherServlet. -->

<beans>
<bean id="springappController" //bean for Controller
class="com.abc.strutspring.controller.SpringappController">

<property name="sessionForm"><value>true</value></property>

<property name="commandName"><value>loginbean</value></property> //loginbean


contains the getter and setter methods of the fields on the indexNew.jsp.

<property name="commandClass"><value>com.abc.strutspring.beans.LoginBean</value>
</property>
<property name="formView"><value>indexNew.jsp</value></property>
<property name="successView"><value>hello.jsp</value></property>
<property name="stringManipulator" ref="auth.service"/> //Reference to
Service interface.
</bean>

<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.htm">springappController</prop>

</props>
</property>
</bean>

<bean id="auth.service.impl" class="com.abc.strutspring.service.LoginImpl">


<property name="authenticatorDAO" ref="authenticatorDAOService"/> //Reference to
the DAO interface.

</bean>

<bean id="auth.service"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces"
value="com.abc.strutspring.service.Login"/>
<property name="target" ref="auth.service.impl"/> //Reference to the
service implementation class.

</bean>

<bean id="auth.service.daoimpl"
class="com.abc.strutspring.dao.LoginDataManipulatorImpl">
<property name="dataSource"> <ref local="dataSourceDBDirect"/>
</property> //Reference to the dataSourceDBDirect bean which
contains the connection parameters.

</bean>

<bean id="authenticatorDAOService"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces"
value="com.abc.strutspring.dao.LoginDataManipulator"/>
<property name="target" ref="auth.service.daoimpl"/>//Reference to
the DAO implementation class.
</bean>

<bean id="dataSourceDBDirect"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-
method="close">
<property name="driverClassName"
value="sun.jdbc.odbc.JdbcOdbcDriver"/>
<property name="url" value="jdbc:odbc:DBNAME "/>
<property name="username" value="U@Name"/>
<property name="password" value="abc@1234"/>
</bean>//Connection Parameters

</beans>

// Do not directly connect your components and services together in code but
describe which services are needed by which components in a configuration file.
This concept is called Wiring.

5. Since the JSP submits itself to the Controller mentioned in the springapp-
servlet.xml file, the next step is to create the Controller itself.

Sample Code for the solution: (SpringappController.java)

/**Package Declaration**/
package com.abc.strutspring.controller;
/**Java Imports**/
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
/**Application Imports**/
import com.abc.strutspring.beans.LoginBean;
import com.abc.strutspring.service.Login;

public class SpringappController extends SimpleFormController


{

//creating a reference of the service interface


Login stringManipulator;

/**
* Method onSubmit
* @param HttpServletRequest
* @param HttpServletResponse
* @param Object
* @param BindException
* @return ModelAndView
*
*/

protected ModelAndView onSubmit(HttpServletRequest request,


HttpServletResponse response, Object command, BindException e)
throws Exception {

//Typecasting the command object of the Object class into the


//LoginBean object to access attribute values

LoginBean loginBean = (LoginBean)command;

//Calling the carryData method of the service layer using


reference of
//the service interface
String s1 = stringManipulator.carryData(loginBean);

//Calling the fetchData method of the service layer using


reference of
//the service interface
List dataList = stringManipulator.fetchData(loginBean);

//Setting the returned string into request


request.setAttribute("data1",s1);

//Setting the returned list into request


request.setAttribute("dataList",dataList);

//Returning the view


return new ModelAndView(getSuccessView());

//Getter and Setter methods of stringManipulator


/**
* @return stringManipulator
*/
public Login getStringManipulator() {
return stringManipulator;
}

/**
* @param login
*/
public void setStringManipulator(Login login) {
stringManipulator = login;
}

}//End of class SpringappController

6. After the jsp is submitted, the control comes to the onSubmit method of
the controller class (Same as the execute method of the Struts Action
class). The data from the JSP is passed to this method using the command
object of the Object class. The Controller then typecasts the command
object of the Object class into the LoginBean object to access the attribute
values. The controller refers to the service interface using the reference of
the Service interface created in the controller class itself. Using the
reference of the service interface, the controller calls a method of the
Service class and passes the LoginBean object as an argument to this
method.
7. The Service interface contains the definitions of the methods in the
Service layer.

Sample Code for the solution: (Login.java)

/**Package Declaration**/
package com.abc.strutspring.service;
/**Java Imports**/
import java.util.ArrayList;
import java.util.List;
/**Application Imports**/
import com.abc.strutspring.beans.LoginBean;

public interface Login {

//Definition of method carryData


public String carryData(LoginBean loginBean);

//Definition of method fetchData


public List fetchData(LoginBean loginBean);

}//End of interface Login

8. From the wiring done in springapp-config.xml, the control goes to the


implementing class of the Service interface. This class receives the data
from the Controller class, creates a reference of the DAO interface and
using that reference calls a method of the DAO layer and passes the
loginBean object as an argument to the DAO layer.

Sample Code for the solution: (LoginImpl.java)

/**Package Declaration**/
package com.abc.strutspring.service;
/**Java Imports**/
import java.util.ArrayList;
import java.util.List;
/**Application Imports**/
import com.abc.strutspring.beans.LoginBean;
import com.abc.strutspring.dao.LoginDataManipulator;

public class LoginImpl implements Login{

//Creating a reference of the DAO interface


LoginDataManipulator authenticatorDAO;

/**
* Method carryData
* @param LoginBean
* @return String
*/

public String carryData(LoginBean loginBean)


{
return authenticatorDAO.carryData(loginBean);
}

/**
* Method fetchData
* @param LoginBean
* @return List
*/

public List fetchData(LoginBean loginBean)


{
List dataList = authenticatorDAO.fetchData(loginBean);
return dataList;
}
/**
* @return
*/
public LoginDataManipulator getAuthenticatorDAO() {
return authenticatorDAO;
}

/**
* @param manipulator
*/
public void setAuthenticatorDAO(LoginDataManipulator manipulator) {
authenticatorDAO = manipulator;
}

}//End of class LoginImpl

9. The DAO interface contains the definitions of the methods in the DAO
layer.

Sample Code for the solution: (LoginDataManipulator.java)

/**Package Declaration**/
package com.abc.strutspring.dao;
/**Java Imports**/
import java.util.ArrayList;
import java.util.List;
/**Application Imports**/
import com.abc.strutspring.beans.LoginBean;

public interface LoginDataManipulator {


//Definition of method carryData
public String carryData(LoginBean loginBean);

//Definition of method fetchData


public List fetchData(LoginBean loginBean);

}//End of interface LoginDataManipulator

10. The DAO Implementation class receives the loginBean object from the
Service Implementation class and contains all the methods in which the
database transactions are performed. This class extends JdbcDaoSupport
class which is an inbuilt class of Spring framework which provides the
JDBC functionality. The query is fired by making an object of the
JdbcTemplate class which is again provided by the framework.

Sample Code for the solution: (LoginDataManipulatorImpl.java)

/**Package Declaration**/
package com.abc.strutspring.dao;
/**Java Imports**/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultReader;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**Application Imports**/
import com.abc.strutspring.beans.LoginBean;
import com.abc.strutspring.dto.DataDTO;

public class LoginDataManipulatorImpl extends JdbcDaoSupport implements


LoginDataManipulator
{

/**
* Method carryData
* @param LoginBean
* @return String
*/

public String carryData(LoginBean loginBean)


{

//String retValue =
loginBean.getUserName()+loginBean.getPassword();
String userName = loginBean.getUserName();
String retValue = userName+" : Following drugs are covered under
your plan";
return retValue;
}

/**
* Method fetchData
* @param LoginBean
* @return List
*/

public List fetchData(LoginBean loginBean)


{
JdbcTemplate jt = getJdbcTemplate();
List dataList = jt.query("select effected_drug_nm,
alternate_drug_nm from gahpt0bd.chng_form_drug_alt", new
RowMapperResultReader(new TasksRowMapper()));
return dataList;
}

class TasksRowMapper implements RowMapper


{

/**
* Method mapRow
* @param ResultSet
* @param int
* @return Object
*/

public Object mapRow(ResultSet rs, int index) throws SQLException


{
DataDTO user = new DataDTO();
user.setEffectedDrug(rs.getString("effected_drug_nm"));
user.setAlternateDrug(rs.getString("alternate_drug_nm"));
return user;
}
}//End of class TasksRowMapper
}//End of class LoginDataManipulatorImpl

11. The data is returned to the Controller in the form of a DTO object. (DTO
class contains the getter and setter methods of the fields on the JSP.)

12. The controller sets the received data in the session and returns the control
to the target jsp (return new ModelAndView (“target.jsp”);).

13. On the target JSP, the data is retrieved from the session and displayed to
the user using JSTL tags or Scriptlets.

References:

1. http://www-128.ibm.com/developerworks/library/wa-spring1/
2. http://www.devx.com/Java/Article/22134

You might also like