SECJ 3303 –
INTERNET PROGRAMMING
TOPIC 7 – SPRING MVC
UTM JOHOR BAHRU
OBJECTIVES
Applied
• Test your web application using Apache Maven build tool.
• Write a basic code with Spring MVC application.
Knowledge
• Describe the Apache Maven build tool.
• Describe the overview of Spring framework.
• Describe the Spring Web MVC in Spring framework.
• Understand the important components of Spring Web MVC.
• Explain the Spring Web MVC flow and know how to implement in a code.
• Understand the Spring Exception Handling
2
Apache Maven
• Maven is a build automation and dependency management tool that helps
in project management.
• Build tool is essential for the process of building. It is needed for the
following process:
• Generating source code
• Generating documentation from the source code
• Compiling of source code
• Packaging the compiled code into JAR files.
• Installing the package code in local repository, server or central
repository.
3
Apache Maven
• Maven is written is Java and C# and is based on the Project Object
Model ([Link]).
• Project Object Model is an XML file that has all the information regarding
project and configuration details.
• When we tend to execute a task, Maven searches for the POM in the
current directory.
• The tool is used to build and manage any Java-based project.
• It helps in downloading dependencies, which refer to the libraries or JAR
files.
4
The Problem That Maven Solved
• Getting right JAR files for each project as there maybe different
versions of separate packages.
• To download dependencies, visiting the official website of different
software is not needed. We can refer to [Link]
• Helps to create the right project structure which is essential for
execution.
• Building and deploying the project to make it works.
5
How to convert to Right click
Maven Project in STS?
Steps:
• Right click on your
dynamic web project
• Select - Configure
• Select - Convert to
Maven project
6
Group id : It uniquely identifies
your project among all.
Example: [Link]
Artifact id : It is name of jar or
war without version. It may be
something like project.
Version : Version is used for
version control for artifact id. If
you distribute this project, you
may incrementally create
different version of it.
7
<dependencies>
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<!-- [Link] -->
<dependency>
Example of
<groupId>[Link]</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.20</version>
dependencies </dependency>
<!-- [Link] -->
in [Link]
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.20</version>
</dependency>
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
8
Spring Framework
• Spring framework makes the easy development of JavaEE application.
• It is helpful for beginners and experienced persons.
• Spring is a lightweight framework.
• It can be thought of as a framework of frameworks because it provides
support to various frameworks such as Struts, Hibernate, Tapestry, EJB,
JSF etc.
• 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
Messaging
Test
9
Spring Framework
Source: [Link]
10
Spring Framework
Core Feature:
• Dependency Injection (DI) is also called as Inversion of Control (IoC)
is the most important feature of the Spring Framework and it is at the
core of all Spring Modules.
Why is this DI or IoC so important?
• It is a software design patterns which is really useful for designing
loosely coupled software components.
• These loosely coupled applications can easily be tested and maintained.
• It is easy to reuse your code in other applications.
• The dependencies won’t be hard coded inside all java objects/classes,
instead they will be defined in XML configuration files or configuration
classes (Java Config).
• Spring Container is responsible for injecting dependencies of objects.
11
Advantages of Spring Framework
1) Predefined templates
• Provides templates for JDBC, Hibernate, JPA etc. technologies. There is no
need to write too much code. It hides the basic steps of these technologies.
2) Loose coupling
• The Spring applications are loosely coupled because of dependency injection.
3) Easy to test
• The Dependency Injection makes easier to test the application.
4) Lightweight
• Lightweight because of its POJO implementation. It doesn't force the
programmer to inherit any class or implement any interface.
5) Fast development
• The Dependency Injection feature of Spring Framework and it support to
12
What is
Spring MVC?
Module of Spring framework
on Web layer:
• Web Module
provides basic web-
oriented integration
features and the
initialization of the
IoC container using
servlet listener and
web application
context.
• Servlet Module
contains Spring Source: [Link]
MVC implementation framework-reference/html/[Link]
for web application.
13
Spring MVC
• Spring MVC is an open source MVC 2 framework for developing
Java 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 and Dependency Injection.
• A Spring MVC provides a solution to use MVC in Spring
framework by the help of DispatcherServlet.
• DispatcherServlet is a class that receives the incoming request
and maps it to the right resource such as controllers, models,
and views.
14
Spring MVC Components
• DispatcherServlet responsible for intercepting the request and
dispatching for specific URL.
• HandlerMapping is an interface that defines a mapping between
requests and handler objects. It determines which controller to call.
• Controller responsible for processing user requests and building
appropriate model and passes it to the view for rendering.
• ModelAndView class object encapsulates view and model linking.
• Model encapsulates the application data, will consist of POJO.
• ViewResolver provides a mapping between view names and actual view.
• View interface represents presentation logic and is responsible for
rendering content
15
Spring Web MVC
(Analogy)
Customer
Customer Service
Request toy
as a gift
Response
toy as a gift
16
Spring Web MVC Get the URL and tell the
exact address of the
Handler
Flow
page that can generate
Prepare the data, create
Mapping data for the request
a Java object to hold
the data (it may take
help from other Java
classes if required)
2 3 Dispatcher
Customer Servlet 4
Request
page
1 Controller
5
Front
Controller
Model
10 And View
Java object holding the
Response 9 8 data and name of the
page final response builder
6
7
Display View Mapping between
View the actual Resolver view name and
view with actual view (final
the data response builder)
17
Spring Web MVC Flow
Source: [Link]
18
Spring Web MVC Flow
1. The request will be received by Front Controller i.e. DispatcherServlet.
2. DispatcherServlet will pass this request to HandlerMapping. HandlerMapping will find
suitable Controller for the request.
3. HandlerMapping will send the details of the controller to DispatcherServlet.
4. DispatcherServlet will call the Controller identified by
HandlerMapping. The Controller will process the request by calling appropriate method
and prepare the data. It may call some business logic or directly retrieve data from the
database.
5. The Controller will send ModelAndView(Model data and view name)
to DispatcherServlet.
6. Once DispatcherServlet receives ModelAndView object, it will pass it
to ViewResolver to find appropriate View.
7. ViewResolver will identify the view and send it back to DispatcherServlet.
8. DispatcherServlet will call appropriate View identified by ViewResolver.
9. The View will create Response in form of HTML and send it to DispatcherServlet.
10. DispatcherServlet will send the response to the browser. The browser will render the
html code and display it to end user.
19
Front Controller - DispatcherServlet
• Spring MVC is designed around a central servlet named
DispatcherServlet.
• Every request is handled by the DispatcherServlet.
• DispatcherServlet is also called a Front Controller.
• It uses to handle all incoming requests and uses customizable logic to
determine which controllers should handle which requests.
• It forwards all responses to, through view handlers to determine the
correct views to route responses.
• It exposes all beans defined in Spring to controllers for dependency
injection.
20
Front Controller Baker
(Analogy)
cake
Customer
Waiter
Request cake Barista
cake
coffee
Response coffee
cake Cashier
receipt
receipt
21
BakerController
myCafe
Front Controller
/cake
Client
BaristaController
/myCafe/cake
/coffee
cake
/receipt PaymentController
Front
Controller
/myCafe/*
22
DispatcherServlet in [Link]
• DispatcherServlet is configured in order to dispatch incoming HTTP
request to handlers and returns response to browsers.
• DispatcherServlet is configured in [Link] file.
• Example of DispatcherServlet in [Link]:
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>
[Link]
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/[Link]</url-pattern>
<url-pattern>/[Link]</url-pattern>
<url-pattern>/[Link]</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
23
Spring Configuration
• By default, Spring looks for a [servletname] – [Link] file in the
/WEB-INF folder to get the DispatcherServlet initialized.
Create new XML file
Right click
- New
- File
24
Spring Configuration
• Example of [servletname] – [Link] file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<bean id="HandlerMapping"
class="[Link]"/>
<bean name="/[Link]" class="[Link]"/>
<bean id="viewResolver"
class = "[Link]">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
25
Controller
• DispatcherServlet delegates the request to the controllers to execute
the functionality specific to it.
• The @Controller annotation indicates that a particular class serves the
role of a controller.
• Controller interpret user input and transform this input into specific model
which will be represented to the user by the view.
• @Controller annotation defines the class as a Spring MVC controller.
• @RequestMapping annotation is used to map a URL to either an entire
class or a particular handler method.
26
Controller – Without Annotation
• Example of [Link] - controller file:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HelloController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal (HttpServletRequest request,
HttpServletResponse response) throws Exception{
ModelAndView modelandview = new ModelAndView("HelloPage");
[Link]("welcomeMessage", "Hi user, welcome to the first Spring MVC
Application");
return modelandview;
}
}
27
Controller – With Annotation
• The @Controller annotation indicates that a particular class serves the role of a controller.
• Spring uses the @RequestMapping method annotation to define the URI Template for the
request. It can be applied to class-level and/or method-level in a controller.
• Example of [Link] - controller file with @Controller and @Request Mapping
annotation:
package [Link];
import [Link];
import [Link];
import [Link];
@Controller
public class HelloController {
@RequestMapping("/welcome")
protected ModelAndView helloWorld(){
ModelAndView modelandview = new ModelAndView("HelloPage");
[Link]("welcomeMessage", "Hello World with annotation! ");
return modelandview;
}
}
28
Spring Configuration – With Annotation
• Example of [servletname] – [Link] file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:context="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation=“
[Link]
[Link]
[Link]
[Link]
<bean id="HandlerMapping"
class="[Link]"/>
<bean name="/[Link]" class="[Link]"/>
<context:component-scan base-package="[Link]" />
<bean id="viewResolver"
class = "[Link]">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
29
MultiAction Controller
• MultiAction Controller is a Controller implementation that allows multiple request
types to be handled by the same class.
• It means inside one controller class we can have many handler methods.
@Controller class level
@RequestMapping("/greet")
public class HelloController { method level
@RequestMapping("/welcome") [Link]
protected ModelAndView helloWorld(){
ModelAndView modelandview = new ModelAndView("HelloPage");
[Link]("welcomeMessage", "Hello World with annotation! ");
return modelandview;
}
[Link]
@RequestMapping("/selamat")
protected ModelAndView selamatDatang(){
ModelAndView modelandview = new ModelAndView("HelloPage");
[Link]("welcomeMessage", "Selamat Datang with annotation! ");
return modelandview;
}
} 30
@PathVariable Annotation
The @PathVariable annotation is used to extract the value of the template variables
and assign their value to a method variable.
@Controller
public class HelloController { User input
@RequestMapping("/welcome/{facultyName}/{userName}")
protected ModelAndView helloWorld(@PathVariable ("facultyName") String faculty, @PathVariable ("userName") String name){
ModelAndView modelandview = new ModelAndView("HelloPage");
[Link]("welcomeMessage", "Hello " + name + " Your faculty is: " + faculty);
return modelandview;
}
}
@Controller
public class HelloController { User input
@RequestMapping("/welcome/{facultyName}/{userName}")
protected ModelAndView helloWorld(@PathVariable Map<String,String> pathV ){
String faculty = [Link]("facultyName");
String name = [Link]("userName");
ModelAndView modelandview = new ModelAndView("HelloPage");
[Link]("welcomeMessage", "Hello " + name + " Your faculty is: " + faculty);
return modelandview; Same output with different way of using @PathVariable annotation in Map
}
} Example of URL: [Link]
31
@RequestParam Annotation
• @RequestParam is a @Controller
public class RegisterController {
Spring annotation used to
bind a web request @RequestMapping("/register")
parameter to a method protected ModelAndView getRegisterForm( ){
parameter.
ModelAndView model = new ModelAndView("RegisterForm");
• It has the following optional
elements: return model;
defaultValue - used as }
a fallback when the @RequestMapping("/submit")
request parameter is protected ModelAndView submitRegisterForm(@RequestParam
not provided or has an (“studentName") String name, @RequestParam (“facultyName")
empty value String faculty ){
name - name of the ModelAndView modelandview = new ModelAndView("HelloPage");
request parameter to [Link]("welcomeMessage", "Hello " + name +
bind to “, Your faculty is: " + faculty);
required - tells whether return modelandview;
the parameter is }
required }
value - alias for name
32
@RequestParam Annotation
Same output with different way of using @RequestParam annotation in Map
@Controller
public class RegisterController {
@RequestMapping("/register")
protected ModelAndView getRegisterForm( ){
ModelAndView model = new ModelAndView("RegisterForm");
return model;
}
@RequestMapping("/submit")
protected ModelAndView submitRegisterForm(@RequestParam Map<String,String> req ){
String name = [Link]("StudentName");
String faculty = [Link]("facultyName");
ModelAndView modelandview = new ModelAndView("HelloPage");
[Link]("welcomeMessage", "Hello " + name + “, Your faculty is: " + faculty);
return modelandview;
}
}
33
@ModelAttribute Annotation
• @ModelAttribute is an annotation that binds a method parameter or
method return value to a named model attribute, and then exposes it to a
web view.
• We can use @ModelAttribute either as a method parameter or at the
method level.
Method level
@ModelAttribute
public void addAttributes(Model model) {
[Link]("msg", "Welcome to Malaysia!");
}
As a method parameter
@RequestMapping(value = "/addEmployee", method = [Link])
public String submit(@ModelAttribute("employee") Employee employee) {
// Code that uses the employee object
return "employeeView";
}
34
@ModelAttribute Annotation
Method level (without @ModelAttribute) Method level (with @ModelAttribute)
@RequestMapping("/register") @RequestMapping("/register")
protected ModelAndView getRegisterForm() { protected ModelAndView getRegisterForm() {
ModelAndView model = new ModelAndView model = new ModelAndView("RegisterForm");
ModelAndView("RegisterForm"); return model;
[Link]("headerMessage", "Welcome to }
University");
return model; @RequestMapping("/submit")
} protected ModelAndView submitRegisterForm (@RequestParam
("studentName") String name, @RequestParam ("facultyName")
@RequestMapping("/submit") String faculty ){
protected ModelAndView submitRegisterForm ModelAndView model = new ModelAndView("HelloPage");
(@RequestParam ("studentName") String name, [Link]("welcomeMessage", "Hello " + name + “,
@RequestParam ("facultyName") String faculty ){ Your faculty is: " + faculty);
return model;
ModelAndView model = new }
ModelAndView("HelloPage");
[Link]("welcomeMessage", "Hello " + @ModelAttribute
name + “, Your faculty is: " + faculty); public void addAttributes(Model model) {
[Link]("headerMessage", "Welcome to [Link]("headerMessage", "Welcome to
University"); University");
return model; }
}
35
@ModelAttribute Annotation
As a method parameter (without @ModelAttribute)
@RequestMapping("/submit")
protected ModelAndView submitRegisterForm(@RequestParam ("studentName") String name,
@RequestParam ("facultyName") String faculty ){
Student student1 = new Student();
[Link](name);
[Link](faculty);
ModelAndView model = new ModelAndView("HelloPage");
[Link]("student1", student1);
return model;
}
As a method parameter (with @ModelAttribute) Reduce line of code
@RequestMapping("/submit")
protected ModelAndView submitRegisterForm(@ModelAttribute ("student1") Student
student1 ){
ModelAndView model = new ModelAndView("HelloPage");
return model;
}
36
Model
• Model is generally defined as a MAP that can contain objects that are to
be displayed in view.
• ModelAndView object encapsulates the relations between view and
model and is returned by the corresponding Controller methods.
• ModelAndView class use ModelMap that is custom MAP
implementation where values are added in key-value fashion.
37
ViewResolver
• The ViewResolver maps view names to actual views.
• Spring framework comes with quite a few view resolvers
e.g. InternalResourceViewResolver, BeanNameViewResolver, and a few
others.
• InternalResourceViewResolver is used to resolve the correct view
based on suffix and prefixes, so the correct output (view) is resolved
based on strings.
38
Front
BakerController
ViewResolver Controller
@Controller
/myCafe/* /cake public class BakerController {
@RequestMapping("/cake")
protected ModelAndView
requestCake(){
/myCafe/cake ModelAndView modelandview =
new
HelloPage ModelAndView(“HelloPage");
Dispatcher [Link]("msg",
"Hello here is your cake! ");
Servlet return modelandview;
}
}
HelloPage
Hello here is your cake!
View
WEB-INF/[Link] Resolver
ViewResolver
<bean id="viewResolver"
class =
"[Link] prefix suffix
ViewResolver"> View
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
WEB-INF/ HelloPage .jsp
</beans>
39
View
• Java Spring MVC can be configured with different view technologies
such as JSF,JSP, Velocity, Freemaker etc.
• View is responsible for displaying the content of Model objects on
browsers as response output.
• View page can be explicitly returned as part of ModelAndView object by
the controller.
• The view name can be independent of view technology and resolved to
specific technology by using ViewResolver and rendered by View.
40
View
• Example of [Link] - view file:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>First Spring MVC</title>
</head>
<body>
<h1>First Spring MVC Application</h1>
<h2>${welcomeMessage}</h2>
</body>
</html>
41
Run the Project
• To run the project:
• Right click on your project
• Select - Run As
• Select - Maven build..
42
Run the Project
• Goals: Type - clean install
• Click - Apply
• Click - Run
43
How to fix if the Maven
build is not success?
• Right Click on project
• -->Build Path
• --> Configure Build Path
• -->Add Library..
• -->JRE System Library --> Next
• --> Alternate JRE
• --> Installed JREs --> Add
• --> Standard VM --> Next
• --> Point to Java folder in C:
drive (Windows) and select
JDK folder and Finish.
44
Display the Output
• To run the project:
Right click on your project
• Select - Run As
• Select - Run on Server
• Type in URL -
[Link]
• Example of output using Spring MVC:
45
Exception Handling:
@ExceptionHandler Annotation
• Inside Spring MVC, users can define an exception handling class by
implementing as below: Example for Null Pointer Exception
@RequestMapping("/register")
protected ModelAndView getRegisterForm() throws Exception {
String exceptionOccured = "NULL_POINTER";
if ([Link]("NULL_POINTER")){
throw new NullPointerException("Null Pointer Exception");
}
ModelAndView model = new ModelAndView("RegisterForm");
return model;
}
@ExceptionHandler (value=[Link])
public String handleNullPointerException(Exception e) {
//logging Null Pointer Exception
[Link] ("Null Pointer Exception Occured: "+e);
return "NullPointerException"; Create a new JSP file with same
} name of the return value to
display the output of error.
46
Exception Handling:
@ControllerAdvice Annotation With @ControllerAdvice as
Global Exception Handler
Without @ControllerAdvice
//In [Link]
//In part of [Link]
@ControllerAdvice
@ExceptionHandler (value=[Link]) public class GlobalExceptionHandlerMethods {
public String handleNullPointerException(Exception e)
{ @ExceptionHandler (value=[Link])
public String handleNullPointerException(Exception e)
//logging Null Pointer Exception {
[Link] ("Null Pointer Exception Occured:
"+e); //logging Null Pointer Exception
return "NullPointerException"; [Link] ("Null Pointer Exception Occured:
} "+e);
return "NullPointerException";
@ExceptionHandler (value=[Link]) }
public String handleIOException(Exception e) {
@ExceptionHandler (value=[Link])
//logging Null Pointer Exception public String handleIOException(Exception e) {
[Link] ("IO Exception Occured: "+e);
return "IOException"; //logging Null Pointer Exception
} [Link] ("IO Exception Occured: "+e);
return "IOException";
}
}
47
HTTP Messages
• 202 OK: Request successfully processed by the Server.
• 404 Not Found: Requested Resource is not available.
• 500 Internal Server Error: An unexpected condition/error occurred while
processing a request.
• 503 Service Unavailable: The server is currently unavailable (because it
is overloaded or down for maintenance).
• **Client Error 4xx
• **Server Error 5xx
• For complete list of Status code:
[Link]
48
TOPIC 7 – Spring Web MVC
The End
UTM JOHOR BAHRU