0% found this document useful (0 votes)
35 views44 pages

Unit Iii

Uploaded by

rickyvanith7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views44 pages

Unit Iii

Uploaded by

rickyvanith7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT–III: Spring and Spring MVC

The Spring Framework is a powerful and flexible platform designed for building Java
applications. It simplifies the development process by handling many of the complex, underlying
infrastructure tasks, allowing developers to focus on creating the actual application.
Spring makes it possible to build applications using "plain old Java objects" (POJOs) while
applying enterprise services to them. This approach works well for both simple Java SE
applications and full-fledged Java EE applications.
Here are a few examples of what you can do with the Spring Framework:
• Automatically manage database transactions without dealing with complex transaction
APIs.
• Turn a simple Java method into a remote procedure without needing to handle remote
APIs.
• Convert a local Java method into a management operation without working with JMX
APIs.
• Make a Java method handle messages without directly dealing with JMS APIs.
1.1 Core Principles#
• Before moving to Spring Framework architecture it is important to know the core
principles.
1. Dependency Injection (DI)#
Dependency Injection is a design pattern that allows the inversion of control between
components, reducing the tight coupling and making the application more modular and easier to
maintain. The Spring framework provides an Inversion of Control (IoC) container that manages
the creation and lifecycle of objects (beans) and their dependencies. The ApplicationContext is
an advanced IoC container that offers additional features like event propagation, declarative
mechanisms to create a bean, and various ways to configure your application.
2. Aspect-Oriented Programming (AOP)#
AOP is a programming paradigm that allows separation of cross-cutting concerns (aspects) from
the business logic of an application. Cross-cutting concerns such as logging, security, and
transaction management can be applied across multiple components without cluttering the core
logic.
• Aspects: An aspect is a modularization of a concern that cuts across multiple classes. In
Spring, aspects are implemented using regular classes annotated with @Aspect.
• Join Points: These are points in the program execution, such as method calls or
exception handling, where an aspect can be applied.
• Advice: This is the action taken by an aspect at a particular join point. Spring supports
various types of advice, including Before, After, Around, and AfterThrowing.
• Pointcuts: These are expressions that match join points to determine whether an advice
should be executed.
Spring’s AOP framework makes it easy to define and apply these aspects declaratively, either
through XML configuration or using annotations. This approach enhances code modularity,
promotes reuse, and simplifies maintenance.
1.2 Modules of the Spring framework#
The Spring Framework is divided into various modules, each designed to address specific
aspects of application development. These modules are grouped into several categories:
• Core Container: Includes fundamental components like IoC and DI, helping to manage
object creation and configuration.
• Data Access/Integration: Provides tools for interacting with databases, handling
transactions, and integrating with other data sources.
• Web: Supports building web applications, including MVC (Model-View-Controller)
architecture.
• AOP (Aspect-Oriented Programming) and Instrumentation: Allows adding cross-
cutting concerns like logging or security in a modular way.
• Test: Offers support for testing Spring components, ensuring that they work as expected.
Figure :- The Spring Framework consists of features organized into about 20 modules. These
modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented
Programming), Instrumentation, and Test, as shown in the following diagram.
Spring
Architecture
1.2.1 Core Container#
The Core Container is the foundation of the Spring Framework, providing essential
functionalities for creating and managing application components, known as beans. This
container is crucial for implementing Dependency Injection (DI) and Inversion of Control (IoC)
principles, which decouple application components and promote modularity.
• Spring Core: This module provides the basic DI and IoC functionality. The IoC
container is responsible for instantiating, configuring, and assembling the beans, which
are the objects that form the backbone of a Spring application. By managing
dependencies between beans, the IoC container reduces tight coupling between
components, making the application more modular and maintainable.
• Spring Beans: This module offers the BeanFactory and BeanWrapper. The
BeanFactory is the core interface for accessing the IoC container, allowing you to retrieve
bean instances. The BeanWrapper, on the other hand, facilitates property manipulation on
Java objects, handling type conversions and other property-related operations.
• Spring Context: An advanced version of BeanFactory, ApplicationContext extends
BeanFactory to provide additional features such as internationalization support, resource
loading, and event propagation. ApplicationContext serves as a central point for
configuration and management, offering a unified view of the entire application context.
• Spring Expression Language (SpEL): SpEL is a powerful expression language that
allows you to query and manipulate objects at runtime. It supports a wide range of
operations, including property access, method invocation, arithmetic, conditionals, and
collection iteration. SpEL is deeply integrated into the Spring Framework, enabling
dynamic expressions in annotations, XML configuration, and even directly in the code.
1.2.2 Data Access/Integration#
Spring provides comprehensive support for data access and integration with various data sources,
simplifying interaction with databases and other external systems.
• Spring JDBC: This module abstracts away the complexities of raw JDBC, reducing
boilerplate code and providing a consistent exception hierarchy. Spring JDBC also
integrates seamlessly with Spring’s transaction management, offering declarative
transaction control that enhances the robustness of data access operations.
• Spring ORM: This module integrates with popular Object-Relational Mapping (ORM)
frameworks such as Hibernate, JPA, and MyBatis. It simplifies the use of ORM tools by
providing a consistent template-based approach, transaction management integration, and
support for resource management.
• Spring OXM: The Object/XML Mapping (OXM) module provides an abstraction layer
for serializing Java objects to XML and deserializing XML to Java objects. It supports a
variety of OXM frameworks like JAXB, Castor, and XStream.
• Spring JMS: This module provides a comprehensive framework for producing and
consuming messages using the Java Message Service (JMS). Spring JMS simplifies
messaging by handling resource management, connection management, and message
conversion.
• Spring Transaction: This module offers declarative transaction management, allowing
developers to manage transactions in a consistent and declarative manner across different
transactional resources (e.g., JDBC, JPA). It supports various transaction propagation and
isolation levels, making it suitable for complex transactional scenarios.
1.2.3 Web#
The Web module in Spring provides a rich set of features for building robust and scalable web
applications. It includes support for traditional servlet-based applications, reactive applications,
and integration with other frameworks.
• Spring Web: This module provides foundational web-oriented integration features, such
as multipart file upload, initialization of IoC containers using servlets, and web
application context management. It serves as the base for Spring’s web stack, including
the integration with servlets and web frameworks.
• Spring MVC (Model-View-Controller): A comprehensive framework for building web
applications using the MVC design pattern. Spring MVC supports a range of features,
including form handling, data binding, validation, and internationalization. It integrates
seamlessly with view technologies like JSP, Thymeleaf, and FreeMarker, allowing
developers to create dynamic web pages.
• Spring WebFlux: A reactive web framework that supports building non-blocking,
asynchronous applications. WebFlux is designed for high-concurrency environments and
is suitable for modern microservices architectures. It supports reactive streams and can be
deployed on various web servers, including Netty and Tomcat.
• Spring Servlet: This module provides the foundation for Spring’s web support, including
integration with the Java Servlet API. It allows for the configuration and management of
servlets, filters, and listeners within a Spring application context.
• Spring Portlet: A specialized module for building portlet-based applications, particularly
for portal environments. Spring Portlet extends the Spring MVC framework to support
JSR-168 and JSR-286 Portlet APIs, enabling developers to create modular, reusable
portlets.
• Spring Struts: This module provides integration with the Apache Struts framework,
allowing developers to use Struts with the Spring IoC container. It facilitates the
migration of legacy Struts applications to the Spring Framework while retaining the
familiar Struts architecture.
1.2.4 AOP and Instrumentation#
• Spring AOP (Aspect-Oriented Programming): AOP in Spring allows developers to
separate cross-cutting concerns (e.g., logging, security, transaction management) from the
business logic. By defining aspects, pointcuts, and advice, developers can modularize
concerns that affect multiple parts of an application, leading to cleaner and more
maintainable code. Spring AOP uses proxy-based implementation, ensuring that aspects
are applied seamlessly.
• Spring Instrumentation: This module provides support for class instrumentation and
bytecode manipulation. It is useful for creating proxy classes dynamically and is often
used in conjunction with Spring AOP and for runtime monitoring. Instrumentation can
also be used to enhance the capabilities of the Spring Framework in managed
environments like application servers.
1.2.5 Test#
• Spring Test: This module supports testing Spring applications with frameworks like
JUnit and TestNG. It provides mock objects, transaction management support, and
utilities for testing Spring components (e.g., controllers, services) in isolation or within an
application context. Spring Test also supports integration testing by providing context
configuration and dependency injection into test cases.
In this article, we covered an extensive overview of the Spring Framework, starting from its core
principles like Dependency Injection (DI) and Aspect-Oriented Programming (AOP), which
form the foundation for building modular and maintainable applications. We explored the various
modules that Spring offers, including the Core Container for managing beans, Data
Access/Integration for simplifying database interactions, Web modules for building robust web
applications, AOP and Instrumentation for handling cross-cutting concerns, and the Spring Test
module for ensuring the reliability of your code. Together, these components make Spring a
versatile and powerful framework for Java application development.
Spring MVC

Spring MVC concepts in one place.


• Spring MVC request workflow
• Spring MVC modules
• 15 main Spring MVC annotations
• Link to free HD PDF cheatsheet
What is Spring MVC
The Spring MVC framework provides an architecture based on the Model-View-Controller
(MVC) pattern, utilising loosely coupled ready-made components. The MVC pattern divides
application concerns (input logic, business logic, and UI logic) while ensuring loose coupling
between them.
• Model encapsulates and combines application data, typically consisting of Plain Old Java
Objects (POJOs).
• View is responsible for displaying Model data, often generating HTML that we see in our
web browsers.
• Controller (referred to as Request Handler in Spring terminology) handles user requests,
creates the corresponding Model, and passes it for display in the View.
Strictly speaking, Spring MVC doesn’t introduce new scopes for beans, as the scopes for web-
related work are found in org.springframework.spring-web, not in org.springframework.spring-
webmvc. Out of the six (five before Spring 5) scopes, four work exclusively with web-aware
ApplicationContexts:
• request: A bean is created for each new HTTP request.
• session: A bean is created for each new session.
• application: A bean is created for each new ServletContext (i.e., for the entire web
application).
• websocket: A bean is created for each new WebSocket.
Which of these letters (M, V, C) houses the application’s business logic?
The answer: none of them! It’s essential to grasp the distinction between the MVC pattern and
the n-tier-based-application design principle. The architectural MVC pattern describes only one
layer of your application — the presentation layer. In a standard web enterprise application, there
are other layers, such as the Business layer, where the application logic and domain logic reside,
and the Data layer, composed of Data Access Objects (DAOs) and Data repositories.
The point is that the MVC pattern emerged in the distant 1970s. Nobody knew about GUI or
REST (let alone the World Wide Web) back then because they didn’t exist. Many of the
programming languages we use today were developed in the 1990s. Therefore, MVC is not
applied in our context in the same way as it was historically.
Spring MVC Configuration
Spring MVC introduces the WebApplicationContext interface, which inherits from
the ApplicationContext interface and adds the getServletContext() method to access
the ServletContext. The WebApplicationContext interface has five concrete implementations,
with the main ones described below.
XmlWebApplicationContext
This implementation of the context reads configurations from XML. This is an outdated legacy
stuff, we will not cover it.
WebApplicationContext and GroovyWebApplicationContext
Types of WebApplicationContext in the Spring Framework specifically configured using Java-
based / Groovy-based classes and annotations. It allows developers to define beans and
configurations for a web application using Java code and annotations, providing a programmatic
and type-safe approach. InGroovy case, it reads configuration from Groovy files parsed by
the GroovyBeanDefinitionReader.
AnnotationConfigWebApplicationContext
It serves as the web application counterpart of AnnotationConfigApplicationContext, allowing
you to configure a Spring MVC application using annotations. You can configure Spring MVC
applications through annotations either by annotating a configuration class
with @Configuration or by using the @Component annotations.
To use this ApplicationContext, you need to specify the fully qualified class name as the value of
the contextClass to the ContextLoader class or as the contextClass init-param value to the class
implementing FrameworkServlet.
Is it possible to specify classes one by one as the location of the application configuration or use
classpath scanning?
You can either specify classes one by one as the location of the application configuration or
utilise classpath scanning:
<context:annotation-config/>: This tag searches for annotations
like @PostConstruct, @PreDestroy, @Resource, @Autowired, @Required, and others, including
JPA and EJB 3 annotations, in all application classes.
<context:component-scan base-package="com.ex.sample, com.ex.all">: This tag goes beyond
what <context:annotation-config/> does. It searches for stereotype annotations such
as @Component, @Controller, @Service, @Repository, and others, but only in classes within
the specified packages.
Request Lifecycle in Spring MVC
Please refer to visuals on the cheatsheet for better memorising. All encountered classes are
further elaborated in their respective sections.
1. An HTTP request arrives at the DispatcherServlet.
2. The DispatcherServlet contacts the HandlerMapping and receives
a HandlerExecutionChain — the order in which the request should pass through
Interceptors to reach a specific controller (handler).
3. The request passes through Interceptors, and the preHandle() method is called for each of
them.
4. The HandlerAdapter calls the handleRequest() method of the controller.
5. The controller takes the request, reads request parameters, and invokes the
corresponding service method based on GET or POST, passing the parameters to it.
6. The invoked method calls service methods, retrieves data for the Model, assembles it, and
provides the controller with the View’s name and Model, which the controller then sends
to the DispatcherServlet.
7. Interceptors are executed in reverse order, and the postHandle() method is called for each
of them.
8. Using the ViewResolver interface, the DispatcherServlet determines which View to use
based on the received View name.
9. Once the View is created, the DispatcherServlet sends Model data as attributes to
the View.
10. The View is rendered in the user’s browser (e.g., through JSP).
11. Interceptors’ afterCompletion() methods are executed.
Things are a bit simpler with REST application. Methods in a RestController typically return
domain objects or collections directly. These objects are automatically converted to JSON or
XML (based on configuration) and sent as the response.
What is DispatcherServlet
The logic of Spring MVC revolves around the DispatcherServlet, which receives and handles all
HTTP requests (from the UI) and their responses. You can think of it as the dispatcher guy who
utilises the services of auxiliary classes and regulates the distribution of requests and responses.
Can there be more than one DispatcherServlet in an application?
In a web application, you can have as many DispatcherServlets as you want. Each of them will
operate within its namespace, raising its own ApplicationContext with its
own mappings, handlers, and so on.
To declare multiple DispatcherServlets, you can either:
• Declare multiple instances of
the org.springframework.web.servlet.DispatcherServlet class with different names and
ensure that each has its <servletName>-servlet.xml configuration file (if you’re working
with XML).
• Create multiple classes that implement WebApplicationInitializer and make a
configuration class for each one (if you’re using annotations).
Configuration of DispatcherServlet
1. Via XML. You can configure Spring and Spring MVC in web.xml by passing XML
configuration files as values for the contextConfigLocation parameter. In more complex
web applications, the front-end and back-end configurations are separated.
<!-- web.xml -->
<web-app>
<!-- Configure the Spring DispatcherServlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2. Java config
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controller") // Specify the package where your
controllers are located
public class WebAppConfig extends WebMvcConfigurerAdapter {

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// Configure a view resolver for rendering JSP views
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
}
What is HandlerMapping
HandlerMapping is an interface in spring-web that classes defining the mapping between
requests and their handlers (which controller handles which request) should inherit. The interface
has a single method:
HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
The primary implementation of this interface is the SimpleUrlHandlerMapping class, which
maps URLs to handler beans.
What is HandlerExecutionChain
HandlerExecutionChain is a class that encapsulates the sequence of processing a request through
Interceptors to the Handler and back through Interceptors. The class has three main methods:
boolean applyPreHandle(HttpServletRequest request,
HttpServletResponse response) throws Exception

void applyPostHandle(HttpServletRequest request,


HttpServletResponse response,
ModelAndView mv) throws Exception

void triggerAfterCompletion(HttpServletRequest request,


HttpServletResponse response,
Exception ex) throws Exception
The first method calls the preHandle() method on all registered interceptors (in the order of
registration), the second calls postHandle() (in reverse order), and the third
calls afterCompletion().
What is an Interceptor
Conceptually, Interceptors are similar to filters when working with servlets. Requests pass
through them on their way to the controller and back. A class implementing an interceptor must
implement the HandlerInterceptor interface, which contains three methods:
1. preHandle(): This method is invoked after the HandlerMapping has determined the
appropriate Handler but before the HandlerAdapter calls its method. A common use case
is implementing security filters before reaching the controller.
2. postHandle(): This method is invoked after the HandlerAdapter has called the Handler's
method and provided the name of the View, but before the DispatcherServlet provides the
View.
3. afterCompletion(): This method is invoked after the request has been processed, and the
View has been provided.
What is HandlerAdapter
HandlerAdapter is an internal Spring interface that all handlers must inherit to process
requests. DispatcherServlet uses this interface to call methods on handlers since it accommodates
various annotations within controller classes and determines which method to call.
The default implementations listed in DispatcherServlet.properties are as follows. They are used
when <mvc:annotation-driven/> is absent in XML configuration (or when @EnableWebMVC is
missing in annotation-based configuration). Otherwise, RequestMappingHandlerAdapter is used
as default.
What is a Controller
Controllers are Plain Old Java Objects (POJOs) annotated with @Controller intended for request
handling. Each controller contains methods that are mapped to URLs using
the @RequestMapping annotation.
Instead of @Controller, you can use @RestController. This is a composite annotation that,
underneath, uses @Controller along with @ResponseBody, indicating that what all controller
methods return is the response body (not the name of a View). In other words, a controller with
this annotation handles only REST requests.
Here’s an example of a controller.
@Controller
@RequestMapping("/persons") // Base URL path for all methods in this controller
public class PersonsController {

@Autowired
private PersonsService personsService;

@RequestMapping(value = "/", method = RequestMethod.GET) // Handles GET requests to


/persons/
public String list(Model model) {
model.addAttribute("persons", personsService.findAll());
return "persons/list"; // View name
}

@RequestMapping(value = "/{id}", method = RequestMethod.GET) // Handles GET requests


to /persons/{id}
public String get(@PathVariable Long id, Model model) {
model.addAttribute("person", personsService.get(id));
return "persons/get"; // View name
}
}
When the @RequestMapping annotation is placed on the class, the path to which the controller is
mapped becomes part of the URL. When the annotation is placed on a method, the path is
resolved relative to the class-level annotation.
Methods not annotated with @RequestMapping cannot be used to handle requests directly (they
can only serve as auxiliary methods for annotated ones).
Parameters of the @RequestMapping annotation:
• value="persons/list": The default parameter, the URL to which the method or controller
class is mapped.
• method=RequestMethod.GET: The HTTP request method to which the method or
controller class is mapped.
• params={"id"}: An array with the names of HTTP request parameters.
• params={"id=1234"}: The same as above but with a specific parameter value.
Accessing Request Parameters
To provide methods with access to HTTP request parameters, common annotations are usually
used, such as:
• @RequestParam(value="page") String page: To pass the value of the page HTTP request
parameter to the controller method (meaning the parameter is static).
• @PathVariable(value="id") int id: To pass dynamic values found directly in the URL, not
in the HTTP request parameters.
If you are serious about your skills development, you need to learn from the best. Get special
discounts on Skillshare with my referral link. I highly recommend.
What is Model
Model encapsulates application data, typically retrieved from a database. An instance of Model is
passed as a parameter to a controller method and is populated within the method.
You can think of Model as a kind of map with the format <attribute name, corresponding
object>. Model attributes are populated using model.addAttribute(), where a string representing
the attribute name and the corresponding Java object are passed as parameters. After this, all
model attributes are accessible to a JSP page for rendering.
If you don’t specify an attribute name, it will be automatically generated based on the data type.
For example, if you pass an object of the Person class, the attribute will be named "person". If
you pass a List<Person>, it will be named "personList".
If you only need to add one object to the model, you can return it directly from the controller
method instead of adding it to the model and then returning the view name. In this case, the view
name is determined based on the URL by removing the first “/” and any extension if it exists.
What is ViewResolver
The HTTP response returned to the client after executing a Handler method is based on
the Model and View. Spring provides a mechanism called ViewResolver to decouple from a
specific rendering technology.
The ViewResolver interface maps a view name to a specific View, which is related to that name.
The interface has a single method:
View resolveViewName(String viewName,
Locale locale) throws Exception,
This method, given the view name and the client’s locale, returns an instance of View.
A straightforward implementation of this interface in Spring is the BeanNameViewResolver class,
which assumes that the viewName is the name of a bean in the
current ApplicationContext (typically in the XML configuration file executed by the
DispatcherServlet).
More complex applications might use
custom ViewResolver and ResourceBundleViewResolver (which supports internationalisation).
What is View
View is responsible for rendering data contained in the Model. In Spring, a View is an interface
with two methods:
String getContentType()
Returns the content type of the View, if predefined. It's used to check the content before starting
to render the View.
void render(Map<String, ?> model,
HttpServletRequest request,
HttpServletResponse response) throws Exception
The main method for rendering. The first step in this method is to prepare the request by setting
objects in the model as attributes of the HTTP request. The second step is the actual rendering of
the View (for example, including a JSP page in the HTTP response via DispatcherServlet).
What is a Filter
A Filter is an interface that allows you to perform filtering tasks on either the HTTP request to a
resource or the response from a resource, or both. Filtering is implemented using the Chain of
Responsibility pattern: each filter performs its part of the work and passes control to the next
one.
The interface has following methods:
//This method is called by the container and initializes the filter
// after it has been instantiated.
public void init(FilterConfig filterConfig) throws ServletException;

//This method is called by the container each time


//a request or response passes through the filter chain.
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException;

//This method is called by the container to give the filter


//an opportunity to clean up after itself.
public void destroy();
Typical implementation steps:
• Check the request.
• Optionally wrap the request in your implementation for content or header filtering.
• Optionally wrap the response in your implementation for content or header filtering.
• Either pass the request/response pair to the next filter in the chain through the FilterChain
object, or block it by not passing the pair to the next filter.
• Set response headers directly after calling the next filter object in the chain.
What is a Listener
A Listener is an interface that allows components to listen for and react to events in the Spring
environment. It’s used in event-driven programming. The only method in this interface is:
void onApplicationEvent(E event)
This method enables a listener to react to a specific event published by a Publisher.
Annotations
1. @Controller: Marks a class as a Spring MVC controller, capable of handling HTTP
requests.
2. @RequestMapping: Maps a method or class to a specific URL or URL pattern. It
specifies which HTTP methods the method can handle.
3. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: Shortcuts for
mapping HTTP GET, POST, PUT, and DELETE requests, respectively, using
the @RequestMapping annotation.
4. @RequestParam: Binds a request parameter to a method parameter. It’s used to access
query parameters or form data from HTTP requests.
5. @PathVariable: Extracts values from URL path segments and binds them to method
parameters.
6. @ModelAttribute: Binds a method parameter or method return value to a named model
attribute. Used for populating data in the model before rendering a view.
7. @ResponseBody: Indicates that the return value of a method should be used as the HTTP
response body, often used for RESTful services returning data in JSON or XML.
8. @RequestBody: Binds the HTTP request body to a method parameter, typically used for
receiving data in JSON or XML format.
9. @RestController: Combines @Controller and @ResponseBody to simplify the creation
of RESTful web services.
10. @ExceptionHandler: Defines methods to handle exceptions thrown by the controller
methods.
11. @ResponseStatus: Specifies the HTTP status code to be returned when a specific
exception is thrown.
12. @SessionAttributes: Specifies which model attributes should be stored in the session
between requests.
13. @RequestHeader: Binds a request header value to a method parameter.
14. @CrossOrigin: Enables cross-origin resource sharing (CORS) for specific controller
methods.
15. @ResponseStatus: Specifies the HTTP response status code and reason phrase to be
returned by a controller method.

Spring MVC Multiple View


• In a Spring MVC application, you can easily handle multiple views by creating multiple
controllers and corresponding views. Each controller is responsible for handling a
specific URL and rendering a specific view.
• Here’s how to set up multiple views in a Spring MVC application:
Step 1: Create Multiple Controllers
• Create separate controller classes for each view you want to handle. Each controller
should be annotated with @Controller and define methods to handle specific URLs.
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
// Return the view name
(e.g., home.jsp)
}
}

@Controller
public class AboutController {
@GetMapping("/about")
public String about() {
return "about";
// Return the view name
(e.g., about.jsp)
}
}
Step 2: Create Multiple JSP Views
• For each controller, create corresponding JSP views in the src/main/webapp/WEB-
INF/views directory. Name the views according to the view name returned by the
controllers.
• For example, if the HomeController returns “home,” create a home.jsp file. If the
AboutController returns “about,” create an about.jsp file.
Here’s an example of a home.jsp:
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to the Home Page</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>About Page</title>
</head>
<body>
<h1>About Us</h1>
<p>We are a company that
does amazing things.</p>
</body>
</html>
Step 3: Configure View Resolver
• In your Spring MVC configuration (e.g., dispatcher-servlet.xml), configure the view
resolver to resolve view names to JSP files.
<bean class="org.springframework
.web.servlet.view
.InternalResourceViewResolver">
<property name="prefix"
value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
Step 4: Access Multiple Views
• Now, you can access the multiple views by navigating to the corresponding URLs
defined in your controllers:
• To access the home page, visit http://localhost:8080/your-web-app-context/.
• To access the about page, visit http://localhost:8080/your-web-app-context/about.

Spring MVC Form Tag Library


• The Spring MVC Form Tag Library provides a set of JSP tags that simplify the process of
rendering HTML forms in Spring MVC applications. These tags generate HTML form
elements, handle data binding between form fields and model attributes, and perform
validation.
• Here are some commonly used Spring MVC form tags:
form:form
• This tag represents an HTML

element and is used to create the opening and closing tags of a form. It also binds the
form to a specific model attribute.
<form:form modelAttribute="user"
method="POST"
action="/saveUser">
<!-- Form fields go here -->
</form:form>

form:input
• This tag generates an HTML input element for text input. It can be used for various input
types, such as text, password, email, etc.
<form:form modelAttribute="user"
method="POST"
action="/saveUser">
<!-- Form fields go here -->
</form:fo<form:input path="username" />
rm>
form:radiobutton
• Use this tag to create radio buttons
<form:radiobutton
path="notificationPreference"
value="EMAIL" />
<form:radiobutton
path="notificationPreference"
value="SMS" />
form:checkbox
• This tag generates checkboxes for boolean values.
<form:checkbox path="subscribed" />
form:select
• This tag generates an HTML select element for dropdown lists.
<form:select path="gender">
<form:option
value="MALE" label="Male" />
<form:option
value="FEMALE" label="Female" />
</form:select>
form:textarea
• Use this tag to create a text area input element.
<form:textarea path="description" />

form:hidden
• This tag creates a hidden input field.
<form:hidden path="id" />

The form tag


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

n Spring MVC, the @RequestParam annotation is used to extract query parameters, form
data, or path variables from the request and map them to method parameters in the
controller. It is commonly used in request mappings for handling form submissions, URL
query parameters, or retrieving data from the URL.
Here's a detailed explanation and example of how to use @RequestParam:
1. Basic Usage
The @RequestParam annotation binds a web request parameter to a method parameter in
your controller.
java
@Controller
public class MyController {

@RequestMapping("/greet")
public String greet(@RequestParam("name") String name, Model model) {
model.addAttribute("message", "Hello, " + name);
return "greeting"; // Return view name
}
}
In the above example:
• The @RequestMapping("/greet") maps to the /greet endpoint.
• The @RequestParam("name") binds the name parameter from the query string (e.g.,
/greet?name=John) to the name method parameter.
• The greeting message is added to the model and returned to the view.
2. Optional Parameters
You can make a request parameter optional by providing a default value using the
defaultValue attribute.
@Controller
public class MyController {

@RequestMapping("/greet")
public String greet(@RequestParam(value = "name", defaultValue = "Guest") String
name, Model model) {
model.addAttribute("message", "Hello, " + name);
return "greeting"; // Return view name
}
}
In this example:
• If the name parameter is not provided in the request, the default value "Guest" will be
used.
3. Handling Multiple Parameters
You can handle multiple request parameters in a single method.
@Controller
public class MyController {

@RequestMapping("/user")
public String userDetails(@RequestParam("name") String name,
@RequestParam("age") int age, Model model) {
model.addAttribute("message", "Name: " + name + ", Age: " + age);
return "userDetails"; // Return view name
}
}
In this case, the method userDetails expects both name and age as query parameters, like
/user?name=John&age=30.
4. Handling Missing Parameters
You can also specify whether a parameter is required. By default, @RequestParam
expects the parameter to be present, but you can set required = false to make it optional.
@Controller
public class MyController {

@RequestMapping("/user")
public String userDetails(@RequestParam(value = "name", required = false) String
name, Model model) {
String message = (name != null) ? "Hello, " + name : "Hello, Guest";
model.addAttribute("message", message);
return "userDetails"; // Return view name
}
}
In this example:
• If the name parameter is not provided in the request, it will default to "Hello, Guest".
5. Binding Multiple Parameters Using @RequestParam with Map
If you expect multiple parameters with the same name or just want to handle them
dynamically, you can bind them into a Map.
@Controller
public class MyController {

@RequestMapping("/params")
public String params(@RequestParam Map<String, String> allParams, Model model)
{
model.addAttribute("params", allParams);
return "paramsView";
}
}
If the request contains parameters like /params?name=John&age=30, the Map<String,
String> will contain {"name": "John", "age": "30"}.
6. Binding to a Custom Object
You can also bind request parameters to a custom Java object using @RequestParam if
the object’s fields match the request parameters.
public class User {
private String name;
private int age;

// getters and setters


}

@Controller
public class MyController {

@RequestMapping("/user")
public String userDetails(@RequestParam User user, Model model) {
model.addAttribute("message", "User: " + user.getName() + ", Age: " +
user.getAge());
return "userDetails"; // Return view name
}
}
In this case, the request could look like /user?name=John&age=30 and the User object
would be populated automatically with those values.
In a Spring MVC application, file uploading is a common task. Spring provides support
for handling file uploads in forms through the use of multipart file support. The general
approach involves configuring the necessary file upload settings, creating a form to
upload files, and handling the uploaded file in the controller.
Here’s a step-by-step guide to setting up file uploads in Spring MVC.
1. Add Dependencies
To enable file uploading, you need to include the necessary dependencies in your
pom.xml (for Maven).
<dependencies>
<!-- Spring Web MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.x</version>
</dependency>

<!-- File upload dependency (commons file upload) -->


<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>

<!-- Commons IO for handling file IO -->


<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
2. Configure multipart Support in web.xml
To enable multipart file uploads in Spring, you need to configure a MultipartResolver
bean. This can be done in your web.xml (for Servlet-based applications) or via a Java
configuration class.
Example web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

<!-- Multipart Config -->


<multipart-config>
<max-file-size>10485760</max-file-size> <!-- 10MB -->
<max-request-size>20971520</max-request-size> <!-- 20MB -->
<file-size-threshold>0</file-size-threshold>
</multipart-config>

<!-- Other servlet configurations -->


<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
This configuration tells the servlet container to handle multipart data (i.e., file uploads) in
the request.
3. Create a Form to Upload Files
Now, create an HTML form where users can select and upload files. You'll need to set the
enctype attribute to multipart/form-data to allow the form to handle file data.
Example HTML Form (JSP):
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
4. Controller to Handle File Upload
In your Spring MVC controller, you can handle the file upload using @RequestParam for
the file parameter.
Example Controller:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;

@Controller
public class FileUploadController {

private static final String UPLOAD_DIR = "/uploads/";

@PostMapping("/upload")
public ModelAndView handleFileUpload(@RequestParam("file") MultipartFile file) {
ModelAndView modelAndView = new ModelAndView();

if (!file.isEmpty()) {
try {
// Get the file and save it locally
String filePath = UPLOAD_DIR + file.getOriginalFilename();
File dest = new File(filePath);
file.transferTo(dest);

modelAndView.setViewName("uploadSuccess");
modelAndView.addObject("message", "File uploaded successfully!");
} catch (IOException e) {
modelAndView.setViewName("uploadFailure");
modelAndView.addObject("message", "Failed to upload file.");
}
} else {
modelAndView.setViewName("uploadFailure");
modelAndView.addObject("message", "No file selected.");
}

return modelAndView;
}
}
5. Configuration for MultipartResolver (Optional)
If you're using Java configuration, you need to define the MultipartResolver bean in your
@Configuration class.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Configuration
public class AppConfig {

@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(10485760); // 10MB
resolver.setMaxInMemorySize(1048576); // 1MB
return resolver;
}
}
6. Handle Upload Result in the View
In your JSP or HTML view, you can display the result of the upload operation.
Example uploadSuccess.jsp:
<h1>${message}</h1>
Example uploadFailure.jsp:
<h1>${message}</h1>
7. Configure Application Properties (Optional)
You can configure additional properties related to file uploads in your
application.properties file (if using Spring Boot or Spring Framework with Spring Boot-
like configuration).
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=20MB

In Spring MVC, validation is an essential part of handling form submissions and ensuring
that the data entered by users is correct. Spring provides powerful validation mechanisms
that can be integrated with forms using annotations, and these can be extended with
custom validation logic using regular expressions or numeric constraints.
Here’s a detailed explanation of how to implement validation in Spring MVC, including
validation with regular expressions and numbers.

1. Basic Validation in Spring MVC


Spring provides the @Valid and @Validated annotations, which can be used to trigger
validation on form backing objects. To perform validation, you typically use JSR-
303/JSR-380 annotations (such as @NotNull, @Size, @Email, etc.).
Example:
Model Class:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Email;

public class User {

@NotNull
@Size(min = 2, max = 30)
private String name;

@Email
private String email;

@NotNull
private String password;

// getters and setters


}
Controller Class:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
@Controller
public class UserController {

@RequestMapping("/register")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "userForm";
}

@RequestMapping("/submitForm")
public String submitForm(@Valid @ModelAttribute("user") User user, BindingResult
bindingResult) {
if (bindingResult.hasErrors()) {
return "userForm"; // Return to the form view with validation errors
}
return "success";
}
}
In the above example:
• The @NotNull, @Size, and @Email annotations perform validation.
• The BindingResult is used to check for validation errors.

2. Validation with Regular Expressions


Spring MVC allows you to validate form fields using regular expressions with the
@Pattern annotation. This is useful for validating things like phone numbers, zip codes,
or any custom string patterns.
Example:
Model Class:
import javax.validation.constraints.Pattern;
public class User {

@Pattern(regexp = "^[a-zA-Z0-9]+$", message = "Username must be alphanumeric")


private String username;

@Pattern(regexp = "^\\+?[1-9]\\d{1,14}$", message = "Invalid phone number format")


private String phoneNumber;

// getters and setters


}
In this example:
• The @Pattern annotation is used to ensure that the username consists only of
alphanumeric characters.
• The phoneNumber field is validated using a regular expression that ensures the phone
number format is valid for international phone numbers.
3. Validation with Numbers
To validate numbers (e.g., age, price, etc.), you can use annotations like @Min, @Max,
@DecimalMin, @DecimalMax, and @Digits.
Basic Numeric Validation with @Min, @Max:
• @Min: Ensures that the number is greater than or equal to a specified minimum value.
• @Max: Ensures that the number is less than or equal to a specified maximum value.
Example:
import javax.validation.constraints.Min;
import javax.validation.constraints.Max;

public class Product {

@Min(value = 1, message = "Price must be at least 1")


@Max(value = 10000, message = "Price must not exceed 10000")
private double price;

// getters and setters


}
In this example:
• The price field is validated to ensure that it’s between 1 and 10000.
Decimal Validation with @DecimalMin, @DecimalMax:
For decimal numbers, use @DecimalMin and @DecimalMax.
Example:
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.DecimalMax;

public class Product {

@DecimalMin(value = "0.1", message = "Price must be at least 0.1")


@DecimalMax(value = "9999.99", message = "Price must not exceed 9999.99")
private double price;

// getters and setters


}
In this example:
• The price field is validated to ensure it’s between 0.1 and 9999.99 (for decimal values).
Validation with @Digits:
Use the @Digits annotation to ensure that a numeric field has a specific number of
integral digits and fractional digits.
Example:
import javax.validation.constraints.Digits;
public class Product {

@Digits(integer = 5, fraction = 2, message = "Invalid price format")


private double price;

// getters and setters


}
In this example:
• The @Digits annotation ensures that the price has at most 5 integral digits and 2
fractional digits (e.g., 99999.99).

4. Custom Validation with Regular Expressions


You can also create custom validation annotations using @Constraint, @Target, and
@Retention to perform validation with complex logic, including regular expressions.
Example of Custom Regular Expression Validator:
1. Create the Annotation:
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = PhoneNumberValidator.class)
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidPhoneNumber {
String message() default "Invalid phone number format";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
2. Create the Validator Class:
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PhoneNumberValidator implements


ConstraintValidator<ValidPhoneNumber, String> {

private static final String PHONE_REGEX = "^\\+?[1-9]\\d{1,14}$";

@Override
public void initialize(ValidPhoneNumber constraintAnnotation) {
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && value.matches(PHONE_REGEX);
}
}
3. Use the Custom Validator in the Model Class:
public class User {

@ValidPhoneNumber
private String phoneNumber;

// getters and setters


}
This custom validation ensures that the phone number adheres to a specific format using
a regular expression.

Here’s a simplified version of a CRUD application using Spring MVC with Spring
Data JPA. This example will cover basic operations (Create, Read, Update, Delete) with
minimal configuration and a focus on simplicity.
Step-by-Step Example
1. Add Dependencies (pom.xml)
If you're using Maven, include the following dependencies in your pom.xml for Spring
MVC, Spring Data JPA, and H2 (an in-memory database).
<dependencies>
<!-- Spring Web MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.x</version>
</dependency>

<!-- Spring Data JPA -->


<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.7.x</version>
</dependency>

<!-- H2 Database (in-memory for simplicity) -->


<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>runtime</scope>
</dependency>

<!-- Spring Boot Starter Data JPA (Optional if using Spring Boot) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
2. Configure Application Properties
Configure H2 as an in-memory database and set up basic JPA properties in
application.properties.
# H2 Database Configuration (In-memory database for simplicity)
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
3. Create Entity Class
The entity will represent a simple Student table in the database.
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Student {

@Id
private Long id;
private String name;
private String email;

// Constructors, getters, and setters


public Student() {}

public Student(Long id, String name, String email) {


this.id = id;
this.name = name;
this.email = email;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public String getEmail() {
return email;
}

public void setEmail(String email) {


this.email = email;
}
}
4. Create Repository Interface
The repository will interact with the database to perform CRUD operations.
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student, Long> {


// No need to write queries for basic CRUD operations
}
5. Create Controller Class
This controller will handle HTTP requests and interact with the StudentRepository for
CRUD operations.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentRepository studentRepository;

// Show list of students (READ)


@GetMapping
public String listStudents(Model model) {
List<Student> students = studentRepository.findAll();
model.addAttribute("students", students);
return "student/list"; // View: list.jsp
}

// Show the form to create a new student (CREATE)


@GetMapping("/new")
public String showCreateForm(Model model) {
model.addAttribute("student", new Student());
return "student/form"; // View: form.jsp
}

// Handle the form submission to save a student (CREATE)


@PostMapping("/save")
public String saveStudent(@ModelAttribute Student student) {
studentRepository.save(student);
return "redirect:/students"; // Redirect to the list
}

// Show the form to edit an existing student (UPDATE)


@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable("id") Long id, Model model) {
Student student = studentRepository.findById(id).orElseThrow();
model.addAttribute("student", student);
return "student/form"; // View: form.jsp
}

// Handle the form submission to update an existing student (UPDATE)


@PostMapping("/update")
public String updateStudent(@ModelAttribute Student student) {
studentRepository.save(student);
return "redirect:/students"; // Redirect to the list
}

// Handle deletion of a student (DELETE)


@GetMapping("/delete/{id}")
public String deleteStudent(@PathVariable("id") Long id) {
studentRepository.deleteById(id);
return "redirect:/students"; // Redirect to the list
}
}
6. Create Views (JSP)
You'll need basic JSP views to render the list of students and provide forms for
adding/editing students.
list.jsp (Displaying All Students):
<h2>Students List</h2>
<a href="/students/new">Add New Student</a>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${students}">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.email}</td>
<td>
<a href="/students/edit/${student.id}">Edit</a> |
<a href="/students/delete/${student.id}">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
form.jsp (Create or Edit Student Form):
<h2>${student.id == null ? 'Add New' : 'Edit'} Student</h2>
<form action="${student.id == null ? '/students/save' : '/students/update'}"
method="post">
<input type="hidden" name="id" value="${student.id}" />
<label>Name: </label>
<input type="text" name="name" value="${student.name}" required /><br/>
<label>Email: </label>
<input type="email" name="email" value="${student.email}" required /><br/>
<button type="submit">${student.id == null ? 'Add Student' : 'Update
Student'}</button>
</form>
7. Run the Application
You can now run the Spring MVC application. The basic flow will be:
1. Create: Go to /students/new, fill in the form, and submit it to add a student.
2. Read: View the list of students at /students.
3. Update: Click "Edit" next to a student to modify their details.
4. Delete: Click "Delete" next to a student to remove them.

You might also like