Spring in webtech
Spring in webtech
UNIT-5
ADVANCE JAVA
TOPICS COVERED
• Spring enables you to build applications from “plain old Java objects” (POJOs) and to
apply enterprise services non-invasively to POJOs.
• This capability applies to the Java SE programming model and to full and partial Java EE.
• Spring allows developers to create high-quality applications using POJOs. Using POJOs
exclusively has the advantage of not requiring an EJB container like an app server,
allowing for the use of a resilient servlet container like Tomcat or a different commercial
option.
• Spring is structured in a modular way. Despite the large quantity of packages and classes,
you only need to focus on the ones you require and disregard the others.
• Spring leverages existing technologies such as ORM frameworks, logging frameworks,
JEE, Quartz and JDK timers, and other view technologies rather than creating new ones.
• It is easy to test an application developed in Spring since any code specific to the
environment is placed within the framework. Additionally, employing JavaBeanstyle
POJOs makes it simpler to utilize dependency injection for inserting test data.
BENEFITS OF SPRING
• Spring's web framework is a well-structured web MVC framework that offers a strong
alternative to web frameworks like Struts or other complex or less popular options.
• Spring offers a user-friendly interface for converting technology-specific exceptions (such
as those raised by JDBC, Hibernate, or JDO) into uniform, unchecked exceptions.
• Small IoC containers are typically lighter than EJB containers, especially in comparison.
This is advantageous for developing and deploying applications on computers with
restricted memory and CPU resources.
• Spring offers a transaction management interface that is versatile enough to handle both
small-scale transactions with a single database and large-scale transactions with JTA.
DEPENDENCY INJECTION (DI)
• The technology that Spring is most identified with is the Dependency Injection
(DI) flavour of Inversion of Control.
• The Inversion of Control (IoC) is a general concept, and it can be expressed in many
different ways.
• Dependency Injection is merely one concrete example of Inversion of Control.
• When writing a complex Java application, application classes should be as independent as
possible of other Java classes to increase the possibility to reuse these classes and to test
them independently of other classes while unit testing.
• Dependency Injection helps in gluing these classes together and at the same time keeping
them independent.
DEPENDENCY INJECTION (DI)
• The Core Container consists of the Core, Beans, Context, and Expression Language modules:
• The Core module provides the fundamental parts of the framework, including the IoC and
Dependency Injection features.
• The Bean module provides BeanFactory, which is a sophisticated implementation of the
factory pattern.
• The Context module expands on the strong foundation of the Core and Beans modules, serving as a
gateway to interact with any defined and configured objects. The ApplicationContext interface is the
central focus of the Context module.
• The SpEL module offers a robust expression language for dynamic querying and manipulation of an
object graph.
MODULE: DATA ACCESS/INTEGRATION
• The Data Access/Integration layer is comprised of the JDBC, ORM, OXM, JMS, and Transaction
modules, with the following explanation for each one.
• The JDBC module offers a JDBC-abstraction layer that eliminates the necessity for laborious JDBC
coding.
• The ORM module offers connectivity layers for commonly used object-relational mapping APIs
such as JPA, JDO, Hibernate, and iBatis.
• The OXM module offers a layer of abstraction that backs Object/XML mapping implementations
such as JAXB, Castor, XMLBeans, JiBX, and XStream.
• The JMS module in Java Messaging Service includes functionalities for creating and receiving
messages.
• The Transaction module offers both programmatic and declarative transaction management for
classes with special interfaces and for all POJOs.
MODULE: WEB
• The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules
which are as follows −
• The Web module provides basic web-oriented integration features such as multipart file-
upload functionality and the initialization of the IoC container using servlet listeners and a
web-oriented application context.
• The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
• The Web-Socket module provides support for WebSocket-based, two-way
communication between the client and the server in web applications.
• The Web-Portlet module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.
MODULE: MISCELLANEOUS
• There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules
which are as follows −
• The AOP module provides an aspect-oriented programming implementation allowing you to
define method-interceptors and pointcuts to cleanly decouple code that implements functionality
that should be separated.
• The Aspects module provides integration with AspectJ, which is again a powerful and mature AOP
framework.
• The Instrumentation module provides class instrumentation support and class loader
implementations to be used in certain application servers.
• The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in
applications. It also supports an annotation programming model for routing and processing
STOMP messages from WebSocket clients.
• The Test module supports the testing of Spring components with JUnit or TestNG frameworks.
SPRING JDBC FRAMEWORK
• Spring JDBC Framework manages all the low-level aspects, including opening the
connection, preparing and executing SQL statements, handling exceptions, managing
transactions, and ultimately closing the connection.
• Spring JDBC offers multiple methods and various classes to connect with the database.
• This is the primary framework class that oversees all database interactions and exception
management.
JDBCTEMPLATE CLASS
• The JDBC Template class executes SQL queries, updates statements, stores procedure
calls, performs iteration over ResultSets, and extracts returned parameter values.
• It also catches JDBC exceptions and translates them to the generic, more informative,
exception hierarchy defined in the org.springframework.dao package.
• Instances of the JdbcTemplate class are threadsafe once configured. So you can
configure a single instance of a JdbcTemplate and then safely inject this shared
reference into multiple DAOs.
• A common practice when using the JDBC Template class is to configure a DataSource
in your Spring configuration file, and then dependency-inject that shared DataSource
bean into your DAO classes, and the JdbcTemplate is created in the setter for the
DataSource.
CONFIGURING DATA SOURCE
• Now we need to supply a DataSource to the JDBC Template so it can configure itself to get
database access.
• You can configure the DataSource in the XML file with a piece of code as shown in the
following code snippet
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "password"/>
</bean>
DATA ACCESS OBJECT (DAO)
• DAO stands for Data Access Object, which is commonly used for database interaction.
• DAOs exist to provide a means to read and write data to the database and they
should expose this functionality through an interface by which the rest of the
application will access them.
• The DAO support in Spring makes it easy to work with data access technologies like
JDBC, Hibernate, JPA, or JDO in a consistent way.
EXECUTING SQL STATEMENTS
return student;
} }
QUERIES WITH OBJECTS
• Interface Declaration
• Following is the declaration for
org.springframework.jdbc.core.PreparedStatementSetter interface −
• public interface PreparedStatementSetter
• Usage
• Step 1 − Create a JdbcTemplate object using a configured datasource.
• Step 2 − Use JdbcTemplate object methods to make database operations while
passing PreparedStatementSetter object to replace place holders in query.
PREPARED STATEMENT--SYNTAX
• Interface Declaration
• Following is the declaration for
org.springframework.jdbc.core.ResultSetExtractor interface −
• public interface ResultSetExtractor
• Usage
• Step 1 − Create a JdbcTemplate object using a configured datasource.
• Step 2 − Use JdbcTemplate object methods to make database operations while
parsing the resultset using ResultSetExtractor.
SPRING JDBC - RESULTSETEXTRACTOR INTERFACE
• Syntax
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL, new
StudentMapper());
• Where
• SQL − Read query to read all student records.
• jdbcTemplateObject − StudentJDBCTemplate object to read student records from
database.
• StudentMapper − StudentMapper object to map student records to student objects.
SPRING JDBC - NAMEDPARAMETERJDBCTEMPLATE
CLASS
• A Spring MVC is a Java framework which is used to build web applications. It follows
the Model-View-Controller design pattern.
• It implements all the basic features of a core spring framework like Inversion of
Control, Dependency Injection.
• A Spring MVC provides an elegant solution to use MVC in spring framework by the
help of DispatcherServlet.
• Here, DispatcherServlet is a class that receives the incoming request and maps it to
the right resource such as controllers, models, and views.
SPRING MVC
SPRING MVC
• Model - A model contains the data of the application. A data can be a single object or
a collection of objects.
• Controller - A controller contains the business logic of an application. Here, the
@Controller annotation is used to mark the class as the controller.
• View - A view represents the provided information in a particular format. Generally,
JSP+JSTL is used to create a view page. Although spring also supports other view
technologies such as Apache Velocity, Thymeleaf and FreeMarker.
• Front Controller - In Spring Web MVC, the Dispatcher Servlet class works as the
front controller. It is responsible to manage the flow of the Spring MVC application.
UNDERSTANDING THE FLOW OF SPRING WEB MVC
UNDERSTANDING THE FLOW OF SPRING WEB MVC
• All incoming requests are captured by the DispatcherServlet, which serves as the
main controller, as shown in the diagram.
• The DispatcherServlet retrieves a handler mapping entry from the XML file and then
directs the request to the controller.
• The Model And View object is returned by the controller.
• The DispatcherServlet verifies the presence of a view resolver entry in the XML file
and calls the designated view component.
ADVANTAGES OF SPRING MVC FRAMEWORK
• Separate roles -The Spring MVC divides each function, with specialized objects like
model object, controller, command object, view resolver, DispatcherServlet, validator,
etc. fulfilling each role.
• Lightweight - It utilizes a light-weight servlet container for building and deploying
your application.
• Powerful configuration-It offers a solid configuration for framework and
application classes with seamless referencing between contexts, like from web
controllers to business objects and validators.
• Rapid development-Spring MVC allows for rapid development in a parallel manner.
ADVANTAGES OF SPRING MVC FRAMEWORK
• Reusable business code- refers to the practice of utilizing the already existing
business objects rather than creating new ones.
• Easy to test - Typically in Spring, we generate JavaBeans classes that allow you to
provide test data through the setter methods.
• Flexible Mapping-It offers precise annotations for seamlessly redirecting the page.
SPRING WEB MVC FRAMEWORK EXAMPLE
• Load the spring jar files or add dependencies in the case of Maven
• Create the controller class
• Provide the entry of controller in the web.xml file
• Define the bean in the separate XML file
• Display the message in the JSP page
• Start the server and deploy the project
REQUIRED JAR FILES OR MAVEN DEPENDENCY
package com.welcome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/")
public String display()
{
return "index";
} }
3. Provide the entry of controller in the web.xml file
• In this xml file, we are specifying the servlet class DispatcherServlet that acts as the front
controller in Spring Web MVC. All the incoming request for the html file will be forwarded to
the DispatcherServlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.c
om/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4. DEFINE THE BEAN IN THE XML FILE
SPRING-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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
4. DEFINE THE BEAN IN THE XML FILE
SPRING-SERVLET.XML
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.welcome" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
</beans>
5. DISPLAY THE MESSAGE IN THE JSP PAGE
• Index.jsp
<html>
<body>
<p>Welcome to Spring MVC </p>
</body>
</html>