0% found this document useful (0 votes)
8 views

FSD-4.2-Spring-notes (2)

The document provides an overview of the Spring Framework, detailing its architecture, features, and advantages for developing enterprise-level applications. It covers key concepts such as Inversion of Control (IoC), Dependency Injection (DI), Spring MVC, and various modules within the framework, including data access and web functionalities. Additionally, it explains the roles of DispatcherServlet, interceptors, view resolution, and form handling in Spring MVC applications.

Uploaded by

Shreya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

FSD-4.2-Spring-notes (2)

The document provides an overview of the Spring Framework, detailing its architecture, features, and advantages for developing enterprise-level applications. It covers key concepts such as Inversion of Control (IoC), Dependency Injection (DI), Spring MVC, and various modules within the framework, including data access and web functionalities. Additionally, it explains the roles of DispatcherServlet, interceptors, view resolution, and form handling in Spring MVC applications.

Uploaded by

Shreya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT-IV

CHAPTER -2
Spring Framework
CONTENTS

1. Introduction
2. Architecture
3. MVC
4. Interception
5. View Resolution
6. Model Interface
7. RequestParam
8. Form Tag s
9. CRUD Example
10.File Upload
11.Validations
12.References
1. Introduction

 Spring is a lightweight and popular open-source Java-based framework developed by


Rod Johnson in 2003.
 It is used to develop enterprise-level applications.
 It is also called framework of frameworks as it supports many other frameworks such as
Hibernate, EJB, JSF, Struts etc.
 The Spring framework comprises several modules such as IOC, AOP, DAO, Context,
ORM, WEB MVC etc
 By offering a POJO-based programming model, the Spring framework aims to make
J2EE development easier to use and to promote good programming habits.
Features of Spring:
 IOC Container
 Data Access framework
 Spring MVC Framework
 Transaction management
 Spring WebService
 JDBC abstraction layer
 Spring TestContext framework
Advantages of Spring:
 POJO Based
 Modular
 Integration with existing frameworks
 Testability
 Web MVC
 Central Exception Handling
 Lightweight
Inversion of Control:
 It promotes loose coupling as the control remains with the framework which executes the
logic code.
 It offers flexibility to modify the implementation of these objects without affecting the
other parts of the application.
 IOC can be achieved with the help of Dependency Injection (DI).
Dependency Injection:
 Dependency Injection is a structural design pattern that eliminates the need to initialize
the objects.
 It injects the required object to the constructor or setter by passing as a parameter.
 The Dependency Injection is implemented in a library called Inversion of Control (IOC)
container.
 The IOC container is responsible for injecting the dependent objects when the bean
creation is taken place.

 IOC is mainly responsible for instantiating, configuring, assembling objects and


managing their life cycles. These objects are called beans.
 Spring provides ApplicationContext interface to implement DI mechanism.
 This interface is a subinterface of BeanFactory interface which provides advanced
configuration method to manage all types of objects.
 ApplicationContext has several implementations for various purposes
o FileSystemXmlApplicationContext – to load XML configuration from a path or
from URL specified for a standalone applications
o XMLWebApplicationContext – to load XML configuration from a file for Web
applications
o ClassPathXmlApplicationContext - to load configuration from a context
definition file for standalone applications
Ex: ApplicationContext appContext = new
ClassPathXmlApplicationContext(“context.xml”);
Bean Scope:
 Spring provides a mechanism to have more granular control on the creation process by
specifying the bean scope.
 The Spring framework provides five scopes.
o singleton: The framework first looks for a cached instance of the bean and if it
cannot find one, it creates a new one.
o prototype: The framework will create a new bean instance on every request. In
order to use the other three scopes listed below, you need to use a web-aware
ApplicationContenxt.
o request: This is similar to the prototype scope but only for web applications,
where a new instance is created on every HTTP request.
o session: As the name suggests, this scope is limited to every HTTP session. A
new instance is available per session.
o global-session: This scope is useful for portlet applications where a new instance
is created for every global session.

Ex: <bean id=“book” class=“com.beans.Book” scope=“request” >


<constructor-arg type=“java.lang.String” value=“Complete Reference”/>
</bean>

Autowiring Dependencies:

Spring container uses autowiring to automatically resolve dependencies. There are four modes
by which we can autowire a bean in XML configuration.
o Default mode: In this mode, no autowiring is used and we have to manually
define the dependencies.
o ByName mode: In this mode, the autowiring is done using the name of the
property. This name is used by Spring to look for a bean to inject.
o ByType mode: In this mode, the type of the property is used by Spring to look for
a bean. If more than one beans are found, Spring throws an exception.
o Constructor mode: In this mode, constructor of the class is used to autowire the
dependencies. Spring will look for beans defined in the constructor arguments.

Variants of Dependency Injection:


1. Constructor-Based Dependency Injection –
a. Required dependencies are injected as constructor-arguments
b. The order in which the parameters are supplied will be used to instantiate the
bean
c. Attributes – index, type, ref should match id of the bean, name should match
the field
Ex: <bean id="student" class="com.beans.Student">
<constructor-arg index="0" value="101"/>
<constructor-arg type="java.lang.String" value="Seetha"/>
<constructor-arg ref="address"/>
</bean>
2. Setter-Based Dependency Injection
a. Once the bean is instantiated, the container uses the setter methods to inject
the dependencies
b. Attributes – name should match with field, ref should match id of the bean,
value
Ex: <bean id="address" class="com.beans.Address">
<property name="city" value="Hyderabad"/>
</bean>
3. Field-Based Dependency Injection
a. Container injects the dependencies on fields which are annotated as
@Autowired once the class is instantiated.
Ex: public class Student{
@Autowired
private Address address;
}
Lazy Initialized Beans:
Bean is initialized on first request rather than at the application startup.

2. Spring Architecture

There are 20 modules in Spring Framework that provides various functionalities.

Core Container: Core Container acts as the base of Spring Framework which consists of Core,
Beans, Context, Expression Language (spEL) modules.

Core Module – responsible for providing fundamental features like IOC and DI.
Beans Module – provides implementation of BeanFactory which decouples the dependencies
from the actual program logic.

Context Module – Provides ApplicationContext interface that provides configuration


information to the application.

Expression Language (spEL) Module - provides a prevailing tool to query and manipulate an
object graph at runtime.

Data Access/Integration: Looks after accessing, storing, manipulating data. This layer contains
ORM, OXM, JDBC, JMS and Transaction modules.

ORM Module – Obect-Relationship Management Module. It offers a easy way to persist objects
without writing queries.

JDBC Module – Java API to interact with database to perform CRUD operations.

OXM Module – Object XML Mapping. It offers a mechanism to convert an object to XML and
vice-versa.

JMS Module – Java Message Service which offers a mechanism to create, send and read
messages in a reliable and asynchronous way.

Transaction Management Module – It offers a reliable abstraction for transaction management.

Web Container: Provides various frameworks useful for web related applications. It consists of
Web, Web-Servlet, Web-Sockets and Web-Portlet modules.

Web Module – It offers web related functionalities like multiple file uploads, integration to IOC
using a servlet and web application context.

Web-Servlet Module – It is an implementation of MVC pattern. It offers a clean separation


between domain model code and web interface.

Web-Socket Module – It provides support of web socket which is a bi-directional


communication between server and client.

Web-Portlet Module – It provides similar functionality of web-socket for implementing MVC in


portlet environment.

Other Modules:

AOP module: This module provides Aspect Oriented Programming support to Spring
Framework. AOP provides a simple mechanism to implement cross-cutting concerns.
Aspects module: This module supports integration with AspectJ.

Testing module: This module provides provision to implement integration and unit tests.

Instrumentation module: This module provides class instrument support and classloader
implementations, which are useful in various application servers.

Messaging module: This module provides foundation for messaging-based applications, which
contains a set of annotations for mapping messages to methods.

3. Spring MVC

Spring MVC is one of the most popular Java website frameworks to program website
applications. All the general Spring features such as DI and IOC are implemented by Spring
MVC.
To use the Spring framework, Spring MVC makes use of class DispatcherServlet. This class
processes an incoming request and assigns it with models, controller, views, or any of the right
resource.
In Spring MVC, any class which uses the annotation “@Controller” is the controller of
the application. For views, a combination of JSP and JSTL can be utilized. For the front
controller, the DispatcherServlet class is used in Spring MVC.
When a request arrives, it is discovered by the DispatcherServlet class. This class gets
the required information from the XML files and delivers the request to the controller.
Subsequently, the controller generates a ModelAndView object. Afterwards, the
DispatcherServlet class processes the view resolver and calls the appropriate view.
DispatcherServlet:
The DispatcherServlet is an actual servlet which needs to be defined in web.xml and map the
requests that needs to be handled by DispatcherServlet by using URL mapping.
Ex:
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>

In the above example, requests ending with .jsp will be handled by HelloWeb DispatcherServlet.
Upon initialization of DispatcherServlet, framework looks for a file named servlet-name-
servlet.xml in the WEB-INF directory of the application and creates the beans defined there.
In the above example the file would be HelloWeb-servlet.xml.

For configuration purposes, the DispatcherServlet requires the WebApplicationContext.


The WebApplicationContext is an extension of the plain ApplicationContext that has some extra
features necessary for web applications. It differs from a normal ApplicationContext in that it is
capable of resolving and that it knows which servlet it is associated with by having a link to
the ServletContext. The WebApplicationContext is bound in the ServletContext, and by using
static methods on the RequestContextUtils class you can always look up
the WebApplicationContext if you need access to it.

For most of the applications, one WebApplicationContext is enough. Sometimes there


will be a context hierarchy in which a single root WebApplicationContext is used for sharing
between more than one instance of DispatcherServlet.
The Spring DispatcherServlet uses special beans which are part of Spring framework to process
requests and render the appropriate views.
1. HandlerMapping: It is used with a handler for mapping requests. It uses the HandlerMapping
implementation.
2. HandlerAdapter: It uses the DispatcherServlet for invoking handlers which are mapped with
a request.528
3. HandlerException resolver: It is used for resolving exceptions where they are mapped with
handlers and error views of the HTML.
4. View resolver: It is used to resolve the view names which rely on logical Strings.
5. Locale resolver: It is used for resolving a client’s locale or timezone.
6. Themes resolver: It is used to resolve the themes of a web application.
7. MultiplepartResolver: It is used for abstraction in order to help with parsing a request which
has multiple parts.
8. FlashMapManager: It is used for storing and retrieving the input/output FlashMap.
Spring MVC Processing:
Once a request comes in for that specific DispatcherServlet, the DispatcherServlet starts
processing the request as follows:
1. It searches the WebApplicationContext and attaches the request in the form of an attribute so
other components such as controller can use it.
2. The request is bound to the locale resolver which allows the process’ elements in resolving the
locale while processing
and preparing data, rendering the view, or other requests.
3. Requests are bound to the theme resolver which allows views and other elements to use the
theme.
4. When a multipart file resolver is defined, all the parts of the request are processed. After
multiparts are discovered, the
MultipartHttpServletRequest is wrapped to help with processing.
5. When the right handler is found, controllers, preprocessors, postprocessors, and others in the
handler’s executive chain
are executed so the model is prepared or rendered. For annotated controllers, it is possible to
render the response.
6. The view is rendered when a model is returned. When it is not returned, there is no need for
view rendering as the
request is already processed.
7. The declared beans in HandlerExceptionResolver resolve exceptions which come up in the
request processing.

4. Interception
To implement certain functionalities for specific requests, interceptors are supported by
SpringMVC HandlerMapping implementations.
Interceptor of a handler must implement org.springframework.webservlet.HandlerInterceptor
having the below methods for preprocessing and postprocessing.
1. preHandle(): It is used for the time period before the handler is executed.
2. postHandle(): It is used when the handler has been executed.
3. afterCompletion(): It is used after the request has been completed the execution.

5. View Resolution
View and ViewResolver interfaces are used by the SpringMVC to render models in a browser.
ViewResolver is used to map actual views and view names.
The View manages the preparation data before it is passed over to a certain technology for
viewing.
To configure the view resolution, add the ViewResolver beans in the configuration of
SpringMVC application.
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</bean>
Multiple view pages:
In a SpringMVC application, user can be redirected between multiple view pages. Once a view is
returned from a controller, by performing action on respective page, user can be redirected
another view and so on.
Multiple Controllers:
It is possible to generate multiple controllers in Spring MVC at the same time. A controller can
be mapped by using @Controller annotation or by adding controller bean definition in the
dispatcher servlet configuration file.
6. Model Interface
Model serves as a container which can be used to store application’s data. The data can be a
record from DB, a String or an object.
The controller must have the Model interface. The data to be send to view should be added to
Model object and the View can access that piece of data from Model’s interface.
Ex:
Define a method in controller which takes Model as an argument. Add data to the model by
using addAttribute() method.
public String show(HttpServletRequest r,Model md){
md.addAttribute(“msg”,”Hello World”);
return “hello”;
}
In hello.jsp, data added to model can be retrieved by
${msg}
7. RequestParam
To read data form a form and to bind to a controller method argument, @RequestParam
annotation is used.
It does not consider the HttpServletRequest object for reading data.
Ex:
public String display(@RequestParam(“name”) String name,@RequestParam
(“pass”) String pass,Model md)
Where name and pass within the annotation are the field names.

8. FormTags
FormTags can be reused and reconfigured according to the requirements of the user. The
FormTags library is in spring-webmvc.jar. To make use of the library’s support, below
configuration is required.
<%@ taglib prefix=“form” uri=“http://www.springframework.org/tags/form” %>
The Spring MVC form tag is a container tag. It is a parent tag that contains all the other tags of
the tag library. This tag generates an HTML form tag and exposes a binding path to the inner
tags for binding.
<form:form action=“nextFormPath” modelAttribute=?abc?>
List of SpringMVC Form tags:
1. form:form – Used to store all of the other tags.
2. form:input – Creates the text field for the user input.
3. form:radiobutton – Creates the radio button which can be marked or unmarked by the user.
4. form:checkbox – Creates the checkboxes which can be checked or unchecked by the user.
5. form:password – Creates a field for user to type password.
6. form:select – Creates a drop-down list for the user to choose an option.
7. form:textarea – Creates a field for text which spans multiple lines.
8. form:hidden – Creates an input field which is hidden.
Ex:
<form:form action=“subfrm” modelAttribute=“reservation”>
First name: <form:input path=“Fname” />
<br><br>
Last name: <form:input path=“Lname” />
<br><br>
<input type=“submit” value=“Submit” />
</form:form>

When the form is submitted the controller processes the request and the form data will be
added to model “reservation”.

public ModelAndView submitForm(@ModelAttribute(“reservation”) Reservation rsv)


{
ModelAndView mav=new ModelAndView();
mav.addObject(“reservation”,reservation);
return mav;
}

The model data can be retrieved in the next page also.


First Name : ${reservation.Fname} <br>
Last Name : ${reservation.Lname}

9. CRUD
The following steps need to be followed to connect to database through Spring.
 Add mysql-connector-j-8.3.0.jar ro the project
 Include below configuration for the database in the configuration file
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/schema1"></property>
<property name="username" value="root"></property>
<property name="password" value="mysql"></property>
</bean>

<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">


<property name="dataSource" ref="ds"></property>
</bean>
 JdbcTemplate will take care of establishing database connection, executing queries and
closing the connection.
 Create a DAO class for the database table and add JdbcTemplate as a field and inject the
bean “jt” and also add CRUD methods
<bean id="dao" class="com.dao.EmpDao">
<property name="jt" ref="jt"/>
</bean>
 In the Controller, add methods and call CRUD methods of DAO class from those
methods.
10. File Upload
In Spring MVC, we can easily incorporate the functionality to upload files in various formats.

For that follow the below steps:

 Download and include the below jars in addition to spring jars


o Commons-fileupload.jar
o Commons-io.jar
 In the dispatcher-servlet, add the below configuration
<bean id=“multipartResolver”
class=“org.springframework.web.multipart.commons.CommonsMultipartResolver”/>
 In the jsp file, set method as "post" and enctype as "multiple/form-data"
Ex: <form:form method=“post” action=“savefile” enctype=“multipart/form-data”>
<p><label for=“image”>Pick any image</label></p>
<p><input name=“file” id=“fileToUpload” type=“file” /></p>
<p><input type=“submit” value=“Upload”></p>
</form:form>
 Use CommonsMultipartFile class in Controller
@RequestMapping(value="/savefile",method=RequestMethod.POST)
public ModelAndView upload(@RequestParam CommonsMultipartFile file,HttpSession
session){
String path=session.getServletContext().getRealPath("/");
String filename=file.getOriginalFilename();
System.out.println(path+" "+filename);
try{
byte barr[]=file.getBytes();
BufferedOutputStream bout=new BufferedOutputStream(new FileOutput
Stream(path+"/"+filename));
bout.write(barr);
bout.flush();
bout.close();
}
catch(Exception e){System.out.println(e);}
return new ModelAndView("upload-success","filename",path+"/"+filename);
}
11. Validation in Spring MVC
The Spring MVC validation is used to restrict the user.
Spring MVC uses Bean Validation API to validate user’s input. For that download and
add hibernate-validate.jar to the application.
It can validate both server-side and client-side applications.
Validation annotations:
1. @Min – It calculates and ensures that a given number is equal to or greater than a
provided value.
2. @Max – It calculates and ensures that a given number is equal to or less than a
provided value.
3. @NotNull – It calculates and ensures that no null value is possible for a field.
4. @Pattern – It calculates and ensures that the provided regular expression is followed
by the sequence.
5. @Size - It determines that the size must be equal to the specified value.

Steps to add validation in Spring MVC application:


1. Download and add hibernate-validate.jar to the application
2. To validation to a field in the bean, map the validation annotation to that field
Ex: @Size(min=1, message=”required”)
private String username;
3. Use @valid and @BindingResult annotations in the controller
@valid – applies the validation on the provided object
@BindingResult – interface which contains the validation result
Ex: public String subfrm( @Valid @ModelAttribute(“stu”) Student s, BindingResult
br)
4. Include check whether validation is success
Ex: if(br.hasErrors())
If in the jsp no value entered in the password field, error will be shown
Validation with Regular Expression:
In spring MVC, user input can be validated using regular expressions. For that , in the
bean class in stead of validation annotation, use regular expression.
Ex: @Pattern(regexp=“^[a-zA-Z0-9]{4}”,message=“The length should be at least 4”)
private String pwd;
Validation with numbers:
Ex: @Min(value=50, message=“A student must score 50 or more to qualify.”)
@Max(value=100, message=“A student cannot score equal or less than 100.”)
private int marks;
If the user enters value less than 50 or greater than 100 for marks field on browser,
validation fails.

12. References

1. TB1: Mayur Ramgir, FullStack Development with Spring MVC, Hibernate, jquery and
BootStrap, WILEY Publications,2020
2. https://docs.spring.io/spring-framework/docs/3.0.x/spring-framework-
reference/html/overview.html
3. https://www.javatpoint.com/spring-tutorial

You might also like