FSD-4.2-Spring-notes (2)
FSD-4.2-Spring-notes (2)
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
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.
2. Spring Architecture
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.
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.
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.
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.
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”.
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>
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