You are on page 1of 168

Introduction to Spring

Sensitivity: Internal & Restricted


Agenda

1 What is Spring?

2 Why Spring?

3 Spring Architecture

Sensitivity: Internal & Restricted © confidential 2


Objectives
At the end of this session, you will be able to:
• Understand What Spring Framework is
• Understand Spring Architecture and it uses

Sensitivity: Internal & Restricted


What is Spring?

Sensitivity: Internal & Restricted


What is Spring ?
▪ Do you know to make a Simple bean Java class? If yes, Then your ready for Spring
▪ In Spring all business modules are simple Bean class or popularly called POJO (Plain OLD
Java Object)

Spring is a popular open source application framework that can make J2EE
development easier by enabling a POJO-based programming model

▪ Spring is not J2EE Application framework but it well integrates with selective J2EE
specifications like Servlet API, JPA etc

Sensitivity: Internal & Restricted © confidential 5


Why Spring ?
Enterprise
services to
Plain Old
Java Objects
(POJO's)

Easy to unit
Spring MVC
test

Spring
features

Dependency Consistent
Injection(DI) framework for
or IOC data access

Less or
almost zero
coupling

Sensitivity: Internal & Restricted © confidential 6


Spring Architecture

Sensitivity: Internal & Restricted © confidential 7


Spring Architecture
▪ Spring Core: Contains the most fundamental part of Spring Framework
▪ Among them the most basic and important one is DI (dependency Injection) or IOC (Inversion
Of Control)
▪ It’s a process where IOC container takes the responsibility of providing (injecting) the
dependencies of an Object either through the constructor or setter methods.
▪ Spring AOP: Spring has its own Aspect Oriented Programming technology framework
▪ This enables modularization of concerns for enterprise services, declarative transaction
management services, logging and securities (crosscutting concerns) etc.
▪ Spring ORM: The ORM package provides integration layers for popular object-relational
mapping(ORM) APIs, including JDO, Hibernate and iBatis
▪ Spring Web: The Spring Web module is part of Spring’s web application development stack,
which includes Spring MVC
▪ Spring DAO: The DAO (Data Access Object) support in Spring is primarily for standardizing the
data access work using the technologies like JDBC, Hibernate or JDO
Sensitivity: Internal & Restricted © confidential 8
Summary
• In this module, we have learnt:

▪ Spring as Framework

▪ Features of Spring

▪ Architecture of Spring

▪ Various Modules of Spring

Sensitivity: Internal & Restricted © confidential 9


Thank you

Sensitivity: Internal & Restricted


Spring basics

Sensitivity: Internal & Restricted


Agenda

1 Spring Core

2 First Spring Application

Sensitivity: Internal & Restricted © confidential 2


Objectives
At the end of this session, you will be able to:
• Understand Core Spring framework
• Understand the steps involved in creating a simple Spring Application

Sensitivity: Internal & Restricted


Spring Core

Sensitivity: Internal & Restricted


Core Spring

▪ The Core Spring can be thought of a Framework and a Container for managing Business
Objects and their relationship

▪ With Spring Framework, most of the times we don't need to depend on Spring specific
Classes and Interfaces

▪ This is unlike other Frameworks, where the framework will force the Client Applications to
depend on their propriety Implementations

▪ Business Components in Spring are POJO (Plain Old Java Object) or POJI (Plain Old
Java Interface)

▪ These Business components are configured to the Spring Container for rendering

Sensitivity: Internal & Restricted © confidential 5


First Spring
Application

Sensitivity: Internal & Restricted


First Spring Application

▪ Let us understand the various components

▪ What is needed?
▪ Simple Java classes to represent our business needs (POJO)
▪ Configuration details to instruct how to manage the business objects
▪ And Spring jars for bringing both together

▪ We would create Maven Projects to take care of the Spring dependencies


▪ i.e. Required Spring jars and its compatibilities between them

▪ Let us take a Simple HelloWorld Application; here our base requirement is to display the
content contained by the data field msg

Sensitivity: Internal & Restricted © confidential 7


First Spring Application
▪ HelloWorld Class

NOTE: We are just understanding the components :


Step by step guide to create the application is given at the end

Sensitivity: Internal & Restricted © confidential 8


First Spring Application
▪ A Normal Application for wanting to use this HelloWorld class would look like this
▪ Here the Related class(GeneralMain) creates
and maintains the required objects of
HelloWorld class
▪ Object Graph created for this scenario would
also look simple with 2 class
▪ When the application grows; the no of object
references increases with Object Graph
complexity

▪ Spring removes this overhead; It creates and delivers the Objects to the related class

▪ Delivering of Objects to the related class is called Dependency Injection(DI) or

▪ IOC Inversion Of Control as Spring takes the control in Object life cycle
Sensitivity: Internal & Restricted © confidential 9
First Spring Application
▪ We need to configure the Spring Container to express
▪ The spring beans
▪ Spring bean’s dependencies
▪ Services needed by these beans
▪ Ways to implement the configuration in Spring are
▪ XML-Based Configuration
▪ Widely used approach. Where <bean> tag is used to define Spring beans
▪ Java-Based Configuration
▪ Java class is used to define the configuration using Annotations like
▪ @Configuration – to annotate the class as Configuration class
▪ @Bean – to annotate the method defining the bean class
▪ Annotation-Based Configuration
▪ It’s a combination of
▪ XML Configuration to express auto scanning feature
▪ Annotations to express the components like
▪ @Component, @Service
▪ @Autowired

Sensitivity: Internal & Restricted © confidential 10


First Spring Application
▪ For Initial Demos we use XML configuration file
▪ Let us look at the configuration File for our HelloWorld class
▪ Named as beans.xml

Sensitivity: Internal & Restricted © confidential 11


First Spring Application
▪ Last step is to create the client class to use the Spring framework functionality
▪ There are 2 ways
▪ BeanFactory
▪ Provides Advanced Configuration for managing any type of Bean, with any type of storage
facility
Resource resource = new FileSystemResource("src/main/resources/beans.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
HelloWorld helloWorld = beanFactory.getBean(HelloWorld.class);
helloWorld.display();

▪ ApplicationContext
▪ Is built over BeanFactory with added functionalities like
▪ Easy integration with Spring AOP
▪ Event Propogation
▪ Enterprise centric functionalities and more
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld = context.getBean(HelloWorld.class);
helloWorld.display();

Sensitivity: Internal & Restricted © confidential 12


First Spring Application
For the Step by Step Guide of creating First Spring Application
Refer: First Spring Projects.pdf

Sensitivity: Internal & Restricted © confidential 13


BeanFactory – A better understanding
▪ BeanFactory is a container that manages all the beans
▪ Configuration
▪ And life cycle [Initialization , rendering , destruction ]
▪ BeanFactory Interface has multiple implementation classes
▪ Commonly used class for instantiation of BeanFactory interface is XMLBeanFactory
▪ XMLBeanFactory is deprecated with Spring 3.1
▪ Alternatively we can use

BeanDefinitionRegistry beanDefinitionRegistry = new DefaultListableBeanFactory();


XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanDefinitionRegistry);
reader.loadBeanDefinitions(new ClassPathResource("SPRING_CONFIGURATION_FILE"));

Sensitivity: Internal & Restricted © confidential 14


Configuration File – A better understanding
• Bean Life Cycle
• The Bean objects defined in the Xml Configuration File undergoes a Standard Lifecycle
Mechanism
• We can enhance or modify the lifecycle of bean objects by using interfaces like
InitializingBean and DisposableBean
• The InitializingBean interface has a single method called afterPropertiesSet() which will
be called immediately after all the property values that have been defined in the Xml
Configuration file is set
• The DisposableBean has a single method called destroy() which will be called during the
shut down of the Bean Container

Sensitivity: Internal & Restricted © confidential 15


Configuration File – A better understanding
• Example code illustrating the usage of ‘Life Cycle Interfaces’

import org.springframework.beans.factory.*;
public class Employee implements InitializingBean, DisposableBean {
private String name;
private String id;
public void afterPropertiesSet() throws Exception {
System.out.println("Employee->afterPropertiesSet() method called");
}
public void destroy() throws Exception {
System.out.println("Employee->destroy() method called");
}
}

Sensitivity: Internal & Restricted © confidential 16


Configuration File – A better understanding
▪ Order of Creation of Beans
▪ We can control the bean creation order by using the depends-on attribute of the bean tag
▪ depends-on attribute take the bean identifier names which needs to be defined prior to the
current bean
▪ Example code – controlling the order of creation of Beans

<bean id = "joseph" class = "spring.complex.Employee" depends-on = "admin">


</bean>
<bean id = "admin" class = "spring.complex.Department" depends-on = "oracle">
</bean>
<bean id = "oracle" class = "spring.complex.Organisation">
</bean>

Sensitivity: Internal & Restricted © confidential 17


Thank you

Sensitivity: Internal & Restricted


Step by Step guide for Maven based Spring Projects.
Demo1 : Simple Hello World Spring Project.

1. Select J2EE Perspective in Eclipse.


2. Choose Maven Project

3. Check Create a Simple Project option. And Click Next

4. Give the Artifact Details:


a. Group ID : that would be your package name.
b. ArtifactID : your Application Name
c. And click finish

Sensitivity: Internal & Restricted


5. Project is created.
a. Added Spring core and Spring context dependencies under pom.xml file

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
</dependencies>

b. You can refer the below link for version and artifact details
https://mvnrepository.com/artifact/org.springframework/spring-core/5.2.1.RELEASE

Sensitivity: Internal & Restricted


6. Once we add the dependencies you can see a new set of library called Mavan dependency with
all the supporting jars for Spring based application.

7. Create a package called com.wipro.sample under src/main/java.


a. Create a class called HelloWorld in the above created package.

Sensitivity: Internal & Restricted


8. Create a xml file called beans.xml under src/main/resources and declare the bean id for the
HelloWorld class

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


<!-- Root element beans which defines the bean objects -->
<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"
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">

<!-- Bean tag is used to create bean objects -->


<bean id="msgBean" class="com.wipro.sample.HelloWorld">
<!-- Value for msg String Object is injected here -->
<property name="msg" value="The World is Bright"></property>
</bean>
</beans>

9. Create the UserMain class in the same com.wipro.sample package and run the same.

Resource resource = new FileSystemResource("src/main/resources/beans.xml");


BeanFactory beanFactory = new XmlBeanFactory(resource);
HelloWorld helloWorld = beanFactory.getBean(HelloWorld.class);
helloWorld.display();

Sensitivity: Internal & Restricted


10. Change the UserMain code to support ApplicationContext instead of BeanFactory

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");


HelloWorld helloWorld = context.getBean(HelloWorld.class);
helloWorld.display();

Sensitivity: Internal & Restricted


Spring
Inversion Of Control

Sensitivity: Internal & Restricted


Agenda

1 Inversion of Control (IoC)

2 Dependency Injection

3 Dependency Injection - Autowiring

Sensitivity: Internal & Restricted © confidential 2


Objectives
At the end of this session, you will be able to:
• Understand What is Inversion Of Control otherwise called as IOC
• Understand Implementation Of Dependency Injection
• Understand the usage of Autowiring in Dependency Injection

Sensitivity: Internal & Restricted


Inversion of Control (IoC)

Sensitivity: Internal & Restricted


Inversion of Control (IoC)
▪ Inversion Of Control, In Software Engineering is explained as a Programming
Technique were the object management (creation & association between the
objects) is done by the framework and not by the client

▪ In other words: Instead of Clients having the control to establish relationship


between Components, now the Framework carries this job

▪ There are several mechanisms to implement IOC


▪ Strategy design pattern
▪ Factory Pattern
▪ Dependency Injection

Sensitivity: Internal & Restricted


Inversion of Control (IoC)
▪ Let us understand this in a simple form.
▪ We have an Employee class which needs Employee address as a separate object association
▪ In general we’ll create the object in the Employee class itself or from client application

Sensitivity: Internal & Restricted © confidential 6


Inversion of Control (IoC)
▪ Let us understand this in a simple form.
▪ Let us see an example of client application
▪ Client or some class in between
has to create the object and
render it
▪ Here the Address Object is a data
object
▪ hence we may require more than
one object depending on the
data
▪ When the business component is
a service object then client
should create a singleton object
▪ Such Dependencies are removed and taken care by the framework; which we call Inversion Of
Control
Sensitivity: Internal & Restricted © confidential 7
Dependency Injection
(DI)

Sensitivity: Internal & Restricted


Dependency Injection (DI)
▪ Let us learn how to Implement Spring Inversion of Control using Dependency Injection

▪ Dependency Injection is a form of IOC that removes explicit dependence on container APIs
▪ ordinary Java methods are used to inject dependencies such as collaborating
objects or configuration values into application object instances.

▪ The two major flavors of Dependency Injection are


▪ Setter Injection (injection via JavaBean setters)
▪ Constructor Injection (injection via constructor arguments).

Sensitivity: Internal & Restricted © confidential 9


Dependency Injection (DI)
▪ Setter Injection
▪ using setter methods in a bean class, the Spring IOC container will inject the dependencies
▪ Let us take the same Employee Bean and Address bean example
▪ Configuration file to express setter injection of Address object to Employee Bean

<bean id="addressBean" class="com.wipro.bean.Address">


<property name="street" value="Pritech Park"></property>
<property name="city" value="Bengaluru"></property>
<property name="pincode" value="560037"></property>
</bean> addressBean Object is
injected as setter value
<bean id="employeeBean" class="com.wipro.bean.Employee"> to the EmployeeBean
<property name="name" value="ALLEN"></property>
<property name="empId" value="2000123"></property>
<property name="address" ref="addressBean"></property>
</bean>

Sensitivity: Internal & Restricted © confidential 10


Dependency Injection (DI)
▪ Constructor Injection
▪ using parameterized constructor of the bean, the Spring IOC container will inject the
dependencies while creating the object
▪ The constructor will take arguments based on number of dependencies required

<bean id="addressBean" class="com.wipro.bean.Address">


<property name="street" value="Pritech Park"></property> addressBean Object is
<property name="city" value="Bengaluru"></property> injected as constructor
<property name="pincode" value="560037"></property> value to the EmployeeBean
</bean>

<bean id="employeeBean" class="com.wipro.bean.Employee">


<constructor-arg index="0" type="java.lang.String" value="ALLEN"></constructor-arg>
<constructor-arg index="1" type="java.lang.String" value="2000123"></constructor-arg>
<constructor-arg index="2" type="com.wipro.bean.Address" ref="addressBean"></constructor-arg>
</bean>

Sensitivity: Internal & Restricted © confidential 11


Dependency Injection (DI) : Sample Demo
▪ Create the Bean class Employee and Address
Employee.java Address.java
public class Employee {
private String name; public class Address {
private String empId; public Address(){
private Address address;
public Employee(String name, String empId, Address }
address){ private String street;
this.name = name; private String city;
this.empId = empId; private String pincode;
this.address = address;
} // TODO Getters and Setters for all Properties
}
// TO DO Getters and Setters for all properties
}

For sample demo refer :: Spring IOC Demo Projects.pdf

Sensitivity: Internal & Restricted © confidential 12


Dependency Injection (DI) : Sample Demo
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
▪ Create the xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
ApplicationContext.xml xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
for Constructor Injection http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="addressBean" class="Address">
<property name="street">
<value>Main Street</value>
</property>
<property name="city">
<value>Bangalore</value>
</property>
<property name="pincode">
<value>567456</value>
</property>
</bean>
<bean id="employeeBean" class="Employee">
<constructor-arg index="0" type="java.lang.String" value="MyName"/>
<constructor-arg index="1" type="java.lang.String" value="001"/>
<constructor-arg index="2">
<ref bean="addressBean"/>
</constructor-arg>
</bean></beans>

Sensitivity: Internal & Restricted © confidential 13


Dependency Injection (DI) : Sample Demo
• Create the main class to test the app
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class ConstructorInjection {


public static void main(String args[]){
Resource xmlResource = new FileSystemResource(“ApplicationContext.xml");
BeanFactory factory = new XmlBeanFactory(xmlResource);
Employee employee = (Employee)factory.getBean("employeeBean");
Address address = employee.getAddress();
System.out.println(employee.getName());
System.out.println(employee.getEmpId());
System.out.println(address.getCity());
System.out.println(address.getStreet());
System.out.println(address.getPincode());
}
}

Sensitivity: Internal & Restricted © confidential 14


Dependency Injection (DI) : Sample Demo
▪ Edit ApplicationContext.xml (for Setter Injection)
▪ Employee.java (for Setter Injection) : no constructor with ‘address’ as parameter, only setter &
getter methods
<beans …>
<bean id="addressBean" class="Address">
<property name="street“ value=“Normal Street” />
<property name="city“ value=“Bangalore” />
<property name="pincode“ value=“567456” />
</bean>
<bean id="employeeBean" class="Employee">
<property name="name" value="MyName"/>
<property name="empId" value="001"/>
<property name="address" ref="addressBean"/>
</bean>

</beans>

▪ Again execute the main application to experience the Setter Injection

Sensitivity: Internal & Restricted © confidential 15


DI Autowiring

Sensitivity: Internal & Restricted


Dependency Injection - Autowiring
▪ Object Injection can be automated by the concept of autowiring
▪ Instead of explicit referencing of the dependent object through setter or through
constructor; it can be automated by setting autowire attribute of the bean
▪ Different values of autowire attribute are
▪ byType - setter Injection
▪ byName - setter Injection
▪ constructor - Constructor Injecton
<bean id="addressBean" class="com.wipro.bean.Address">
<!-- Using Constructor for passing the values -->
<constructor-arg index="0" type="java.lang.String" value="Pritech Park"></constructor-arg>
<constructor-arg index="1" type="java.lang.String" value="Bengaluru"></constructor-arg>
<constructor-arg index="2" type="java.lang.String" value="560037"></constructor-arg>
</bean>

<bean id="employeeBean" class="com.wipro.bean.Employee" autowire="byType">


<property name="name" value="ALLEN"></property>
<property name="empId" value="2000123"></property>
</bean>
Sensitivity: Internal & Restricted
Dependency Injection - Autowiring
▪ byType looks for a bean definition of the required Object’s Type
▪ If there are more than one Bean definition found for the required Object Type, it raises
NoUniqueBeanDefinitionException Exception
<bean id="addressBean" class="com.wipro.bean.Address">
<!-- Using Constructor for passing the values -->
<constructor-arg index="0" type="java.lang.String" value="Pritech Park"></constructor-arg>
<constructor-arg index="1" type="java.lang.String" value="Bengaluru"></constructor-arg>
<constructor-arg index="2" type="java.lang.String" value="560037"></constructor-arg>
</bean>
<bean id="addressBean1" class="com.wipro.bean.Address">
<!-- Using Constructor for passing the values -->
<constructor-arg index="0" type="java.lang.String" value="new World"></constructor-arg>
<constructor-arg index="1" type="java.lang.String" value="Delhi"></constructor-arg>
<constructor-arg index="2" type="java.lang.String" value="450037"></constructor-arg>
</bean>

<bean id="employeeBean" class="com.wipro.bean.Employee" autowire="byType">


<property name="name" value="ALLEN"></property>
<property name="empId" value="2000123"></property>
</bean>
Sensitivity: Internal & Restricted
Dependency Injection - Autowiring
▪ byName injects the bean id value matching to the property name of the required
Object
<bean id="address" class="com.wipro.bean.Address">
<!-- Using Constructor for passing the values -->
<constructor-arg index="0" type="java.lang.String" value="Pritech Park"></constructor-arg>
<constructor-arg index="1" type="java.lang.String" value="Bengaluru"></constructor-arg>
<constructor-arg index="2" type="java.lang.String" value="560037"></constructor-arg>
</bean>

<bean id="employeeBean" class="com.wipro.bean.Employee" autowire="byName">


<property name="name" value="ALLEN"></property>
<property name="empId" value="2000123"></property>
</bean>

public class Employee {


private String name;
private String empId;
private Address address; //bean id value is same as the Address variable name
//Constructors and Getters and Setters are given
}
Sensitivity: Internal & Restricted
Dependency Injection - Autowiring

For detailed demo Refer :


Spring DI - Autowiring Demo.pdf

Sensitivity: Internal & Restricted


Summary
▪ In this module, we have learnt

▪ Inversion of Control methodologies


▪ Dependency Injection
▪ Setter Injection
▪ Constructor Injection
▪ Autowiring

Sensitivity: Internal & Restricted © confidential 21


Thank you

Sensitivity: Internal & Restricted


Spring IOC Demo Projects
I. Setter Based DI
a. Let us make a Maven Based Project.

b. Add the dependencies in the POM.xml file

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
</dependencies>

c. Under src/main/java – Create a package called com.wipro.bean


d. Under the package create 2 classes called
i. Address.java
ii. Employee.java

Address Class Code:


package com.wipro.bean;

public class Address {

private String street;

Sensitivity: Internal & Restricted


private String city;
private String pincode;
public Address() {
// TODO default constructor stub
}

public Address(String street, String city, String pincode) {


this.street = street;
this.city = city;
this.pincode = pincode;
}

public String getStreet() {


return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
@Override
public String toString() {
return "Address [street=" + street + ", city=" + city + ", pincode=" +
pincode + "]";
}

Employee Class Code:


package com.wipro.bean;

public class Employee {


private String name;
private String empId;
private Address address;
public Employee() {
super();
// TODO default constructor stub
}
public Employee(String name, String empId, Address address) {
super();
this.name = name;
this.empId = empId;

Sensitivity: Internal & Restricted


this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Employee [name=" + name + ", empId=" + empId + ",
address=" + address + "]";
}

e. Create the beans.xml configuration file under the src/main/resources


<?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"
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">

<bean id="addressBean" class="com.wipro.bean.Address">


<property name="street" value="Pritech Park"></property>
<property name="city" value="Bengaluru"></property>
<property name="pincode" value="560037"></property>
</bean>

<bean id="employeeBean" class="com.wipro.bean.Employee">


<property name="name" value="ALLEN"></property>
<property name="empId" value="2000123"></property>
<property name="address" ref="addressBean"></property>
</bean>
</beans>

f. Create the UserMain class under src/main/java – package com.wipro.services

Sensitivity: Internal & Restricted


II. Constructor Based DI

On to the same application above Let us change the beans.xml and UserMain to see difference
in Constructor based DI.

1. Create xml configuration file named beans-consdi.xml under src/main/resources


<?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"
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">

<bean id="addressBean" class="com.wipro.bean.Address">


<!-- Using Constructor for passing the values -->
<constructor-arg index="0" type="java.lang.String" value="Pritech
Park"></constructor-arg>
<constructor-arg index="1" type="java.lang.String"
value="Bengaluru"></constructor-arg>
<constructor-arg index="2" type="java.lang.String"
value="560037"></constructor-arg>
</bean>

<bean id="employeeBean" class="com.wipro.bean.Employee">


<constructor-arg index="0" type="java.lang.String"
value="ALLEN"></constructor-arg>
<constructor-arg index="1" type="java.lang.String"
value="2000123"></constructor-arg>
<constructor-arg index="2" type="com.wipro.bean.Address"
ref="addressBean"></constructor-arg>
</bean>

Sensitivity: Internal & Restricted


</beans>

2. Create UserMainConstructorDI class to test the constructor based DI.

Sensitivity: Internal & Restricted


Spring DI - Autowiring Demo

Autowiring

Can be autowired using 4 types


1. By Type
2. By Name
3. By constructor
4. @Autowired Annotation [We’ll see this with Spring MVC]

To understand the autowire concept better let us add print statements to the employee class
constructor and setter method of address field.
package com.wipro.bean;

public class Employee {


private String name;
private String empId;
private Address address;
public Employee() {
super();
// TODO default constructor stub
}
public Employee(String name, String empId, Address address) {
super();
this.name = name;
this.empId = empId;
this.address = address;
System.out.println("Address value @ constructor : "+address);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
System.out.println("Address value @ Setter Method : "+address);
}
@Override
public String toString() {

Sensitivity: Internal & Restricted


return "Employee [name=" + name + ", empId=" + empId + ", address=" +
address + "]";
}

1. Code example of autowire by type.

<?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"
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">

<bean id="addressBean" class="com.wipro.bean.Address">


<!-- Using Constructor for passing the values -->
<constructor-arg index="0" type="java.lang.String" value="Pritech
Park"></constructor-arg>
<constructor-arg index="1" type="java.lang.String"
value="Bengaluru"></constructor-arg>
<constructor-arg index="2" type="java.lang.String"
value="560037"></constructor-arg>
</bean>
<bean id="employeeBean" class="com.wipro.bean.Employee" autowire="byType">
<property name="name" value="ALLEN"></property>
<property name="empId" value="2000123"></property>

</bean>
</beans>

Sensitivity: Internal & Restricted


2. Code example of autowire by Name.
<bean id="address" class="com.wipro.bean.Address">
<!-- Using Constructor for passing the values -->
<constructor-arg index="0" type="java.lang.String" value="Pritech
Park"></constructor-arg>
<constructor-arg index="1" type="java.lang.String"
value="Bengaluru"></constructor-arg>
<constructor-arg index="2" type="java.lang.String"
value="560037"></constructor-arg>
</bean>

<bean id="employeeBean" class="com.wipro.bean.Employee" autowire="byName">


<!-- Property Name is address …. Auto reference by name -->
<property name="name" value="ALLEN"></property>
<property name="empId" value="2000123"></property>

</bean>

3. Code example of autowire by Constructor.


<?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"
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">

<bean id="addressBean" class="com.wipro.bean.Address">


<!-- Using Constructor for passing the values -->
<constructor-arg index="0" type="java.lang.String" value="Pritech
Park"></constructor-arg>

Sensitivity: Internal & Restricted


<constructor-arg index="1" type="java.lang.String"
value="Bengaluru"></constructor-arg>
<constructor-arg index="2" type="java.lang.String"
value="560037"></constructor-arg>
</bean>

<bean id="employeeBean" class="com.wipro.bean.Employee" autowire="constructor">


<constructor-arg index="0" type="java.lang.String"
value="ALLEN"></constructor-arg>
<constructor-arg index="1" type="java.lang.String"
value="2000123"></constructor-arg>
<!-- we are not passing any value for 3 argument, it automatically takes
through constructor using BY TYPE -->
</bean>
</beans>

Sensitivity: Internal & Restricted


Spring MVC

Sensitivity: Internal & Restricted


Agenda

1 MVC Overview 4 Core Components of Spring MVC

2 Spring MVC 5 First Spring MVC Application

3 Work Flow in Spring MVC 6 Spring Annotations


And Lifecycle of a request in Spring MVC

7 Spring MVC Application 2

Sensitivity: Internal & Restricted © confidential 2


Objectives
At the end of this session, you will be able to:
• Understand MVC Architecture
• Understand Spring MVC Architecture and its Work flow
• Understand the various Spring MVC components
• Understand Spring Annotations
• Understand How to create a Spring Web Application

Sensitivity: Internal & Restricted


MVC Overview

Sensitivity: Internal & Restricted


MVC Overview
▪ MVC => Model-View-Controller
▪ This pattern clearly separates applications into
▪ business (Model) logic,
▪ presentation (View) logic and
▪ navigation(Controller) logic
▪ Model
▪ It represents the data that is transferred between the View and the controller or to its other
business logic components (like services, dao)
▪ Controller
▪ Handles navigation logic, handles the request, interacts with the service tier for
business logic
▪ It acts as an interface between the view and the model
▪ View
▪ Interface to the client : What client sees and interacts with
▪ Renders the response to the request
▪ Pulls data from the model

Sensitivity: Internal & Restricted © confidential 5


MVC Overview - Separation Of Concern
▪ Separation Of Concern is a design principle for separating a computer application into
distinct sections
▪ Each section addresses a separate concern
▪ Separation of concern helps us in identifying these layers and responsibilities of each
layer
▪ A typical Web Application High Level Architecture may look like this

Sensitivity: Internal & Restricted © confidential 6


Spring MVC

Sensitivity: Internal & Restricted


Spring MVC
▪ Spring MVC is framework to develop web application based on MVC guidelines and
with all Spring benefits like IOC
Spring MVC = Web Application + MVC Guidelines + Spring Benefits

▪ Spring has clear separation of Concern, where each role could be achieved by a specific
object like
▪ Dispatcher- Servlet, Handler-mapping, Controller, Model Object, Form Object, View
Resolver, Validator etc.
▪ Spring supports different view technology like JSP, JSTL, Velocity, Thymeleaf,
FreeMarker etc.
▪ Model transfer or data transfer is flexible, it supports easy integration with any view
technology
▪ Spring MVC’s container WebApplicationContext by default gives all bean objects the
scope of HttpSession (i.e. Bean Objects are session scoped objects)

Sensitivity: Internal & Restricted © confidential 8


Front Controller Design

• Front controller design pattern is used to


provide a centralized request handling
mechanism
• This ensures that all requests will be handled
by a single handler
• This can be used do the authentication,
authorization, logging or tracking of request
and then pass the requests to corresponding
handlers

Sensitivity: Internal & Restricted © confidential 9


Work Flow in Spring MVC
And Lifecycle of a request in Spring MVC

Sensitivity: Internal & Restricted


Work Flow in Spring MVC
A High Level work flow of Spring MVC

Sensitivity: Internal & Restricted © confidential 11


Work Flow in Spring MVC
▪ Spring follows FrontController design pattern
▪ A servlet class called DispatcherServlet is an implementation of FrontController in Spring
to which initially all requests are mapped
▪ Any request to the Spring MVC application passes through the FrontController (i.e.
DispatcherServlet)
▪ DispatcherServlet provided by the Spring API which in turn sends calls to the respective
handler method mapping to the request
▪ Specific Requests are handled as methods and these handler methods are mapped to the
request using @RequestMapping Annotation
▪ The class containing the handler methods are called as controller written as POJO class
Annotated with @Controller
▪ Request routing is completely controlled by the Front Controller i.e. DispatcherServlet in
Spring

Sensitivity: Internal & Restricted © confidential 12


Lifecycle of a request in Spring MVC
▪ A request leaves the browser asking for a particular URL and optionally with request
parameters
▪ The request is first examined by the DispatcherServlet
▪ DispatcherServlet consults handler-mappings defined in a configuration file (Spring
Configuration file)
▪ It selects an appropriate controller and delegates to it to handle the request
▪ The controller applies appropriate logic to process the request which may in most times
results in some information or data to be return back to the page
▪ This information or data in called the model
▪ Model is associated with the logical name of the result page or rendering entity called view
▪ The whole (model data and result page’s logical name) is returned as a ModelAndView
object along with the request back to DispatcherServlet

Sensitivity: Internal & Restricted © confidential 13


Lifecycle of a request in Spring MVC (Contd.).
▪ DispatcherServlet then consults the logical view name with a view resolving object to
determine the actual view
▪ DispatcherServlet delivers the model and request to the view implementation which renders
an output and sends it back to the browser.

Sensitivity: Internal & Restricted © confidential 14


Core Components
of Spring
And Lifecycle of a requestMVC
in Spring MVC

Sensitivity: Internal & Restricted


Core Components of Spring MVC
▪ DispatcherServlet
▪ Spring’s Front Controller implementation
▪ Any request that comes to the application is first interfaced with the
DispatcherServlet
▪ Controller
▪ User created component for handling requests
▪ Encapsulates navigation logic
▪ Delegates requests to the service objects for business logic implementation
▪ Handler method returns the Model object and the logical view name to render it
▪ Model
▪ Data Object that is transmitted between the View, Business logic and Controller
▪ ViewResolver
▪ Used to map logical View names to actual View implementations

Sensitivity: Internal & Restricted © confidential 16


Core Components of Spring MVC
▪ View
▪ Responsible for rendering output
▪ Can be designed using any view technologies like simple JSP pages
▪ ModelAndView
▪ The ModelAndView class is simply a container to hold the model data to be
transported and the logical view name
▪ The Object is created and returned by the handler method of the Controller
▪ ModelAndView helps in returning both the Model and the view in one return by the
controller

Sensitivity: Internal & Restricted © confidential 17


First Spring MVC Application
And Lifecycle of a request in Spring MVC

Sensitivity: Internal & Restricted


First Spring MVC Application
▪ Let us understand how to create a simple Spring MVC application
▪ First we’ll create the app to request for the simple page
▪ Next we’ll enhance the same to display our dynamic message on the rendered page

▪ What is needed?
▪ 2 JSP Pages, index page and welcome page
▪ Simple Java class to represent user defined controller (POJO)
▪ Configuration details to instruct handler mapping
▪ And Spring jars for bringing all together

▪ We would create Maven Projects to take care of the Spring dependencies


▪ i.e. Required Spring jars and its compatibilities between them

Sensitivity: Internal & Restricted © confidential 19


First Spring MVC Application

▪ Let us set up the eclipse environment with WebServer ( Apache Tomcat Server 9 )
▪ Download Apache Tomcat server 9 and unzip the same
https://tomcat.apache.org/download-90.cgi
▪ Add the tomcat server to eclipse from Windows Preferences
▪ Server -> Runtime Environments -> search

Sensitivity: Internal & Restricted © confidential 20


First Spring MVC Application

▪ Create a Maven Project


▪ On first page choose Use default workspace and click
Next
▪ Under Archetype choose maven-archetype-webapp and
click Next
▪ Fill the Maven Project details
▪ Group ID :: com.wipro
▪ Artifact ID :: FirstMVCApp
▪ Click finish
▪ It takes little time and generates Spring Web Project
▪ The initial error is because the build path is not aware of
servlets and JSP APIs
▪ To set it Right click on project -> Properties -> Java Build
Path -> Add Library
▪ Server Runtime -> Apache Tomcat -> Finish

Sensitivity: Internal & Restricted © confidential 21


First Spring MVC Application
▪ Next set the dependencies in the POM <dependency>
<groupId>org.springframework</groupId>
file
<artifactId>spring-core</artifactId>
▪ Open POM.xml file <version>5.2.1.RELEASE</version>
▪ Add the following spring </dependency>
dependencies under the tag
<dependency>
<dependencies>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>

Sensitivity: Internal & Restricted © confidential 22


First Spring MVC Application
▪ Configure DispatcherServlet in web.xml and establish URL mappings
▪ Edit Web.xml file to include the below script
▪ This acts as the front controller
▪ In url-pattern we have just the /(slash) to indicate any request to this app should be
directed to the dispatcher
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Sensitivity: Internal & Restricted © confidential 23


First Spring MVC Application
▪ Next create the Spring configuration metadata in a configuration file named <servlet-
name>-servlet.xml in the WEB-INF directory of your web application
▪ i.e. File name has to be the dispatcher servlet name given in the web.xml file post fixed
with -servlet.xml
▪ In our case its dispatcher so the file name would be 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"
xmlns:context="http://www.springframework.org/schema/context"
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">

</beans>

▪ Note here we have added the spring-bean.xsd and spring-context.xsd


Sensitivity: Internal & Restricted © confidential 24
First Spring MVC Application
▪ In the Spring configuration file in between the <beans> tag we add the following script

<context:component-scan base-package="com.wipro" />

▪ When the request is received by the DispatcherServlet, it checks the Spring configuration
file (i.e. dispatcher-servlet.xml) for a mapping of the specified URL to a user defined
controller bean
▪ <contect:component-scan>is used to indicate the location were the required components
like User defined Controller beans and Service beans can be looked up for

Sensitivity: Internal & Restricted © confidential 25


First Spring MVC Application
▪ Next script to be added in the Spring configuration file is
<!-- Including the bean for View Resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

▪ Logical View name returned by the handler methods is resolved by the view resolver bean
class called InternalResourceViewResolver
▪ DispatcherServlet looks for a view resolver to resolve the logical view name that it got
from the ModelAndView object
▪ In our case all views except index.jsp has to be created under the prefix value

Sensitivity: Internal & Restricted © confidential 26


First Spring MVC Application
▪ Add the following code in Index.jsp to request for a new page called HelloPage.jsp

<a href="Hello">Click here </a>

▪ Create a new page called HelloPage.jsp under WEB-INF/views

Sensitivity: Internal & Restricted © confidential 27


First Spring MVC Application
▪ Let us create the Controller to handle the Hello request and Run the Application

@Controller
public class HelloController {

@RequestMapping("/Hello")
public String helloMethod() {
return "HelloPage";
}
}

Sensitivity: Internal & Restricted © confidential 28


Spring Annotations
And Lifecycle of a request in Spring MVC

Sensitivity: Internal & Restricted


Spring Annotations
▪ Spring has adopted Annotations in a very effective way like to describe the bean
configuration, bean wiring etc.
▪ Some Spring Core Annotations are
▪ @Autowired – used for Dependency Injection, It injects the object dependency implicitly
▪ @Configuration – used for defining Spring Configuration as a java class instead of XML
▪ @Bean – used for defining bean class in Spring Configuration class

▪ All beans in Spring are Components and they are annotated as @Component
▪ Based on the special purpose of the bean there are specific Annotations to mark them
like @Controller, @Service or @Repository which are inherited from @Component
▪ These are classified as Spring Stereotype Annotations
▪ These Annotations help in auto detect of the bean classes using classpath specified by
@ComponentScan or <context:component-scan>

Sensitivity: Internal & Restricted © confidential 30


Spring Annotations

@Controller
Represents the class as a Controller class
This is part of Spring MVC Application

@Service
Represents the class as a Business Layer
Class which contains business logic of the
application

@Repository
Represents the class as a
Database/Persistence Layer Class

Sensitivity: Internal & Restricted © confidential 31


Spring MVC Annotations
▪ Some Important Annotations of Spring MVC are
▪ @Controller – To create Controller beans, thus the class doesn’t have to explicitly
implement the basic Controller Interface or inherit any specific Controller classes
▪ This removes the direct dependency on the Servlets
▪ @RequestMapping – maps the request URL to the method which handles it
▪ This gave way to have more flexible method signatures for handler methods
▪ @ModelAttribute – to bind the Model object as method attribute or return object

@Controller Indicates the class as a controller class


public class HelloController {

@RequestMapping("/Hello") Maps the /Hello request url to the


public String helloMethod() { request handler method
return "HelloPage";
}
}

Sensitivity: Internal & Restricted © confidential 32


Spring MVC Application 2
And Lifecycle of a request in Spring MVC

Sensitivity: Internal & Restricted


Spring MVC Application 2
▪ Let us modify the previous demo to return a “Hello World” message back from the
Controller

@RequestMapping("/Hello") ▪ This method only returns a String which is the


public String helloMethod(){ logical view name
return "HelloPage"; ▪ To return both data (Hello World message) and the
} logical View name we use the object of a Class
called ModelAndView

▪ Edit the index.jsp to add new request 1. <a href="Hello">Welcome Demo </a>
2. <a href="HelloWorld">Demo with data </a>

▪ Edit the controller class to add new method for the HelloWorld request

Sensitivity: Internal & Restricted © confidential 34


Spring MVC Application 2
▪ As we have seen The ModelAndView class is a container to hold both the model data
and the logical view name
▪ After Spring MVC 2.5 with Annotations creating a handleRequest method is very simple
with combination of @RequestMapping and ModelAndView

@RequestMapping("/HelloWorld") ▪ Here @RequestMapping is mapped to


public ModelAndView sayHello() { the URL “/HelloWorld”
String msg = "Hello World"; ▪ Return type of the method is
ModelAndView mv = new ModelAndView object
ModelAndView("FirstPage","myMessage", msg); ▪ Which binds the model data named
return mv; myMessage with value from String called
} msg and the redirected page called
FirstPage for the view resolver

Sensitivity: Internal & Restricted © confidential 35


Spring MVC Application 2

▪ To Present the model data on to the view i.e. in JSP Page


▪ Here we are expressing the Spring Model data on the JSP page as Expression Language
▪ By giving the variables in between curly braces {} refixed with $ sign i.e. pattern ${..}
<h2>This is the message from Model :: ${myMessage} </h2>
▪ With Servlet version 2.4 and above EL evaluation is by default actvated
▪ If in case JSP does not evaluate the EL we can activate it by using the Page directive
property isELIgnored
<%@ page isELIgnored="false" %>

▪ Setting the isELIgnored property to false activates the EL

Sensitivity: Internal & Restricted © confidential 36


Spring MVC Application 2

▪ Executed Result of the Application

Sensitivity: Internal & Restricted © confidential 37


Summary
• In this module, we have learnt :

▪ MVC Architecture
▪ Spring MVC understanding
▪ Core Components of Spring MVC
▪ Flow of Request in Spring MVC based Web Application
▪ How to develop a Web Application using Spring MVC

Sensitivity: Internal & Restricted © confidential 38


Thank you

Sensitivity: Internal & Restricted


Spring MVC Project

1. Create Maven Project and choose use default workspace location


a. Click Next

2. Under Archetype choose maven-archetype-webapp from below given group Id and version
a. Group Id : org.apache.maven.archetypes
b. Version can be any latest version. Here It is taken 1.0
i. You can also pick a specific version by checking the Include snapshot archetypes
c. Click Next

Sensitivity: Internal & Restricted


3. Fill the Maven Project details
a. Group ID :: com.wipro
b. Artifact ID :: HelloMVCWorld
c. Click finish

4. This generates Spring Web Project. With the initial Error


a. This is because the build path is not aware of servlets and jsp APIs.
b. Add Tomcat server
i. Click on window menu -> preferences -> server -> Runtime Environment
1. Search the unzipped folder of your Apache Tomcat Server
c. right click on project -> Properties -> Java Build Path -> Add Library
d. Server Runtime -> Apache Tomcat -> Finish

Sensitivity: Internal & Restricted


5. Set the spring dependencies.
a. Open POM file
b. Add the following spring dependencies under the tag <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>

6. Set the dispatcher Servlet.


a. Edit the web.xml file
b. Include <servlet> and <servlet-mapping>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Sensitivity: Internal & Restricted


7. Create the Spring configuration file named 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"
xmlns:context="http://www.springframework.org/schema/context"
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="com.wipro" />

<!-- Including the bean for View Resolver -->


<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>

Sensitivity: Internal & Restricted


8. Create the views folder under WEB-INF for defining the views
a. Right click on WEB-INF folder NEW -> Folder (Enter Name as views ) - > finish.

9. Create the controller class named HelloController


a. Right click on Java Resources and create a package called com.wipro.controller
b. Under the package Create a class called HelloController

Sensitivity: Internal & Restricted


package com.wipro.controller;

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

//Add @controller Annotation to make this class as a Controller Class

@Controller
public class HelloController {
@RequestMapping("/Hello")
public ModelAndView sayHello() {
/**
* ModelAndView object created to be returned.
* With the redirected page called HelloPage for the view resolver
*/
ModelAndView mv = new ModelAndView("HelloPage");
/**
* Adding a model data named message
* with value from String called msg
*/
String msg = "Hello World";
mv.addObject("message", msg);
return mv;
}
}

10. Edit the Index.jsp page to initiate the call to HelloPage

<html>
<body>
<h2>Hello World!</h2>
<a href="Hello">Click here </a>
</body>
</html>

Sensitivity: Internal & Restricted


11. Create a new jsp page under WEB-INF -> views called HelloPage.jsp
a. Use ${message} for presenting the data stored in message model value from
ModelAndView object.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!-- Since our web app version is 2.3 EL is be default ignored --
-- Including the attribute isELIgnored to false : enables EL -->

<%@ page isELIgnored="false" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>This is the message from Model :: ${message }</h1>
</body>
</html>

Sensitivity: Internal & Restricted


12. Run the Application from index.jsp Page

Sensitivity: Internal & Restricted


Spring MVC and
Hibernate

Sensitivity: Internal & Restricted


Agenda

1 Spring MVC - Form Handling

2 Spring MVC Application:With Form Handling

3 Spring – Hibernate Application

Sensitivity: Internal & Restricted © confidential 2


Objectives
At the end of this session, you will be able to:
• Understand the role of Spring Form tags in JSP
• Understand How to create a Spring Web Application with form data
• Understand How to persist data using hibernate

Sensitivity: Internal & Restricted


Spring MVC Form
Handling

Sensitivity: Internal & Restricted


Spring MVC Form Handling
▪ Traditionally when handling from data in Web application we use HTML form and input
tags to accept data from client
▪ This data is received by the controller through request object is then converted into bean /
model class
▪ With Spring MVC the above 2 steps are encapsulated
▪ Spring MVC has a separate tag library to support form data
▪ These Spring tags are aware of data binding, It automatically sets and gets data from
the model
▪ Tags are more similar to HTML tags for easy understanding and familiarity of usage
▪ As It internally encapsulates HTML tags and its attributes
▪ Spring form tags are included in the JSP page using taglib

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

Sensitivity: Internal & Restricted © confidential 5


Spring Form Tags
▪ Spring MVC Form tags used for designing forms so that the data binding is taken care
▪ Let us look at few tags and their uses
▪ Form tag is a container tag that holds other form field representing tags like text fields,
radio button etc.
▪ Attribute action is HTML form action attribute
▪ It is used to specify the URL of the submission document (Absolute / Relative)
▪ Attribute method to indicate how to send the form data (get/post)
▪ Attribute modelAttribute is gives the name of the model attribute under which the form
object is exposed

<form:form action="InsertDepartment" method="post" modelAttribute="department">

▪ Here department is the Model object to / from which the form field values are mapped

Sensitivity: Internal & Restricted © confidential 6


Spring Form Tags
▪ Let us look at few tags and their uses

Tags Purpose
<input> This is similar to <input type=“text”> of html ; text field
<password> This is similar to <input type=“password”> of html ; text field with encrypted text

<select> This is a drop down field


<radiobutton> This is radio button option field
<checkbox> This is check box option field

▪ All these tags have path attribute which sets the property path for binding data
▪ In other words it specifies the model class property name mapped to the field
▪ Here deptno is a property under the class Department

Enter Department No: <sp:input path="deptno" />

Sensitivity: Internal & Restricted © confidential 7


Spring MVC Application:
With Form Handling

Sensitivity: Internal & Restricted


Spring MVC Application with form data
To do List:
▪ Create a Maven Project
▪ Choose Archetype as maven-archetype-webapp
▪ Add the required dependencies to the pom.xml file
▪ Spring-core, spring-web and spring-webmvc
▪ Edit the web.xml to include dispatcher servlet
▪ Create dispatcher-servlet.xml the spring configuration file
▪ Create Department Bean to represent the model class
▪ Create index.jsp for department operations menu
▪ Create InsertDepartment.jsp for accepting department details
▪ Create result.jsp for showing the result of form data
▪ Create Department Controller for processing the requests

Sensitivity: Internal & Restricted © confidential 9


Spring MVC Application with form data
Editing the pom.xml file : Adding dependencies
<dependency>
<groupId>org.springframework</groupId>
▪ Created Maven Project called
<artifactId>spring-core</artifactId>
DepartmentApplication with Archetype <version>5.2.1.RELEASE</version>
as maven-archetype-webapp </dependency>
▪ Edit the pom.xml file with the following
<dependency>
dependencies
<groupId>org.springframework</groupId>
▪ spring-core <artifactId>spring-web</artifactId>
▪ spring-web and <version>5.2.1.RELEASE</version>
▪ spring-webmvc </dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>

Sensitivity: Internal & Restricted © confidential 10


Spring MVC Application with form data
Editing the web.xml file : Adding dispatcher Servlet

▪ Configure DispatcherServlet in web.xml and establish URL mappings


▪ Edit Web.xml file to include the below script

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Sensitivity: Internal & Restricted © confidential 11


Spring MVC Application with form data
Create Spring Configuration File

▪ Next create the Spring configuration metadata in a configuration file


▪ The file name would be dispatcher-servlet.xml Just as the previous demo
▪ we have to add the component-scan element and view resolver

<context:component-scan base-package="com.wipro" />

<!-- Including the bean for View Resolver -->


<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

Sensitivity: Internal & Restricted © confidential 12


Spring MVC Application with form data
Create Department class

▪ Department class is an entity class package com.wipro.bean;


to represent the data
▪ Create the class under the package public class Department {
com.wipro.bean private int deptno;
private String dname;
private String loc;
public Department() {
}
public Department(int deptno, String dname, String loc) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
}
//Required getters and setters are added

Sensitivity: Internal & Restricted © confidential 13


Spring MVC Application with form data
▪ Add the following code in Index.jsp to request for a inserting operation
<a href="PreInsertDepartment">Insert Department</a>

▪ Create a jsp page called InsertDepartment.jsp under WEB-INF/views


▪ Add the spring forms tag library
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sp" %>

▪ Create the form for Entering department data


<sp:form action="InsertDepartment" method="post" modelAttribute="department">
Enter Department No: <sp:input path="deptno" />
Enter Department Name : <sp:input path="dname"/>
Enter Department Location : <sp:input path="loc" />
<input type="submit"/>
</sp:form>

▪ Note: modelAttribute “department” is the representation of Department Object


▪ path attribute values (deptno,dname,loc) are properties of Department class
Sensitivity: Internal & Restricted © confidential 14
Spring MVC Application with form data
▪ Let us create the DepartmentController class under the package com.wipro.controller
▪ It handles the PreInsertDepartment request and InsertDepartment request
▪ PreInsertDepartment request from the index Page Creates a new Department Class
Object
▪ Adds default department no value and returns back along with the InsertDepartment view

@Controller
public class DepartmentController {

@RequestMapping("PreInsertDepartment")
public ModelAndView preInsert() {
Department department = new Department();
department.setDeptno(30); //sets the initial value as 30
ModelAndView mv = new ModelAndView("InsertDepartment","department",department);
return mv;
}

This is referred as modelAttribute in the form tag

Sensitivity: Internal & Restricted © confidential 15


Spring MVC Application with form data
▪ Executing with Just One request handling implemented in the controller
▪ clicking on the hyperlink of index.jsp we get the IndertDepartment Page loaded

Sensitivity: Internal & Restricted © confidential 16


Spring MVC Application with form data
▪ On click of submit on IndertDepartment.jsp Page InsertDepartment request is raised
▪ Controller is edited to handle the new request
@RequestMapping("InsertDepartment")
public ModelAndView insertDepartment(@ModelAttribute("department") Department dept) {

ModelAndView mv = new ModelAndView("result","department",dept);


return mv;
}

Entered form data is now sent to the controller through


the model Attribute and is available as the dept object
▪ Now the entered data is displayed on the new result.jsp Page

Sensitivity: Internal & Restricted © confidential 17


Spring MVC Application with form data
▪ Create result.jsp Page and add the following content
▪ Using Expression Language the department object details are displayed
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<pre>
Department [ ${department.deptno } , ${department.dname } , ${department.loc } ]
</pre>
</body>
</html>

Sensitivity: Internal & Restricted © confidential 18


Spring MVC Application with form data
▪ On final execution we get

result.jsp

Sensitivity: Internal & Restricted © confidential 19


Spring – Hibernate
Application

Sensitivity: Internal & Restricted


Spring And Hibernate
▪ Now Let us elevate our DepartmentApplication to persist the Department data
▪ Spring supports multiple ways to persist the data, like
▪ Spring with JDBC
▪ Spring Data
▪ Spring ORM
▪ In our session we will use Spring ORM
▪ Spring has various APIs to support easy integration with any framework
▪ Thus Spring framework supports integration with Hibernate, Java Persistence API
(JPA) and Java Data Objects (JDO) for Data Persistance and Management
▪ All Hibernate configuration details could be provided in Spring Configuration file
▪ With Spring IOC required objects are Autowired and there is no need to create objects of
configuration to get SessionFactory object

Sensitivity: Internal & Restricted © confidential 21


Spring – Hibernate Application

▪ To the previously created Application now let us add the Hibernate Requirements
1. Edit pom.xml file to add hibernate dependencies
2. Edit Spring Configuration file to add Hibernate configurations
3. Edit the Department Class to include Hibernate Annotations to mark the mappings
4. Create DeaprtmentDao class for Data Access Layer
5. Edit the Controller to use the Dao in order to insert the Department data to the
database

Sensitivity: Internal & Restricted © confidential 22


Spring – Hibernate Application
1. Edit pom.xml file to add hibernate dependencies

<dependency>
<dependency>
<groupId>org.hibernate</groupId>
<groupId>org.springframework</groupId>
<artifactId>hibernate-core</artifactId>
<artifactId>spring-tx</artifactId>
<version>5.4.9.Final</version>
<version>5.2.6.RELEASE</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>org.springframework</groupId>
<groupId>commons-dbcp</groupId>
<artifactId>spring-orm</artifactId>
<artifactId>commons-dbcp</artifactId>
<version>5.2.1.RELEASE</version>
<version>1.2.2</version>
</dependency>
</dependency>

Sensitivity: Internal & Restricted © confidential 23


Spring – Hibernate Application
1. Edit pom.xml file to add hibernate dependencies
• In continuation we are going to add the oracle dependency for ojdbc6.jar
• For this we need to explicitly install the jar from local directory to maven repository by
issuing the below given command
mvn install:install-file -Dfile=D:/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6
-Dversion=11.1.0 -Dpackaging=jar

• –Dfile denotes the location of the ojdbc6.jar


• –DgroupId denotes groupId of the dependency
• –DartifactId = artifact Id of the dependency
• –Dversion = artifact version
<dependency>
• Include this dependency also to the pom.xml <groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.1.0</version>
</dependency>

Sensitivity: Internal & Restricted © confidential 24


Spring – Hibernate Application
2. Edit Spring Configuration file to add Hibernate configurations
• Add <context:annotation-config/> to activate dependency injection annotations like
• @Autowired and @Quallifier
• Add bean definition for DataSource where we configure the connection details like
• Driver class
• url, username and password

<context:annotation-config />

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />


<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="username" value="scott" />
<property name="password" value="tiger" />
</bean>

Sensitivity: Internal & Restricted © confidential 25


Spring – Hibernate Application
2. Edit Spring Configuration file to add Hibernate configurations in continuation
• Add bean definition for SessionFactory where we configure the session factory details
like
• dataSource which is mapped to the dataSource bean created earlier
• hibernateProperties which provides hibernate property information on
• dialect, hbm2ddl etc.
• packagesToScan which is used to map the package where entity beans can be found
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan" value="com.wipro.bean" />
/*This is one style used in sessionFactory bean */
</bean>
Sensitivity: Internal & Restricted © confidential 26
Spring – Hibernate Application
2. Edit Spring Configuration file to add Hibernate configurations continuation
• Adding Hibernate mapping to the configuration can be done using
• <property name="mappingResources"> by adding the list of hbm.xml files
• <mapping class=“Annotated class”> used for mapping annotated class
• <property name="packagesToScan" > used for mapping the annotated classes path

• <tx:annotation-driven/> to indicate that dependencies are Annotated


• HibernateTransacionManager is an implementation for Single Hibernate Session
Factory
• With this just @Transactional at class level is enough and we don’t have to explicitly
create beginTransaction , commit or rollback
<tx:annotation-driven />

<bean id="transactionManager“
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

Sensitivity: Internal & Restricted © confidential 27


Spring – Hibernate Application
2. Edit Spring Configuration file to add Hibernate configurations continuation
• HibernateTemplate is a helper class
• It gives simplified Hibernate Data Access Code
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
• With HibernateTemplate in Spring Framework code for inserting a record of Department
class looks like this

@Autowired
HibernateTemplate hibernateTemplate;
public boolean insertDepatment(Department department) {

hibernateTemplate.persist(department);

return true;
}

Sensitivity: Internal & Restricted © confidential 28


Spring – Hibernate Application
package com.wipro.bean;
3. Edit the Department Class to
include Hibernate Annotations to import javax.persistence.*;
mark the mappings
@Entity
• Include the required getters
@Table(name="MYDept")
and setters public class Department {
@Id
private int deptno;
@Column(length = 10)
private String dname;
@Column(length = 10)
private String loc;
public Department() {
}
public Department(int deptno, String dname, String loc) {
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
}

Sensitivity: Internal & Restricted © confidential 29


Spring – Hibernate Application
4. Create DeaprtmentDao class for Data Access Layer
package com.wipro.dao;

import java.util.List;
import javax.transaction.Transactional;

import org.hibernate.*; @Repository tells that the class is


import org.springframework.beans.factory.annotation.Autowired; a DAO class
import org.springframework.stereotype.Repository;
import com.wipro.bean.Department; @Transactional tells hibernate
transactions has to be managed
@Repository
@Transactional
public class DepartmentDao { @Autowired provides requested
@Autowired object injections
SessionFactory sessionFactory;
@Autowired
HibernateTemplate hibernateTemplate;

Sensitivity: Internal & Restricted © confidential 30


Spring – Hibernate Application
4. Create DeaprtmentDao class for Data Access Layer
public int getDepartmentId() {
int id=0;
Session session = sessionFactory.openSession();
Query<Department> qry = session.createQuery("Select max(d.deptno) from Department d");
List l=qry.list();
if(l!=null && l.size()>0) {
Object b=l.get(0);
if(b!=null)
id=(Integer) b;
}
session.close();
return id+10;
}

public boolean insertDepatment(Department department) {


hibernateTemplate.persist(department);
return true;
}
}

Sensitivity: Internal & Restricted © confidential 31


Spring – Hibernate Application

5. Edit the Controller to use the Dao in order to insert the Department data to the database

@Controller
public class DepartmentController {
@RequestMapping("InsertDepartment")
@Autowired public ModelAndView
DepartmentDao dao; insertDepartment(@ModelAttribute("department")
Department dept) {
@RequestMapping("PreInsertDepartment")
public ModelAndView preInsert() { ModelAndView mv = new
Department department = new Department(); ModelAndView("result","department",dept);
department.setDeptno(dao.getDepartmentId()); if(dao.insertDepatment(dept))
ModelAndView mv = new mv.addObject("msg", "Inserted Successfully");
ModelAndView("InsertDepartment","department", else
department); mv.addObject("msg", "Insert Failed");
return mv; return mv;
} }

}//Class closing

Sensitivity: Internal & Restricted © confidential 32


Spring – Hibernate Application
6. Execution Result
1. DB before Execution 2. Index Page

3. Insert Page

Sensitivity: Internal & Restricted © confidential 33


Spring – Hibernate Application
6. Execution Result
4. Insert Page Filled

6. DB after execution

5. Result Page

Sensitivity: Internal & Restricted © confidential 34


Summary
• In this module, we have learnt :

▪ Spring Form Tags and its uses


▪ Form tags mapping to Entity class
▪ Spring and Hibernate mapping

Sensitivity: Internal & Restricted © confidential 35


Thank you

Sensitivity: Internal & Restricted


Spring MVC with Forms

1. Create Maven Project and choose use default workspace location


a. Click Next

2. Under Archetype choose maven-archetype-webapp from below given group Id and version
a. Group Id : org.apache.maven.archetypes
b. Version can be any latest version. Here It is taken 1.4
i. You can also pick a specific version by checking the Include snapshot archetypes
c. Click Next

Sensitivity: Internal & Restricted


3. Fill the Maven Project details
a. Group ID :: com.wipro
b. Artifact ID :: DepartmentApp
c. Click finish

4. This generates Spring Web Project. With the initial Error


a. This is because the build path is not aware of servlets and jsp APIs.
b. Add Tomcat server
i. Click on window menu -> preferences -> server -> Runtime Environment
1. Search the unzipped folder of your Apache Tomcat
c. right click on project -> Properties -> Java Build Path -> Add Library
d. Server Runtime -> Apache Tomcat -> Finish

Sensitivity: Internal & Restricted


5. Set the spring dependencies.
a. Open POM file
b. Add the following spring dependencies under the tag <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>

6. Set the dispatcher Servlet.


a. Edit the web.xml file from project path : src->main->webapp->WEB-INF->web.xml
b. Include <servlet> and <servlet-mapping>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Sensitivity: Internal & Restricted


7. Create the Spring configuration file names 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"
xmlns:context="http://www.springframework.org/schema/context"
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="com.wipro" />

<!-- Including the bean for View Resolver -->


<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>

8. Create the views folder under WEB-INF for defining the views
a. Right click on WEB-INF folder NEW -> Folder (Enter Name as views ) - > finish.

Sensitivity: Internal & Restricted


9. Create a class called Department under the package com.wipro.bean
package com.wipro.bean;

public class Department {

private int deptno;


private String dname;
private String loc;
public Department() {

}
public Department(int deptno, String dname, String loc) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {

Sensitivity: Internal & Restricted


return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Department [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc +
"]";
}
}

10. Edit the Index.jsp page to request for a inserting operation for Department

<html>
<body>
<h2>Hello World!</h2>
<a href="PreInsertDepartment">Insert Department</a>
</body>
</html>

11. Create the controller class named DepartmentController


a. Right click on Java Resources and create a package called com.wipro.controller
b. Under the package Create a class called DepartmentController

package com.wipro.controller;

import org.springframework.stereotype.Controller;

Sensitivity: Internal & Restricted


import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wipro.bean.Department;

@Controller
public class DepartmentController {

@RequestMapping("PreInsertDepartment")
public ModelAndView preInsert() {
Department department = new Department();
department.setDeptno(50);
ModelAndView mv = new
ModelAndView("InsertDepartment","department",department);
return mv;
}

@RequestMapping("InsertDepartment")
public ModelAndView insertDepartment(@ModelAttribute("department") Department
dept) {

ModelAndView mv = new ModelAndView("result","department",dept);


return mv;
}

12. Create a new jsp page under WEB-INF -> views called InsertDepartment.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body><pre>
<sp:form action="InsertDepartment" method="post" modelAttribute="department">
Enter Department No: <sp:input path="deptno" />
Enter Department Name : <sp:input path="dname"/>
Enter Department Location : <sp:input path="loc" />
<input type="submit"/>
</sp:form>
</pre>
</body>
</html>

Sensitivity: Internal & Restricted


Create a new jsp page under WEB-INF -> views called result.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<pre>
${msg}
Department [ ${department.deptno } , ${department.dname } , ${department.loc } ]

</pre>
</body>
</html>

Sensitivity: Internal & Restricted


13. Run the Application from index.jsp

Sensitivity: Internal & Restricted


Spring MVC with Hibernate

1. Create Maven Project and choose use default workspace location


a. Click Next

2. Under Archetype choose maven-archetype-webapp from below given group Id and version
a. Group Id : org.apache.maven.archetypes
b. Version can be any latest version. Here It is taken 1.4
i. You can also pick a specific version by checking the Include snapshot archetypes
c. Click Next

Sensitivity: Internal & Restricted


3. Fill the Maven Project details
a. Group ID :: com.wipro
b. Artifact ID :: DepartmentApplication
c. Click finish

4. This generates Spring Web Project. With the initial Error


a. This is because the build path is not aware of servlets and jsp APIs.
b. Add Tomcat server
i. Click on window menu -> preferences -> server -> Runtime Environment
1. Search the unzipped folder of your version of Appache Tomcat
c. right click on project -> Properties -> Java Build Path -> Add Library
d. Server Runtime -> Apache Tomcat -> Finish

Sensitivity: Internal & Restricted


5. Set the spring and Hibernate dependencies.
a. Open POM file
b. Add the following spring dependencies under the tag <dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<!-- dependencies required for Hibernate ORM Integration -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.9.Final</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>

<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>

Sensitivity: Internal & Restricted


6. Set the dispatcher Servlet.
a. Edit the web.xml file from project path : src->main->webapp->WEB-INF->web.xml
b. Include <servlet> and <servlet-mapping>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

7. Create the Spring configuration file named 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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">

<context:component-scan base-package="com.wipro" />


<context:annotation-config />
<!-- Including the bean for View Resolver -->
<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>

Sensitivity: Internal & Restricted


</property>
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:orcl" />
<property name="username" value="scott" />
<property name="password" value="tiger" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="packagesToScan" value="com.wipro.bean" />

</bean>
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<tx:annotation-driven />

<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

</beans>

Sensitivity: Internal & Restricted


8. Create the views folder under WEB-INF for defining the views
a. Right click on WEB-INF folder NEW -> Folder (Enter Name as views ) - > finish.

9. Create the entity bean class called Department under the package com.wipro.bean
package com.wipro.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity

Sensitivity: Internal & Restricted


@Table(name="MYDept")
public class Department {
@Id
private int deptno;
@Column(length = 10)
private String dname;
@Column(length = 10)
private String loc;
public Department() {

}
public Department(int deptno, String dname, String loc) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Department [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc +
"]";
}
}

Sensitivity: Internal & Restricted


10. Edit the Index.jsp page to request for inserting operation for Department

<html>
<body>
<h2>Department Actions</h2>
<pre>
<a href="PreInsertDepartment">Insert Department</a>
</pre>
</body>
</html>

11. Create the DataAccess Layer called DepartmentDao under com.wipro.dao


package com.wipro.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.wipro.bean.Department;

@Repository
@Transactional
public class DepartmentDao {
@Autowired
SessionFactory sessionFactory;

@Autowired
HibernateTemplate hibernateTemplate;

public int getDepartmentId() {


int id=0;
Session session = sessionFactory.openSession();
Query<Department> qry = session.createQuery("Select max(d.deptno) from
Department d");
List l=qry.list();
System.out.println("L value"+l + " : " );
if(l!=null && l.size()>0) {
Object b=l.get(0);
if(b!=null)

Sensitivity: Internal & Restricted


id=(Integer) b;
}
session.close();
return id+10;
}
public boolean insertDepatment(Department department) {
hibernateTemplate.persist(department);
return true;
}
}

12. Create the controller class named DepartmentController under the package called
com.wipro.controller

package com.wipro.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wipro.bean.Department;
import com.wipro.dao.DepartmentDao;

@Controller
public class DepartmentController {

@Autowired
DepartmentDao dao;

@RequestMapping("PreInsertDepartment")
public ModelAndView preInsert() {
Department department = new Department();
department.setDeptno(dao.getDepartmentId());
ModelAndView mv = new
ModelAndView("InsertDepartment","department",department);
return mv;
}

@RequestMapping("InsertDepartment")
public ModelAndView insertDepartment(@ModelAttribute("department") Department dept) {

ModelAndView mv = new ModelAndView("result","department",dept);


if(dao.insertDepatment(dept))

Sensitivity: Internal & Restricted


mv.addObject("msg", "Inserted Successfully");
else
mv.addObject("msg", "Insert Failed");
return mv;
}
}

13. Create a new jsp page under WEB-INF -> views called InsertDepartment.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body><pre>
<sp:form action="InsertDepartment" method="post" modelAttribute="department">
Enter Department No: <sp:input path="deptno" />
Enter Department Name : <sp:input path="dname"/>
Enter Department Location : <sp:input path="loc" />
<input type="submit"/>
</sp:form>
</pre>
</body>
</html>

14. Create a new jsp page under WEB-INF -> views called result.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<pre>
${msg}
Department [ ${department.deptno } , ${department.dname } , ${department.loc } ]

</pre>
</body>
</html>

Sensitivity: Internal & Restricted


15. Run the Application from index.jsp file

Sensitivity: Internal & Restricted


16. Now connect to the database and check for the table creation and inserti

Sensitivity: Internal & Restricted

You might also like