You are on page 1of 29

PRESENTATION ON SPRING MVC

Eos Software Systems Pvt Ltd.


INTRODUCTION

Spring is an open source framework , which is very flexible while developing any
kind of application.

Spring is a light weight framework.

Spring is having total six modules.

We can use the modules independently or combine depending on the type of


application and requirement.
The 6 modules of Spring framework is :-

● IOC(Inversion of Control).

● AOP(Aspect Oriented Programming).

● DAO & JDBC.

● ORM(Object Relational Mapping System).

● J2EE.

● Web & MVC


Spring Framework came with every module for every tier. No other
framework contains these many modules.

Tier:- It is a clear separation of two or more Systems arranged by


one after another.
Possible Tiers while developing an application:-

UI PRESENTATION BUSINESS INTEGRATION DATABASE


TIER TIER TIER TIER TIER
Three core collaborating components

MVC = Model-View-Controller.
Clearly separates business, navigation and presentation
logic.

Controller
Handles navigation logic and interacts with the service
tier for business logic
Model
The contract between the Controller and the View
Contains the data needed to render the View
View
Renders the response to the request
Pulls data from the model
UI Tier: User Interface Tier. Like a web browser.

Presentation Tier: CSS, HTML, JavaScript, Images,


Servlet, JSP, Web MVC Module of Spring, Struts.

Business Tier: We can use plain java class, java beans,


Ejb, messaging services.

Integration Tier: JDBC or any ORM tools like hibernate,


Ibatis. For this, spring is providing JDBC&DAOmodule.

Database Tier: Under this Enterprise


Information Services will come.
DISPACHER SERVLET
1 2

JSP WEB.XML
Request HANDLER MAPPING

Response 4 DAO
To
7 JSP 6 CONTROLLER (Saving or
User
5 retrieving/up
dating data)
The transition of the spring MVC flow is described below:-

Transition 1:- User sends request to the server by submitting form / by


clicking the hyperlink etc. Request is initially given to
Web.xml.
Transition 2:- Web.xml routes request to DispacherServlet by looking at
<servlet-mapping> tag.
Transition 3:- Inside DispacherServlet , first 'HandlerMapping' handed over
request to suitable 'controller'.
Transition 4:- Controller maps request to proper Model class(pojo classes)
If database operation is needed then that should be carried
out in DAO.
Transitionn5:- If needed then attach attributes into request/session
/application scope and return back to the controller.
Transition 6:- Controller simply returns it to any View(JSP/HTML etc)
Transition 7:- JSP/HTML is viewed back to user
Web.xml
User sends the request and that request is initially given to the web.xml file.
DispacherServlet class is defined inside <servlet-class> . This class can be
used in a spring WebMVC application only if it is configured in the web.xml
file of any web application.
we should configure the DispacherServlet by giving the url-mapping like *.htm

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
DispacherServlet class

The DispacherServlet class is an important part of Spring Web MVC


framework. It is used for intercepting the incoming requests and
determines which controller handels the request.

It is the servlet which handles the Http request and is inherited from
the HttpServlet base class.

The function of the DispacherServlet class is just like a front


controller where each request goes through the controller. This
class can be used in a spring WebMVC application if it is configured
in the web.xml file of any web application.
Handler Mapping Interface
Handler mapping is a technique ,which handles the execution of
controllers and helps us match a specified URL. It is used for mapping
the incoming requests to appropriate handlers, which are actually
simple controllers, providing the handleRequest() method to forward
our request.
The SimpleUrlHandlerMapping class is one of the example of
handler mapping.
The SimpleUrlHandlerMapping class is used to handle more complex
URL's. It is configured in the application context and compiles the
rules of matching the URL's.
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
>
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
<prop key="home.htm">employeeHome</prop>
<prop key="employee.htm">employeeForm</prop>
</props>
</property>
</bean>
Detailed explanation
User sends request to the server by submitting form / by clicking the hyperlink etc.
Request is initially given to Web.xml.
Inside Web.xml we should configure the DispacherServlet by giving the url-
mapping like *.htm.
Then we need to create a DispacherServlet.xml file in which we will do the Spring
url mappings.
DispacherServlet.xml will load the Spring configuration files. Inside configuration file
the root node is beans and inside that there are many bean tags in which we use
to define different bean.
One of the bean is url-mapping and inside that we can define property mappings.
Inside which the url home.htm is mapped to employeeHome.

Inside DispacherServlet we will also configure the view in which we will define that
it should take .jsp file as a View or .html file as a View etc.
Inside DispacherServlet we will also configure the controller
CONTROLLER
Spring provides many types of controllers and the best way to decide
which controller type to use probably is by knowing what type of
functionality you need. For example, do your screens contain a form?
Do you need wizard like functionality? Do you just want to redirect to
a JSP page and have no controller at all? These are the types of
questions you will need to ask yourself to help you narrow down the
choices.
ABSTRACT CONTROLLER

public class EmployeeHome extends AbstractController

{
EmployeeDao employeeDao;
public void setEmployeeDao(EmployeeDao employeeDao)
{
this.employeeDao = employeeDao;

}
protected ModelAndView handleRequestInternal(HttpServletRequest
request,HttpServletResponse response) throws Exception
{
Map model = new HashMap();
String view = "employeeHome";

model.put("employees", employeeDao.getEmployeeList());

return new ModelAndView(view, model);


}

}
The Model And View Class

The ModelAndView class holds a view(Web page) and a model of the


Spring MVC framework, which contains the bean names and the
corresponding objects, such as a form.
Every controller's execution must return a ModelAndView instance
that comprises a view and a model.
Form Controllers
EXAMPLE
SimpleFormController: best to use for processing forms

public class EmployeeController extends SimpleFormController


{
EmployeeDao employeeDao;

public void setEmployeeDao(EmployeeDao employeeDao)


{
this.employeeDao = employeeDao;
}
Protected object formBackingObject(HttpServletRequest request) throws Exception
{
Employee employee=null;
Integer id=null;

//check whether the id is null or not by getting the id and if its null then create a new employee
object or else call the employee dao to get the details.
}
protected ModelAndView showForm(HttpServletRequest request,HttpServletResponse
response, BindException errors)throws Exception
{
String viewName = "edit";
System.out.println("c");
if (request.getParameter("edit") != null)
{
}
else if (request.getParameter("save") != null)
{
}

return showForm(request, errors, viewName);


}
protected void onBindAndValidate(HttpServletRequest request,Object command, BindException
errors) throws Exception {
//int id = Integer.parseInt("id");
Employee employee = (Employee)command;

if(employee.getFirstName() == null || employee.getFirstName().isEmpty())


{
errors.rejectValue("firstName", null,null,"Enter employee first name.");
}
}
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,
Object command, BindException errors)throws Exception {

if(!errors.hasErrors()){
Map map = new HashMap();
employeeDao.save((Employee)command);
System.out.println("d");
map.put("employee",command);
return new ModelAndView("successView",map);
}
return showForm(request,response, errors);
}

}
SimpleFormController:- best to use for processing forms.
FormBackingObject():- Retrive the command object which
can be from session or may be from database.
ShowForm:- Completes ModelAndView and returns
command object stored in session if configured . Renders
the actual form.
onBindAndValidate:- Allows you to bind parameters to the
command that don't need validation.
If validation fails then add errors to the ModelAndView and
show the form again.
Implementing Hibernate With Spring Framework

While integrating the hibernate and the spring framework, you need to
perform several steps and functions.

1. Configuring SessionFactory in Spring


2. Implementing DAO's using Hibernate Template Class
Configuring SessionFactory in Spring
The session interface in the Hibernate API provides methods to find, save,
and delete objects in the relational database.
The Hibernate Session is created by creating the sessionfactory. For session
creation,the Spring API provides implementation of the AbstractSession-
FactoryBean subclasses.

LocalSessionFactoryBean :- Classes needs to be configured with the


mapping file locations. These file locations need to be local from the
application's point of view.This is done in applicationcontext.xml file.
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
<value>ContactInfo.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
Implementing DAOs using HibernateTemplate class

The Spring API contains HibernateTemplate class provide


template methods for different types of Hibernate operations such
as managing them. The methods available in the
HibernateTemplate class ensure proper functioning of Hibernate
sessions, such as opening and closing of the sessions and so on.
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="mySessionFactory"/>
</property>
</bean>
What is a DAO?
DAO pattern
– Separation of data access logic from business logic
– Enables easier replacement of database without
affecting business logic
public class EmployeeDao extends HibernateDaoSupport
{
public List getEmployeeList(){
return getHibernateTemplate().find("from Employee");
}
public void save(Employee employee){
getHibernateTemplate().saveOrUpdate(employee);
}
public Employee getEmployee(Integer id){
return getHibernateTemplate().load(Employee.class, id);
}

}
POJO Classes
POJO:-(Plain old Java object)For creating Persistent object for saving
datas
public class Employee
{
Integer id =null;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
}
Mapping
● The process of specifying the bindings between an object
model and a database schema
● Principal mechanism is via XML mapping files
● Defacto file name extension: is .hbm.xml
● Multiple ways to set this up: a single file, one file per
class. Best practice is is to use one file per class,
with each file placed next to its corresponding class
file in the package hierarchy, and loaded as a resource
One-to-One Mapping
EXAMPLE
<hibernate-mapping> (Employee.hbm.xml)
<class name="com.employee.model.Employee" lazy="false" table="employee">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name"/>
<property name="middleName" column="middleName"/>
<property name="lastName" column="lastName"/>
<one-to-one name="contactInfo" lazy="false" class="com.employee.model.ContactInfo" />
</class>
</hibernate-mapping>

<hibernate-mapping> (ContactInfo.hbm.xml)
<class name="com.employee.model.ContactInfo" lazy="false" table="contactinfo">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="email" column="email"/>
<property name="city" column="city"/>
<property name="state" column="state"/>
<property name="phno" column="phno" />
</class>
</hibernate-mapping>
The ViewResolver Interface

ViewResolver is an interface that manages mapping between the


logical and actual views .A bean that implements the ViewResolver
interface is used for resolving a view.

Implementation of ViewResolver interface by the urlBasedViewResolver


class:-
<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolve
r"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />

The urlBasedViewResolver class implements the viewResolver interface to map the logical
views with URL's. This class uses the URL to render response in the form of View technologies
such as a JSP page etc.
Creating the Views

To create a view , we need to create jsp pages and that are used to
display the view(Web page) based on the Spring Web MVC paradigm.

You might also like