Professional Documents
Culture Documents
19 Spring
1 What is Spring?
2 Why Spring?
3 Spring Architecture
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
Easy to unit
Spring MVC
test
Spring
features
Dependency Consistent
Injection(DI) framework for
or IOC data access
Less or
almost zero
coupling
▪ Spring as Framework
▪ Features of Spring
▪ Architecture of Spring
1 Spring Core
▪ 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
▪ 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
▪ Let us take a Simple HelloWorld Application; here our base requirement is to display the
content contained by the data field msg
▪ Spring removes this overhead; It creates and delivers the Objects to the related class
▪ 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
▪ 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();
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");
}
}
<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
9. Create the UserMain class in the same com.wipro.sample package and run the same.
2 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.
</beans>
<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>
On to the same application above Let us change the beans.xml and UserMain to see difference
in Constructor based DI.
Autowiring
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;
</bean>
</beans>
</bean>
▪ 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)
▪ 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
▪ 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
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
</beans>
▪ 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
▪ 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
@Controller
public class HelloController {
@RequestMapping("/Hello")
public String helloMethod() {
return "HelloPage";
}
}
▪ 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>
@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
▪ 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
▪ 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
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
<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>
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
@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;
}
}
<html>
<body>
<h2>Hello World!</h2>
<a href="Hello">Click here </a>
</body>
</html>
<!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>
▪ Here department is the Model object to / from which the form field values are mapped
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
▪ 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
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<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>
@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;
}
result.jsp
▪ 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
<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>
<context:annotation-config />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<bean id="transactionManager“
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
@Autowired
HibernateTemplate hibernateTemplate;
public boolean insertDepatment(Department department) {
hibernateTemplate.persist(department);
return true;
}
import java.util.List;
import javax.transaction.Transactional;
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
3. Insert Page
6. DB after execution
5. Result Page
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
<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>
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.
}
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() {
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>
package com.wipro.controller;
import org.springframework.stereotype.Controller;
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) {
12. Create a new jsp page under WEB-INF -> views called InsertDepartment.jsp
</pre>
</body>
</html>
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
<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>
<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>
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
<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>
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
}
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 +
"]";
}
}
<html>
<body>
<h2>Department Actions</h2>
<pre>
<a href="PreInsertDepartment">Insert Department</a>
</pre>
</body>
</html>
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;
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) {
13. Create a new jsp page under WEB-INF -> views called InsertDepartment.jsp
14. Create a new jsp page under WEB-INF -> views called result.jsp
</pre>
</body>
</html>