You are on page 1of 465

JAVASERVER PAGES

Instructor: CUONGPNB1

©FPT SOFTWARE - Corporate Training Center - Internal Use 1


Learning Goals

Know about
Java Server
Pages (JSP)
Can use JSP
to build Web
application

©FPT SOFTWARE - Corporate Training Center - Internal Use 2


Table of contents
◊ JSP Introduction
◊ JSP Scripting Element
◊ Implicit Objects
◊ Q&A

©FPT SOFTWARE - Corporate Training Center - Internal Use 3


Section 1

JSP INTRODUCTION

©FPT SOFTWARE - Corporate Training Center - Internal Use 4


JSP Introduction (1/2)
 What is JSP?
 JavaServer Pages (JSP) is a technology for developing web pages that
support dynamic content which helps developers insert java code in
HTML.
 As an extension of Servlet technology
 JSPs are essential an HTML page with special JSP tags embedded.
 All JSP programs are stored as a .jsp files
HTML page JSP page

©FPT SOFTWARE - Corporate Training Center - Internal Use 5


JSP Introduction (2/2)
 Servlet:
 Java Servlets are programs that run on a Web server and act as a middle
layer between a request coming from a Web browser and databases on
the HTTP server.

 JSP vs Servlet:

©FPT SOFTWARE - Corporate Training Center - Internal Use 6


Architecture of a JSP Application
 JSP plays a key role and it is responsible for of processing the
request made by client.
 Client (Web browser) makes a request
 JSP then creates a bean object which then fulfills the request and pass
the response to JSP
 JSP then sends the response back to client

©FPT SOFTWARE - Corporate Training Center - Internal Use 7


JSP Process
Steps required for a JSP request:
1. The user goes to web side made using JSP. The web browser makes the request via
the Internet.
2. The JSP request gets sent to the Web server.
3. The Web server recognizes that the file required is special (.jsp), therefore passes the JSP file
to the JSP servlet engine.
4. If the JSP file has been called the first time, the JSP file is parsed, otherwise goto step 7.
5. The next step is to generate a special Servlet from the JSP file. All the HTML required is
converted to println statements.
6. The Servlet source code is compiled into a class.
7. The servlet is instantiated, calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
9. HTML results are displayed on the user's web browser.

©FPT SOFTWARE - Corporate Training Center - Internal Use 8


Example
First Example

©FPT SOFTWARE - Corporate Training Center - Internal Use 9


Practical time
1. Create Dynamic Web Project:

2. Create jsp page in WebContent


folder

©FPT SOFTWARE - Corporate Training Center - Internal Use 10


Practical time
Create a simple jsp page:

©FPT SOFTWARE - Corporate Training Center - Internal Use 11


Practical time
3. Setup tomcat server:
 Download and unzip Apache Tomcat .
 Open Window | Preferences | Server | Installed Runtimes to create a Tomcat
installed runtime.
 Click on Add... to open the New Server Runtime dialog, then select your runtime
under Apache
4. Run your code

©FPT SOFTWARE - Corporate Training Center - Internal Use 12


Section 2

JSP SCRIPTING ELEMENT

©FPT SOFTWARE - Corporate Training Center - Internal Use 13


Scriptlet
 Scriptlet (<% ... %>) - also called “Scripting Elements”
 Enable programmers to insert Java code in JSPs
 Performs request processing
 For example, to print a variable:

Code snippet
<%
String username = "alliant";
out.println(username);
%>

©FPT SOFTWARE - Corporate Training Center - Internal Use 14


JSP Tags
 Declaration tag (<%! %>)
 Allow the developer to declare variables or methods.
Code snippet
<%!
private int counter = 0;
private String getAccount(int accountNo);
%>
 Expression tag (<%= %>)
 Allow the developer to embed any Java expression and is
short for out.println()
Code snippet
<%!
<%=new java.util.Date()%>
%>

©FPT SOFTWARE - Corporate Training Center - Internal Use 15


Directive tags (1/3)
 Directive[chỉ thị] (<%@ directive... %>
 Give special information about the page to the JSP
container.
 Enable programmers to specify:
 Page settings (page directive):
Ex:<%@page import="java.sql.Statement"%>

 Content to include from other resources (Include directive).


Ex:<%@include file="Connection.jsp"%>

 Tag libraries to be used in the page (Tag library).


Ex:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

©FPT SOFTWARE - Corporate Training Center - Internal Use 16


Directive tags (2/3)
 Content to include from other resources (Include directive).

Code snippet
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Directive tag</title>
</head>
<body>
<%@include file="Header.jsp"%>

<hr />
<h2>This is main content</h2>
<h4 style="color: red"><%=new Date()%></h4>
<hr />

<%@include file="Footer.jsp"%>
</body>
</html>

©FPT SOFTWARE - Corporate Training Center - Internal Use 17


Directive tags (3/3)
 Tag libraries to be used in the page (Tag library).
 Add jstl lib

 Defining core tags:


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Code snippet
<h3 align="left">TRAINEE FULL INFORMATION</h3>
<table>
<tr>
<th>Id</th>
<th>Trainee Name</th>
<th>Salary</th>
</tr>
<!-- traineeData: a list of trainee -->
<c:forEach items="${traineeData}" var="trainee">
<tr>
<td>${trainee.getId()}</td>
<td>${trainee.getName()}</td>
<td>${trainee.getSalary()}</td>
</tr>
</c:forEach>
</table>
©FPT SOFTWARE - Corporate Training Center - Internal Use 18
Action tags (1/2)
 Action (<%action... %>
 JSP Actions lets you perform some action.
 Provide access to common tasks performed in a JSP:
• Including content from other resources.
• Forwarding the user to another page.
• Interacting with JavaBeans.
 Delimited by <jsp:action> and </jsp:action>.

©FPT SOFTWARE - Corporate Training Center - Internal Use 19


Action tags (2/2)
Action Description
<jsp:include> Dynamically includes another resource in a JSP. As the JSP executes,
the referenced resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static page. This
action terminates the current JSP’s execution.
<jsp:plugin> Allows a plug-in component to be added to a page in the form of a
browser-specific object or embed HTML element. In the case of a
Java applet, this action enables the downloading and installation of the
Java Plug-in, if it is not already installed on the client computer.
<jsp:param> Used with the include, forward and plugin actions to specify
additional name/value pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies
the scope of the bean and assigns it an ID that scripting components can
use to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of
this action is automatic matching of request parameters to bean
properties of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the
result to a string for output in the response.

©FPT SOFTWARE - Corporate Training Center - Internal Use 20


Include tag (1/3)
 Include action tag is used for including another resource to the
current JSP page.
 The included resource can be a static page in HTML, JSP page,
 We can also pass parameters and their values to the resource which we
are including.
 Syntax:
1) Include along with parameters.
<jsp:include page="Relative_URL_Of_Page">
<jsp:param ... />
<jsp:param ... />

</jsp:include>
2) Include of another resource without sharing parameters.
<jsp:include page="Relative_URL_of_Page" />

©FPT SOFTWARE - Corporate Training Center - Internal Use 21


Include tag (2/3)
Code snippet
<html>
<body>
<div class="main_wrap">
<div class="header">
<jsp:include page="Header.jsp"></jsp:include>
</div>
<div class="container">
<div class="side-bar">
<jsp:include page=“SideBar.jsp"></jsp:include>
</div>
<div class="content">
<jsp:include page=“Order.jsp"></jsp:include>
</div>
</div>
</div>
</body>
header
</html>

side-bar

content

©FPT SOFTWARE - Corporate Training Center - Internal Use 22


Include tag (3/3)
 Directives vs Actions:
1. Directives are used during translation phase (at translate time) while actions are
used during request processing phase (at request time).
JSP Include Directive JSP Include Action

2. If the included file is changed but not the JSP which is including it then the changes
will reflect only when we use include action tag. The changes will not reflect if you
are using include.
3. Syntax difference.
4. When using include action tag we can also pass the parameters to the included page
by using param action tag but in case of include directive it’s not possible.

©FPT SOFTWARE - Corporate Training Center - Internal Use 23


Back to menu
Forward tag (1/2)
 Forwards request processing to another JSP, servlet or static
page. This action terminates the current JSP’s execution.
 Request can be forwarded with or without parameter
 Syntax:
1) Forwarding along with parameters.
<jsp:forward page="display.jsp">
<jsp:param ... />
<jsp:param ... />

</jsp:forward>
2) Forwarding without parameters.
<jsp:forward page="Relative_URL_of_Page" />

©FPT SOFTWARE - Corporate Training Center - Internal Use 24


Forward tag (2/2)
 Without passing parameters
<html>
<head>
<title>Forward tag</title>
</head>
<body>
<p align="center">My main JSP page</p>
<jsp:forward page="OtherPage.jsp"></jsp:forward>
</body>
</html>

 With passing parameters


<html>
<head>
<title>Forward tag</title>
</head>
<body>
<p align="center">My main JSP page</p>
<jsp:forward page="OtherPage.jsp">
<jsp:param name="name" value="Chaitanya" />
<jsp:param name="tutorialname" value="Jsp forward action" />
</jsp:forward>
</body>
</html>

©FPT SOFTWARE - Corporate Training Center - Internal Use 25


Usebean tag (1/3)
 A JavaBean is a specially constructed Java class written in the Java. JavaBeans
component design conventions govern the properties of the class and govern the
public methods that give access to the properties.
Code snippet
package ctc.fr.atjb.bean;

public class Account implements Serializable {

private String emailAddress;


private String password;

public String getEmailAddress() {


return emailAddress;
}

public void setEmailAddress(String emailAddress) {


this.emailAddress = emailAddress;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}
}

©FPT SOFTWARE - Corporate Training Center - Internal Use 26


Usebean tag (2/3)
Accessing JavaBeans:
 The useBean action declares a JavaBean for use in a JSP.
 The full syntax:
<jsp: useBean id="unique_name_to_identify_bean" class="package_name.class_name" />
<jsp:setProperty name="unique_name_to_identify_bean" property="property_name" />
<jsp:getProperty name="unique_name_to_identify_bean" property="property_name" />
 Example:
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id="date" class="java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>

©FPT SOFTWARE - Corporate Training Center - Internal Use 27


Usebean tag (3/3)

Code snippet
<jsp:useBean id="account" class="ctc.fr.atjb.bean.Account">
<jsp:setProperty property="emailAddress" name="account" />
<jsp:setProperty property="password" name="account" />
<h3>
Welcome,
<jsp:getProperty property="emailAddress" name="account" /><br>
</h3>
You have been successfully Logged in...
</jsp:useBean>

©FPT SOFTWARE - Corporate Training Center - Internal Use 28


Section 3

JSP IMPLICIT OBJECTS

©FPT SOFTWARE - Corporate Training Center - Internal Use 29


Implicit Objects (1/3)
 These objects are created by JSP Engine during translation phase
(while translating JSP to Servlet)
 All the implicit objects are divided by four variable scopes:
 Application:
• Objects owned by the container application
• Any servlet or JSP can manipulate these objects
 Page:
• Objects that exist only in page in which they are defined
• Each page has its own instance of these objects
 Request:
• Objects exist for duration of client request
• Objects go out of scope when response sent to client
 Session:
• Objects exist for duration of client’s browsing Session
• Objects go out of scope when client terminates Session or when Session
timeout occurs
©FPT SOFTWARE - Corporate Training Center - Internal Use 30
Implicit Objects (2/3)
Implicit Object Description
Application Scope
application This javax.servlet.ServletContext object represents the
container in which the JSP executes.
Page Scope
config This javax.servlet.ServletConfig object represents the JSP
configuration options. As with servlets, configuration options can be
specified in a Web application descriptor.
exception This java.lang.Throwable object represents the exception that is
passed to the JSP error page. This object is available only in a JSP error
page.
out This javax.servlet.jsp.JspWriter object writes text as part
of the response to a request. This object is used implicitly with JSP
expressions and actions that insert string content in a response.
page This java.lang.Object object represents the this reference for
the current JSP instance.
pageContext This javax.servlet.jsp.PageContext object hides the
implementation details of the underlying servlet and JSP container and
provides JSP programmers with access to the implicit objects discussed
in this table.
JSP implicit objects (part 1 of 2).
©FPT SOFTWARE - Corporate Training Center - Internal Use 31
Implicit Objects (3/3)
Implicit Object Description
response This object represents the response to the client. The object normally
is an instance of a class that implements HttpServletResponse
(package javax.servlet.http). If a protocol other than HTTP is
used, this object is an instance of a class that implements
javax.servlet.ServletResponse.
Request Scope
request This object represents the client request. The object normally is an
instance of a class that implements HttpServletRequest
(package javax.servlet.http). If a protocol other than HTTP is
used, this object is an instance of a subclass of
javax.servlet.ServletRequest.
Session Scope
session This javax.servlet.http.HttpSession object represents
the client session information if such a session has been created. This
object is available only in pages that participate in a session.
JSP implicit objects (part 2 of 2).

©FPT SOFTWARE - Corporate Training Center - Internal Use 32


Implicit Objects
Request

 The JSP request is an implicit object of type HttpServletRequest i.e. created


for each jsp request by the web container.
 It can be used to get request information such as:
• parameter, header information, remote address, server name, server port, content
type, character encoding etc.
 It can also be used to set, get and remove attributes from the jsp
request scope.
 Methods:
 getParameter(String name): get the value of a request’s parameter;
 getParameterNames(): It returns enumeration of all the parameter names associated to
the
request: Enumeration enum = request.getParameterNames();
 getParameterValues(String name) : It returns the array of parameter values.
String[] allpasswords = request.getParameterValues("password");
 getAttribute(String name) – Used to get the attribute
value. request.getAttribute(“admin”) would give you the value of attribute admin.
 setAttribute(String,Object) – It assigns an object’s value to the attribute.
 getCookies() – It returns an array of cookie objects received from the client.

©FPT SOFTWARE - Corporate Training Center - Internal Use 33


Implicit Objects
Request
<h3>STOCK INFORMATION</h3>
<form action="ViewStock.jsp" method="post">
<table cellspacing="5px">
<tr>
<td>Stock Code:</td>
<td><input type="text" size="20px" name="stockCode"></td>
</tr>
<tr>
<td>Stock Name:</td>
<td><input type="text" size="20px" name="stockName"></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea rows="3px" cols="30" name="des"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" style="border-radius: 10px; width: 80px">
<input type="reset" value="Clean" style="border-radius: 10px; width: 80px">
</td>
</tr>
</table>
</form>

<!--ViewStock.jsp -->
<%
String stockCode = request.getParameter("stockCode");
String stockName = request.getParameter("stockName");
String description = request.getParameter("des");
%>
©FPT SOFTWARE - Corporate Training Center - Internal Use 34
Implicit Objects
Response

 In JSP, response is an implicit object of type HttpServletResponse.


 The instance of HttpServletResponse is created by the web container
for each jsp request.
 It can be used to add or manipulate response such as redirect response to
another resource, send error etc.
 Methods:
 void sendRedirect(String address) – It redirects the control to a new JSP
page. For e.g.
• Example: response.sendRedirect("http://beginnersbook.com");
 void addCookie(Cookie cookie) – This method adds a cookie to the
response. The below statements would add 2 Cookies Author and
Siteinfo to the response.
• Example: response.addCookie(Cookie Author); response.addCookie(Cookie Siteinfo);
 void sendError(int status_code, String message) – It is used to send
error response with a code and an error message.
• For example: response.sendError(404, "Page not found error");

©FPT SOFTWARE - Corporate Training Center - Internal Use 35


Implicit Objects
Session

 This javax.servlet.http.HttpSession object represents the client session


information if such a session has been created.
 Methods:
 setAttribute(String, object): This method is used to save an object in
session by assigning a unique string to the object.
 getAttribute(String name): The object stored by setAttribute method is
fetched from session using getAttribute method.
 removeAttribute(String name): The objects which are stored in session
can be removed from session using this method. Pass the unique string
identifier as removeAttribute’s method.
 getAttributeNames: It returns all the objects stored in session. Basically,
it results in an enumeration of objects.

©FPT SOFTWARE - Corporate Training Center - Internal Use 36


Database Connectivity
 Review:
 Provides a programming interface that is used to request a connection between the
application and database
 JDBC API executes SQL statements (in the Java code to retrieve data) and sends the
results through a single API
 Five steps to work with database:
 Load driver:
Class.forName
("com.microsoft.sqlserver.jdbc.SQLServerDriver");
 Create Connection object
String connectionUrl ="jdbc:sqlserver:
//1FWADIEUNT1-LT:1433; databaseName=MY_DB”;
Connection con= DriverManager.getConnection(
connectionUrl, “userid”, “pwd” );
 Create Statement: Statement stat = con.createStatement() ;
 Execute Query:
ResultSet resultset = stat.executeQuery(“Select * from table_name”);
 Process Results: next() method of the ResultSet object is used to process the
results
©FPT SOFTWARE fromTraining
- Corporate the database.
Center - Internal Use 37
Practical time
 Sử dụng JSP Scripting Element, JavaBean, Implicit Objects xử lý
màn hình Login và Màn hình đăng ký đã thiết kế trong bài
trước:

©FPT SOFTWARE - Corporate Training Center - Internal Use 38


Summary
◊ JSP Introduction
◊ JSP Scripting Element
◊ Implicit Objects

©FPT SOFTWARE - Corporate Training Center - Internal Use 39


Thank you

©FPT SOFTWARE - Corporate Training Center - Internal Use 40


40
JAVA SERVLET
PROGRAMMING
Instructor: DieuNT1

©FPT SOFTWARE - Corporate Training Center - Internal Use 1


Learning Goals

Can use
Servlet to
develop web
application
Understand
Servlet

©FPT SOFTWARE - Corporate Training Center - Internal Use 2


Table Content
◊ Introduction to Servlet
◊ Servlet API
◊ Servlet Request and Response
◊ Servlet Context
◊ Create servlet in Eclipse IDE

©FPT SOFTWARE - Corporate Training Center - Internal Use 3


Section 1

INTRODUCTION TO SERVLET

©FPT SOFTWARE - Corporate Training Center - Internal Use 4


Servlet Overview
 Java Servlets are programs that run on a Web or Application
server and act as a middle layer between a request coming
from a Web browser or other HTTP client and databases or
applications on the HTTP server.
 Performance is significantly better.
 Servlets are platform-independent because they are written in
Java.

©FPT SOFTWARE - Corporate Training Center - Internal Use 5


Servlet Architecture
 A Servlet is a class, which implements the javax.servlet.Servlet interface.
 To write a servlet we need to implement Servlet interface.
 Servlet interface can be implemented directly or indirectly by
extending GenericServlet or HttpServlet class.
 Purpose of extending the HttpServlet class is to provide the HTTP
specific services to your servlet.

©FPT SOFTWARE - Corporate Training Center - Internal Use 6


Servlet Architecture

©FPT SOFTWARE - Corporate Training Center - Internal Use 7


Servlet Application works
 Web container is responsible for managing execution of
servlets and JSP pages or Java EE application:
 User sends request for a servlet by clicking a link that has URL to a
servlet.
 The container finds the servlet using deployment descriptor and creates
two objects:
• HttpServletRequest
• HttpServletResponse

1 2

©FPT SOFTWARE - Corporate Training Center - Internal Use 8


Servlet Application works
 Then the container calls the Servlet's service() method and passes the
request, response objects as arguments.
 The service() method, then decides which servlet method, doGet() or
doPost() to call.
3 4

 Then the Servlet uses response object to write the response back to the
client. 5 6

©FPT SOFTWARE - Corporate Training Center - Internal Use 9


Servlet Life Cycle
 A servlet life cycle can be defined as the entire process from its creation till
the destruction.
 The following are the paths followed by a servlet:
 The servlet is initialized by calling the init () method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.

Servlet container provides the execution The Web container manages a servlet by
environment for Servlet. invoking various life cycle methods.
©FPT SOFTWARE - Corporate Training Center - Internal Use 10
Section 2

SERVLET API

©FPT SOFTWARE - Corporate Training Center - Internal Use 11


HttpServlet Class
 The HttpServlet class extends the GenericServlet class and implements
Serializable interface.
 It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
 Method doGet responds to get requests
 Retrieve the content of a URL.
 Method doPost responds to post requests
 Post data from an HTML form to a server-side form handler.
 Browsers cache Web pages.
 HttpServletRequest and HttpServletResponse objects
 Created by the servlet container and passed as an argument to the servlet's
service methods (doGet, doPost, etc.)
 HttpServletRequest object contains request from the client,
 HttpServletResponse object provides HTTP-specific functionality in sending a
response (access HTTP headers, cookies, etc.)

©FPT SOFTWARE - Corporate Training Center - Internal Use 12


HttpServlet Class
 public void service(ServletRequest req,ServletResponse res):
 dispatches the request to the protected service method by converting
the request and response object into http type.
 protected void service(HttpServletRequest req, HttpServletResponse res):
 receives the request from the service method, and dispatches the
request to the doXXX() method depending on the incoming http request
type.
 protected void doGet(HttpServletRequest req, HttpServletResponse res):
 handles the GET request. It is invoked by the web container.
 protected void doPost(HttpServletRequest req, HttpServletResponse res):
 handles the POST request. It is invoked by the web container.
 protected void doHead(HttpServletRequest req, HttpServletResponse res)
 handles the HEAD request. It is invoked by the web container.
 protected void doOptions(HttpServletRequest req, HttpServletResponse
res)
 handles the OPTIONS request. It is invoked by the web container.
 protected void doPut(HttpServletRequest req, HttpServletResponse res)
 handles the PUT request. It is invoked by the web container.

©FPT SOFTWARE - Corporate Training Center - Internal Use 13


HttpServlet Class
 protected void doTrace(HttpServletRequest req, HttpServletResponse res):
 handles the TRACE request. It is invoked by the web container.

 protected void doDelete(HttpServletRequest req, HttpServletResponse


res)
 handles the DELETE request. It is invoked by the web container.

 protected long getLastModified(HttpServletRequest req)


 returns the time when HttpServletRequest was last modified since midnight January 1,
1970 GMT.

©FPT SOFTWARE - Corporate Training Center - Internal Use 14


Section 3

SERVLET REQUEST AND RESPONSE

©FPT SOFTWARE - Corporate Training Center - Internal Use 15


HttpServletRequest
 HttpServletRequest interface adds the methods that relates to
the HTTP protocol.
 Methods (extension/addition method)

©FPT SOFTWARE - Corporate Training Center - Internal Use 16


HttpServletResponse
 HttpServletResponse interface adds the methods that relates
to the HTTP response.
 Methods (extension/addition method)

©FPT SOFTWARE - Corporate Training Center - Internal Use 17


RequestDispatcher
 RequestDispatcher is an interface, implementation of which
defines an object which can dispatch request to any
resources(such as HTML, Image, JSP, Servlet) on the server.
 Methods:

 Example:

©FPT SOFTWARE - Corporate Training Center - Internal Use 18


RequestDispatcher
redirection vs request dispatching
 The main difference between a redirection and a request
dispatching:
 redirection makes the client(browser) create a new request to get to the
resource, the user can see the new URL;
 request dispatch get the resource in same request and URL does not
changes.

©FPT SOFTWARE - Corporate Training Center - Internal Use 19


ServletContext
 An object of ServletContext is created by the web container at time of
deploying the project. This object can be used to get configuration
information from web.xml file.
 Servlet Context has 3 main methods:
 GetAttribute ()
 SetAttribute ()
 RemoveAttribute ()
 Servlet Context help provides communication between the servlet
 Servlet Context can also be used to obtain configuration information
web.xml.

©FPT SOFTWARE - Corporate Training Center - Internal Use 20


ServletContext Example

©FPT SOFTWARE - Corporate Training Center - Internal Use 21


Servlet Context
Sample

 We can change the init() method of the SurveyServlet as below:

 Then we need to amend the web.xml file to specify the initial


context parameters:

©FPT SOFTWARE - Corporate Training Center - Internal Use 22


Section 4

CREATE SERVLET IN ECLIPSE IDE

©FPT SOFTWARE - Corporate Training Center - Internal Use 23


Steps to create Servlet using Eclipse IDE
 Create a Dynamic Web Project, give a name to your project (Ex: SMS_P1)
1

A directory structure of your


Project will be automatically
created by Eclipse IDE.
©FPT SOFTWARE - Corporate Training Center - Internal Use 24
Steps to create Servlet using Eclipse IDE
Create a Servlet class by extends HttpServlet.

Add servlet-api.jar JAR


file to your project

©FPT SOFTWARE - Corporate Training Center - Internal Use 25


Handling HTTP get Requests
 Create a Servlet (WelcomeServlet.java):

Import the javax.servlet and javax.servlet.http packages.

Extends HttpServlet to handle HTTP get requests and HTTP


post requests.
doGet
Override method doGet to provide custom get request
processing.

Uses the response object’s setContentType method to specify


the content type of the data to be sent as the response to the
client.

Uses the response object’s getWriter method to obtain a


reference to the PrintWriter object that enables the servlet to
send content to the client.

Create the XHTML document by writing strings with the out


object’s println method.

Closes the output stream, flushes the output buffer and sends the
©FPT SOFTWARE - Corporate Training Center - Internal Use information to the client. 26
Create Deployement Descriptor
1 <!DOCTYPE web-app PUBLIC
Deployment
2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
3 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> descriptor
4 Element web-app defines the configuration of (web.xml) for
5 <web-app>
each servlet in the Web application and the servlet the Web
6
7 <!-- General description
mapping for each servlet.
of your Web application --> application.
8 <display-name>
Element display-name specifies a name
9 Sample
10 Servlet Examples
that can be displayed to the administrator
11 </display-name> of the server on which the Web
12 application is installed.
13 <description>
Element description specifies a
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples.
description of the Web application that
16 </description> might be displayed to the administrator of
17 the server.
18 <!-- Servlet definitions -->
19 <servlet> Element servlet describes a servlet. Element servlet-name is the
20 <servlet-name>welcome</servlet-name>
name for the servlet.
21
22 <description> Element description
23 A simple servlet that handles an HTTP get request. specifies a description for this
24 </description>
particular servlet.
25
26 <servlet-class> Element servlet-class specifies
27 atjb.day3.WelcomeServlet compiled servlet’s fully
28 </servlet-class> qualified class name.
29 </servlet>
30

©FPT SOFTWARE - Corporate Training Center - Internal Use 27


Create Deployement Descriptor
31 <!-- Servlet mappings -->
32 <servlet-mapping>
33 <servlet-name>welcome</servlet-name>
Element servlet-mapping
34 <url-pattern>/welcomeServlet</url-pattern>
specifies servlet-name and url-
pattern elements.
35 </servlet-mapping>
36
37 </web-app>

©FPT SOFTWARE - Corporate Training Center - Internal Use 28


Handling HTTP get Requests
 Jsp page in which the form’s action invokes WelcomeServlet through the
alias welcome specified in web.xml.
 Example: Welcome.jsp

©FPT SOFTWARE - Corporate Training Center - Internal Use 29


Handling HTTP post Requests
 HTTP post request
 Post data from an HTML form to a server-side form handler
 Browsers cache Web pages
 Practices time:
 Let’s try to see differences between HTTP post and HTTP get requests
 Use HTTPServletRequest’s getParameter method() to get param value

©FPT SOFTWARE - Corporate Training Center - Internal Use 30


Practices time
 Handling HTTP post Requests sample:
<form action="${pageContext.request.contextPath}/WelcomeServlet?"
method="post">

User Login

©FPT SOFTWARE - Corporate Training Center - Internal Use 31


Summary
Introduction to Servlet
Servlet API
Servlet Request and Response
Servlet Context
Create servlet in Eclipse IDE

©FPT SOFTWARE - Corporate Training Center - Internal Use 32


Thank you

©FPT SOFTWARE - Corporate Training Center - Internal Use 33


33
MVC AND JSP MODELS

Instructor:

©FPT SOFTWARE - Corporate Training Center - Internal Use 1


Table Content
What Is a MVC?
Web Application MVC Pattern
 Model
 View
 Controller

JSP Model 1, 2

©FPT SOFTWARE - Corporate Training Center - Internal Use 2


Learning Goals
After the course, attendees will be able to:
Understand MVC - JSP Models
Can use MVC – JSP Models to build Project

©FPT SOFTWARE - Corporate Training Center - Internal Use 3


What Is a MVC?
MVC stands for Model / View / Controller.
 A software pattern where logic is separated from the model
and view in order to provide for better reuse possibilities.
 A software pattern recognized in the early days of small talk.
 MVC Architecture

©FPT SOFTWARE - Corporate Training Center - Internal Use 4


Web Application MVC Pattern

1 Controller Model:
(Servlet) – Information is provided in
2 objects or beans
View:
Model
(Beans) – The JSP provide the view
3 Controller:
View 4 – Servlet provides control
View logic and becomes the
View
5 (JSPs)View
(JSPs) controller
View
(JSPs)
(JSPs)
(JSP)

©FPT SOFTWARE - Corporate Training Center - Internal Use 5


MVC - Model
The model is responsible for managing the data of the
application.
 Manages Information - If Changes
 Maps Real-World Entities
Contains data and Related Functionality
Performing DB Queries
 Calculating Business Process
Encapsulates Domain Logic which are independent of
Presentation

©FPT SOFTWARE - Corporate Training Center - Internal Use 6


MVC - View
Obtains data from model & presents to the user
Represents Output/Input of the application
Display results of Business Logic
Free Access to Model
Reads Data from Model – Using Query Methods

©FPT SOFTWARE - Corporate Training Center - Internal Use 7


MVC - Controller
Serves logical connection between user’s interaction
and the business process
It receives and translates input to request on model or
view
Input from user and instructs[chỉ thị] the model and view
to perform action
Responsible for making decision among multiple
presentation
Maps the end-user action to the application response

©FPT SOFTWARE - Corporate Training Center - Internal Use 8


Relationship between Components
View and Controller
 Controller is responsible for creating or selecting view
Model and Controller
 Controller depends on model
 If a change is made to the model then there might be
required to make parallel changes in the Controller
Model and View
 View depends on Model
 If a change is made to the model then there might be
required to make parallel changes in the view

©FPT SOFTWARE - Corporate Training Center - Internal Use 9


Logical Layers in Web Application

public class DbBean{


public string userName { get; set; }
public string password { get; set; } Model

}

<form method="post" action="Login">


<input type="text" name="txtUserName"></td>
<input type="text" name="txtUserName"></td>
… View
<td>${u.userName} </td>
<td>${u.userPassword} </td>

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)throws ServletException, IOException {
String userName = request.getParameter("txtUserName");
Contr
String userPassword = request.getParameter("txtPassword");
User u = new User(); oller
UserBO ubo = new UserBO();
u.setUserName(userName);
u.setUserPassword(userPassword);…

©FPT SOFTWARE - Corporate Training Center - Internal Use


• 10
MVC Collaboration Diagram

Controller
1: Post 2: Retrieve Data
Browser Servlet Data
Resource
3: Establish
bean state,
then place in
4: redirect to session or
appropriate view request
object

5: Access beans
JSP Beans

The View The Model

©FPT SOFTWARE - Corporate Training Center - Internal Use 11


Java 2 Web Applications
Java 2 web application options:
Servlets
 Great for Java people
 Difficult to manage graphical changes in HTML layout.
JSP
 Great for web developers
 Seductive tendency to write logic in the JSP page.

©FPT SOFTWARE - Corporate Training Center - Internal Use 12


JSP Model
 Web applications where JSP pages are used for every aspect of
the development.

Option 1 Option 2

©FPT SOFTWARE - Corporate Training Center - Internal Use 13


JSP Model 1
 A request is made to a JSP or servlet
 The JSP or servlet handles all responsibilities for the request
 processing,
 validating data,
 handling the business logic,
 and generating a response

©FPT SOFTWARE - Corporate Training Center - Internal Use 14


JSP Model 1 Observation
The Good
JSP1 JSP3
 Easiest Solution
The Bad JSP2 JSP4
 Presentation and Logic are mixed.
The Ugly
Presentation Logic
 No reuse possibilities
Ctrl Presentation
Presentation Logic
Ctrl Present.
Present. Logic

©FPT SOFTWARE - Corporate Training Center - Internal Use 15


JSP Model 1 Observation (cont.)
Advantages
 Lightweight design – for small, static application
 Suitable for small applications having very simple page flow,
little need for centralized security control and logging.
• Limitations
 Navigation Problem – to change name of JSP file have to
change in many location
 Applications are difficult to modify – large Java code being
embedded in JSP page
 Not suitable for large and complex applications

©FPT SOFTWARE - Corporate Training Center - Internal Use 16


JSP Model 2
 Web applications where JSP pages are used for the GUI aspect
of the web development
 The logic of the application is placed in the servlets it posts to.

DAO

©FPT SOFTWARE - Corporate Training Center - Internal Use 17


JSP Model 2
 Model 2 separates the display of content from the logic used to
obtain and manipulate the content.
 Advantages:
 Easier to build, maintain and extend: Suitable for large and complex
applications.
 Single point of control (Servlet) for security and logging.
 Limitations: Increase Design Complexity

©FPT SOFTWARE - Corporate Training Center - Internal Use 18


JSP Model 2 – Observation
 The Good
 Reuse opportunities: Other application may be able to use the same code.
The Bad
 There is no longer a one to one mapping from a view to a single source
of code.
 The Ugly Logic Control
 Takes more forethought.

JSP1 JSP3

JSP2

©FPT SOFTWARE - Corporate Training Center - Internal Use 19


Summary
What Is a MVC?
Web Application MVC Pattern
 Model
 View
 Controller

JSP Model 1, 2

©FPT SOFTWARE - Corporate Training Center - Internal Use 20


Thank you

©FPT SOFTWARE - Corporate Training Center - Internal Use 21


21
JSP/SERVLET ADVANCED
Instructor: DieuNT1

©FPT SOFTWARE - Corporate Training Center - Internal Use 1


Learning Goals

Can use
Servlet to
develop web
application
Understand
Servlet

©FPT SOFTWARE - Corporate Training Center - Internal Use 2


Table Content
◊ Exception Handling
◊ JSP/ Servlet Session Tracking
◊ Servlet FILTER
◊ Q&A

©FPT SOFTWARE - Corporate Training Center - Internal Use 3


Section 1

EXCEPTION HANDLING

©FPT SOFTWARE - Corporate Training Center - Internal Use 4


Exception Handling
• Exceptions are errors that can occur in a JSP page.
• isErrorPage attribute of page directive[chỉ thị] is used to
construct an error page.
• This attribute is used with the page directive at the beginning
of the JSP page.
 Value of this attribute is either true or false.
• If you want to handle the exceptions that occurs on the
execution of the JSP page you may use the page directive
attribute isErrorPage="true“.
• Syntax :
<%@ page isErrorPage=“true” %>

©FPT SOFTWARE - Corporate Training Center - Internal Use 5


Exception Handling
• The JSP page traps and handles request time errors.
• Unhandled exceptions are forwarded to the error page
• Syntax:
<%@ page errorPage=“errorpage.jsp” %>

©FPT SOFTWARE - Corporate Training Center - Internal Use 6


Exception Handling
 Translation time
 Occurs when the JSP source file is converted to servlets class file. The
JSP engine handles translation time errors.
 This translation can happen:
• After the JSP has been deployed into the JSP container and before the client requests
the JSP.
• When the client requests a JSP.

 In the first case, error processing is implementation-dependent,


and the JSP specification does not cover this.

©FPT SOFTWARE - Corporate Training Center - Internal Use 7


Exception Handling
 Request time:
 Occurs during the processing of the request. Request time errors are
the runtime errors that throw exceptions.

Code snippet
<%@ page isErrorPage="true"%> Makes JSP page an error handler
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h3>Due to following reasons an error has occurred</h3>
<ul>
<li><%=exception.getClass()%></li> Returns error message
<li><%=exception.getMessage()%></li>
</ul>
</body>
</html>

ErrorPage.jsp
©FPT SOFTWARE - Corporate Training Center - Internal Use 8
Exception Handling
Code snippet
<%@ page errorPage="ErrorPage.jsp"%> Forwards the unhandled exception to errorpage.jsp
<html>
<head>
<title>Form</title>
</head>
<body>
<form>
<table>
<tr>
<td>Enter a number :</td>
<td><input type="text" name="number" /></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
<%
String num = request.getParameter("number");
if (num != null) {
String number = num.trim();
int no = Integer.parseInt(number);
int value = 100 / no; Code occurs error
}
%>
</body>
</html>

ExceptionHandlingPage.jsp: to transfer control to the error page

©FPT SOFTWARE - Corporate Training Center - Internal Use 9


Section 2

SESSION TRACKING

©FPT SOFTWARE - Corporate Training Center - Internal Use 10


Introduction
 HTTP protocol and Web Servers are stateless, what it means is that for web
server every request is a new request to process.
 But sometimes in web applications, we should know who the client is and process the
request accordingly[phù hợp].

 Session Management is a mechanism used by the Web container to store


session information for a particular user:
 Cookies
 Hidden form field
 URL Rewriting
 HttpSession

©FPT SOFTWARE - Corporate Training Center - Internal Use 11


Session Tracking
Cookies

 Advantages
 Remember user IDs and password.
 To track visitors on a Web site for better service and new features.
 Cookies enable efficient ad processing.

 Disadvantages
 The size and number of cookies stored are limited.
 Personal information is exposed to the other users.
 Cookies fails to work if the security level is set too high in the Internet
browser.
 Servlet CookieServlet
 Handles both get and post requests

©FPT SOFTWARE - Corporate Training Center - Internal Use 12


Session Tracking
HttpSession

 The servlet API has a built-in support for session tracking.


 Session objects live on the server.
 Each user has associated an HttpSession object—one user/session
 HttpSession object operates like a hashtable

©FPT SOFTWARE - Corporate Training Center - Internal Use 13


Using Session Object
To get a user's existing or new session object:
 HttpSession session = request.getSession(true);
 "true" means the server should create a new session object
if necessary
To store or retrieve an object in the session:
 Stores values: setAttribute("cartItem", cart);
 Retrieves values: getAttribute("cartItem");

©FPT SOFTWARE - Corporate Training Center - Internal Use 14


Session Tracking
HttpSession

©FPT SOFTWARE - Corporate Training Center - Internal Use 15


Session Tracking
URL Rewriting

 Append a token or identifier to the URL. We can send parameter


name/value pairs using the following format:
url?name1=value1&name2=value2&
 When the user clicks the hyperlink, the parameter name/value pairs will be
passed to the server. We can use getParameter() method to obtain a
parameter value.
 Advantage of URL Rewriting
 It will always work whether cookie is disabled or not (browser independent).
 Extra form submission is not required on each pages.
 Disadvantage of URL Rewriting
 It will work only with links.
 It can send Only textual information.

©FPT SOFTWARE - Corporate Training Center - Internal Use 16


Session Tracking
URL Rewriting

The session ID is encoded in the URLs that are created by the JSP pages
<b>Search results for books</b>
<form method="post" action="serverprogram.jsp"> URL of server side program
// Provides check box for different products
<input type="checkbox" name="productID" value="100">
CD MP3 Converter Kit For Your CAR<br>
<input type="checkbox“ name="productID" value="101">
Front Loading Car MP3/CD Player With Anti Shock Memory and FM<br>
<input type="checkbox“ name="productID" value="102">
CAR/Home DVD/VCD/MP3 Playerwith anti shock for Indian Roads<br>
// Submits the user input to URL
<input type="submit“ name="Submit" value="Add to Cart"><br>
</form>

©FPT SOFTWARE - Corporate Training Center - Internal Use 17


Session Tracking
URL Rewriting

// URL for server side program after the user selects a product
// and goes to another page
<form method="post" action="serverprogram.jsp?productID=102">
// Provides check box for different products
<input type="checkbox" name="productID" value="150">
DVD Player with built in Amplifier <br>
<input type="checkbox" name="productID" value="160">
Ultra Slim DVD Player Multi Region 5.1 Digital<br>
// Submits input to the URL
<input type="submit" name="Submit" value="Add to Cart"> <br>
</form>

©FPT SOFTWARE - Corporate Training Center - Internal Use 18


Session Tracking
Hidden Form Fields

 We store the information in the hidden field and get it from


another servlet.
 This approach is better if we have to submit form in all the
pages and we don't want to depend on the browser.
<input type="hidden" name="uname" value="Vimal Jaiswal">
 Advantage of Hidden Form Field
 It will always work whether cookie is disabled or not.
 Disadvantage of Hidden Form Field:
 It is maintained at server side.
 Extra form submission is required on each pages.
 Only textual information can be used.
 When the user visits the next page, the server
side program reads all the parameters that a
user passes in the previous form
©FPT SOFTWARE - Corporate Training Center - Internal Use 19
Session Tracking
Hidden Form Fields

<b>Search results for books</b>


<form method="post" action="serverprogram.jsp">
// Hidden input field
<input type="hidden" name="productID" value="100">
// Provides check box for user input
<input type="checkbox" name="productID" value="150">
DVD Player with Built in Amplifier <br>
<input type="checkbox" name="productID“ value="160">
Ultra Slim DVD Player Multi Region 5.1 Digital<br>
// Submits user input to the server side program
<input type="submit" name="Submit" value="Add to Cart"><br>
</form>

©FPT SOFTWARE - Corporate Training Center - Internal Use 20


Section 3

SERVLET FILTER

©FPT SOFTWARE - Corporate Training Center - Internal Use 21


Introduction to Filter API
 Filters are compontents that you can use and configure to
perform some filtering tasks.
 Filter is used for pre-processing of requests and post-processing of
responses.

©FPT SOFTWARE - Corporate Training Center - Internal Use 22


Introduction to Filter API (2/2)
 For creating a filter, we must implement Filter interface. Filter
interface gives the following life cycle methods for a filter:
 void init(FilterConfig filterConfig): invoked by the web container to
indicate to a filter that it is being placed into service.
 void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain): invoked by the container each time a
request/response pair is passed through the chain due to a client
request for a resource at the end of the chain.
 void destroy(): invoked by the web container to indicate to a filter that it
is being taken out of service.

©FPT SOFTWARE - Corporate Training Center - Internal Use 23


Deployment Descriptor

©FPT SOFTWARE - Corporate Training Center - Internal Use 24


Practical time
In this example we are using Filter to authenticate:

LoginServlet

user_login.jsp AppFilter

©FPT SOFTWARE - Corporate Training Center - Internal Use 25


Summary
Introduction to Servlet
Servlet API
Servlet Request and Response
Servlet Context
Create servlet in Eclipse IDE
Servlet FILTER

©FPT SOFTWARE - Corporate Training Center - Internal Use 26


Thank you

©FPT SOFTWARE - Corporate Training Center - Internal Use 27


27
SPRING FRAMEWORK
Instructor: DieuNT1

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 1


Table Content

1 • Overview of the Spring Framework

2 • Spring IoC

3 • Spring Bean

4 • Dependency Injection

5 • SpEL

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 2


Learning Goals
 After the course, attendees will be able to:

Understand Spring Framework and its core technologies.

Know how to write a Web application with Spring Framework.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 3


Section 1

OVERVIEW OF THE SPRING FRAMEWORK

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 4


Introduction (1/2)
 The Spring Framework is a Java platform that provides
comprehensive infrastructure support for developing Java
applications.
 Spring framework is one of the most popular application
development frameworks used by java developers.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 5


Introduction (2/2)
It consists of a large number of modules providing a
range of services:
 Core Container;  AOP (Aspect Oriented Programming);
 Data Access/Integration;  Instrumentation;
 Web;  Messaging;
 Test.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 6


Modules (1/3)
 Data Access/Integration
 JDBC module provides a JDBC-abstraction layer
 ORM (object-relational mapping APIs): integrate with JPA, JDO,
Hibernate, and iBatis.
 OXM (Object/XML mapping) implemente for JAXB, Castor, XMLBeans,
JiBX and XStream.
 JMS (Java messaging service): producing and consuming messages.
 Transaction: supports programmatic and declarative transaction
management.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 7


Modules (2/3)
 Web
 Web: Support some features in web application such as : file upload, file
download
 Web-Servlet: contains Spring's model-view-controller (MVC)
implementation for web applications
 Web-Struts: contains the support classes for integrating a classic Struts
web tier (struts 1 or struts 2) within a Spring application
 Web-Portlet module provides the MVC implementation to be used in a
portlet environment and mirrors the functionality of Web-Servlet
module.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 8


Modules (3/3)
 AOP and Instrument
 Spring's AOP module provides an AOP Alliance-compliant aspect-oriented
programming implementation allowing you to define
 Aspects module provides integration with AspectJ.
 Instrumentation module provides class instrumentation support and
classloader implementations to be used in certain application servers.
 Test
 The Test module supports the testing of Spring components with JUnit or
TestNG

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 9


History of Spring Framework
 In October 2002 by Rod Johnson;
 He proposed a simpler solution based on
ordinary java classes (POJO – plain old java
objects) and dependency injection (DI or IoC).
 In June 2003, spring 0.9 was released
under Apache 2.0 license;

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 10


Section 2

SPRING IOC

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 11


What is Spring Inversion of Control(IoC )?
 Let’s first understand the issue, consider the following class:
package com.fsoft.bean;

public class Employee {


private int empId;
private String empName;
private String address;

public Employee() {
}

public Employee(int empId, String empName, String address) {


this.empId = empId;
this.empName = empName;
this.address = address;
}

//getter-setter methods
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 12


Spring IoC
 Standard code that without IoC
package com.fsoft.bean;
public class Client {
public static void main(String[] args) {
Employee employee = new Employee();
employee.setEmpId(1);
employee.setEmpName("John Watson");
employee.setAddress("New York");
System.out.println("Employee details: " + employee);
}
}
Employee
-----
- empId Client
- empName -----
- address + main()
------
+ getter
+ setter

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13


Spring IoC
 With IoC
 You don’t create objects. Using Bean Configuration File;
 Create an application context where we used framework
API ClassPathXmlApplicationContext().
 This API loads beans configuration file and based on the provided API, it
will create and initialize all the objects.

Employee
-----
- empId Client
- empName -----
- address Container + main()
------
+ getter
+ setter

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 14


Spring IoC Demo
 Start Coding in 5 Simple Steps

Load jar files

Bean Class

XML file

Demo Class

Run

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 15


Required Maven Dependency
 Add maven dependency in pom.xml file.
<project ...> <!-- Spring Framework -->
<properties> <dependency>
<project.build.sourceEncoding>UTF-8 <groupId>org.springframework</groupId>
</project.build.sourceEncoding> <artifactId>spring-core</artifactId>
<spring.version>4.3.10.RELEASE</spring.version> <version>${spring.version}</version>
<junit.version>4.12</junit.version> </dependency>
<servlet.version>3.1.0</servlet.version> <dependency>
</properties> <groupId>org.springframework</groupId>
<dependencies> <artifactId>spring-beans</artifactId>
<!-- Junit --> <version>${spring.version}</version>
<dependency> </dependency>
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>org.springframework</groupId>
<version>${junit.version}</version> <artifactId>spring-context</artifactId>
<scope>test</scope> <version>${spring.version}</version>
</dependency> </dependency>
<!--Servlet-Api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
</dependency>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 16


Required Maven Dependency
 Add maven dependency in pom.xml file.
<!-- Spring JDBC (if need) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- MS SQL Server (if need) -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre7</version>
</dependency>
</dependencies>
<build>
<finalName>FRESHERACADEMY</finalName>
</build>
</project>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 17


Spring IoC Demo
 Create Java Project and Load jar files

Load jar files

Bean Class

XML file

Demo Class

Run

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 18


Spring IoC Demo
 Create Bean Configuration File
package com.fsoft.bean;
Load jar files
public class Employee {
private int empId;
Bean Class private String empName;
private String address;
XML file public Employee() {
}
Demo Class public Employee(int empId, String empName, String address) {
this.empId = empId;
this.empName = empName;
Run this.address = address;
}

//getter-setter
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 19


Spring IoC Demo
 Create Bean Configuration File
Load jar files

Bean Class

XML file

Demo Class

Run

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 20


Spring IoC Demo
 Create Source Files
package com.fsoft.bean;
Load jar files
public class Client {
public static void main(String[] args) {
Bean Class
ApplicationContext context = new
ClassPathXmlApplicationContext("employeeBean.xml");
XML file
Employee emp1 = (Employee) context.getBean("emp1");
Employee emp2= (Employee) context.getBean("emp2");
Demo Class
System.out.println("Employee details: " + emp1);
System.out.println("Employee details: " + emp2);
Run }
}

Result
Initial!
Employee details: Employee [empId=1, empName=Jack, address=Eastern Shores]
Employee details: Employee [empId=2, empName=Jennie, address=Shouthern Shores]
Destroy!

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 21


IOC Container Features
IoC

The Spring IoC container by using Java POJO


classes and configuration metadata
procedures a fully configured and executable
system or application.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 22


Types Of IoC Container

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 23


Section 3

SPRING BEAN

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 24


Bean Object

Beans are the objects that form the backbone of our


application and are managed by the Spring IoC container.

Spring IoC container instantiates, assembles, and


manages the bean object.

The configuration metadata that are supplied to the


container are used create Beans object.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25


Some Bean Properties
Property Explain
class This attribute is mandatory and specify the bean class to be used to
create the bean.
name This attribute specifies the bean identifier uniquely. In XML-based
configuration metadata, you use the id and/or name attributes to
specify the bean identifier(s).
scope This attribute specifies the scope of the objects created from a
particular bean definition.
constructor-arg This is used to inject the dependencies and will be discussed in
subsequent chapters.
properties Define properties of class.

autowire mode Set autowire for bean.

lazy-initialization A lazy-initialized bean tells the IoC container to create a bean


mode instance when it is first requested, rather than at startup.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 26


class property
package com.fsoft.bean;
public class Address {
private String city;
private String street;

public Address() {

public Address(String city, String street) {


this.city = city;
this.street = street;
}

// getter-setter methods
}

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="addr" class="com.fsoft.bean.Address">


<property name="city" value="Hanoi" />
<property name="street" value="Duytan" />
</bean>
</beans>
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27
scope property
Scope Explain
singleton (Default) Scopes a single bean definition to a single object
instance per Spring IoC container.

prototype Scopes a single bean definition to any number of object


instances.

request Scopes a single bean definition to the lifecycle of a single HTTP


request; that is, each HTTP request has its own instance of a bean
created off the back of a single bean definition.
session Scopes a single bean definition to the lifecycle ofcan HTTP
Session. Only valid in the context of acweb-aware Spring
ApplicationContext.

global session Scopes a single bean definition to the lifecycle of a global HTTP
Session. Typically only valid when used in a portlet context. Only
valid in the context of a web-aware Spring ApplicationContext.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 28


scope property
Scope “singleton”

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 29


scope property
Scope “prototype”

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 30


Section 4

SPRING DI

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 31


Dependency Injection (DI)

It is a design pattern which removes the dependency from the


programming code, that makes the Application easy to manage and test.

Dependency Injection makes our programming code loosely coupled, which


means change in implementation doesn't affects the use.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 32


Spring DI
 Consider you have an application which has a employee
component and you want to identify a their address.
 Your standard code would look something like this:
public class Employee {

private int empId;


private String empName;
private Address address; // HAS-A relationship
/*private String address;*/

public Employee() {
this.empId = 0;
this.empName = "N/A";
this.address = new Address();
}
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 33


Spring DI
 Let's create a dependency between the Employee and the Address.
 In an IoC scenario, we would instead do something like this:
public class Employee {

private int empId;


private String empName;
private Address address; // HAS-A relationship

public Employee(Address address) {


super();
this.address = address;
}

public void setAddress(Address address) {


this.address = address;
}
}

 We can inject the dependancies using the setter or constructor injection.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 34


Type of Dependency Injection

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 35


Spring DI Demo
 By Constructor
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="addr" class="com.fsoft.bean.di.Address">
<property name="city" value="Hanoi" />
<property name="street" value="Duytan" />
</bean>

<bean id="emp3" class="com.fsoft.bean.di.Employee">


<property name="empId" value="3"/>
<property name="empName" value="My"/>
<property name=" address " ref="addr">/> <--setter-->

<constructor-arg name="address" ref="addr“ />


</bean>
</beans>
Using <constructor-arg> subelement to
initialize instance variables

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 36


Spring DI Demo
 By Setter
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="addr" class="com.fsoft.bean.di.Address">
<property name="city" value="Hanoi" />
<property name="street" value="Duytan" />
</bean>

<bean id="emp4" class="com.fsoft.bean.di.Employee">


<property name="empId" value="4"/>
<property name="empName" value="My"/>
<property name="address" ref="addr“ />
</bean>
</beans>

Using <property> subelement to initialize


instance variables

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 37


Spring IOC and DI
Ways of implement IOC

IOC

DI

Interface Service
Constructor Setter/Getter
Implementation Locator

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 38


Section 5

SpEL

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 39


Spring EL
 The Spring Expression Language (SpEL for short) is a powerful
expression language that supports querying and manipulating
an object graph at runtime.
The Spring EL is similar with OGNL and JSF EL, and
evaluated or executed during the bean creation time.
All Spring expressions are available via XML or
annotation.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 40


SpEL in XML based configuration
 The SpEL are enclosed with #{ SpEL expression }:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="addr" class="com.fsoft.bean.di.Address">
<property name="city" value="Hanoi" />
<property name="street" value="Duytan" />
</bean>
<bean id="employee" class="com.fsoft.bean.di.Employee">
<property name="empId" value="12"/>
<property name="empName" value="My"/>
<property name="address" value="#{addr}"></property>
</bean>
</beans>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 41


SpEL in Annotation-based configuration

package com.fsoft.bean;

import org.springframework.beans.factory.annotation.Value;

@Component("addr")
public class Address {
@Value("Hanoi")
private String city;

@Value("Duytan")
private String street;

public Address() {

}
// ...
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 42


Spring EL in Annotation
 To use SpEL in annotation, you must register your
component via annotation. If you register your bean in XML
and define @Value in Java class, the @Value will failed to
execute.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
xmlns:context="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-
3.0.xsd" >

<context:component-scan base-package="com.fsoft.bean" />


// ...
</beans?

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 43


SUMMAY

1 • Overview of the Spring Framework

2 • Spring IoC

3 • Spring Bean

4 • Dependency Injection

5 • SpEL

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 44


Thank you

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy -


45
45
Internal Use
SPRING WEB MVC FRAMEWORK

Instructor:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher


1
Academy - Internal Use
Table Content

1 • Introduction to Spring Web MVC

2 • Spring Controller

3 • Resolving Views

4 • Spring @Autowired

5 • JdbcTemplate

6 • Spring MVC First Example

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 2


Learning Goals
 After the course, attendees will be able to:

Understand Spring Web MVC Framework and its core


technologies.
Know how to write a Web application with Spring MVC
Framework.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 3


Section 1

INTRODUCTION

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 4


Introduction to Spring MVC

A part of the Spring Framework is Spring Web MVC, an extensible MVC


framework for creating web applications.

Support for Invesrsion of Control (or, the Dependency Injection).

Use DispatcherServlet that dispatches request to handler.

The default handler is based on the @Controller and @RequestMapping


annotations.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 5


An Introduction to MVC
 A Web Application developed using JSP/Servlet
Technology:

 Model : presents Data;


 View : presents UI part;
 Controller : manages the application flow, makes a call to some sort of
service producting Model and then passes on the Model to the View;

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 6


An Introduction to MVC
 A Web Application developed using SpringMVC
framework:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 7


Spring MVC Processing Sequence
•Client sends HTTP Request from the web browser to server. Inside the Web or Application server, Dispatch Servlet will be
Step1 there to handle your Http request and Processed HTTP Response.

•Handler Mapping Maps incoming HTTP Requests to handlers, In spring MVC framework we use @Request
Step2 Mapping annotation to map the incoming Http Request with Model and View Object inside the controller class.

•Controller class in spring is implemented with the help of @Controller Annotation, which does model Map with data and
extracting a view name, it can also send directly as HTTP response without mapping the incoming request with model data
Step3 object.

•The Controller class has ModelAndView objectthat has the model or Data and the view name, the Controller class
executes the incoming request by calling the respective service method and returns ModelAndView Object to
Step4 DispatcherServlet.

•The DispatcherServlet will send the view name to a ViewResolver to find the original View (.jsp) page to display.
Step5

• The DispatcherServlet will then send the model object to View in order to render the
Step6 result.

• The view (.jsp) page will show the HTTP Response back to Client on the web browser.
Step7

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 8


DispatcherServlet
 What is Spring DispatcherServlet?

is Servlet

Is designed around a central Servlet that


dispatches the request to the controller and
offers functionality that facilitates the
DispatcherServlet
development of web applications.

Is completely integrated with the Spring IoC


container and as such allows you to use every
other feature that Spring has.

 DispatcherServlet acts as front controller for Spring based web applications.


 It provides a mechanism for request processing where actual work is performed
by configurable, delegate components.
 It is inherited from javax.servlet.http.HttpServlet, it is typically configured in the
web.xml file.
43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 9
DispatcherServlet
 Configuration of DispatcherServlet in web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>/views/login.jsp</welcome-file>
</welcome-file-list>

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

<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 10


WebApplicationContext
 Spring container creates objects and associations between objects, and manages their
complete life cycle. These container objects are called Spring-managed beans (or simply
beans), and the container is called an application context (via class ApplicationContext)
in the Spring world.
 When DispatcherServlet is loaded, it looks for the bean configuration file of
WebApplicationContext and initializes it.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet-context.xml</param-value>
</context-param>

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

<servlet-mapping>
<servlet-name>dispatcher-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 11


DispatcherServlet and WebApplicationContext

 In the Web MVC framework, each DispatcherServlet has


its own WebApplicationContext, which inherits all the
beans already defined in the root WebApplicationContext.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 12


spring-servlet.xml configuration file
 WebApplicationContext will automatically look for the name as spring-
servlet.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<!--General config -->


<context:component-scan
base-package="fa.training" />

<!-- Enable annotation -->


<context:annotation-config />

<!-- Enable web mvc -->


<mvc:annotation-driven />
<!-- Include JS or CSS files in a JSP page -->
<mvc:resources mapping="/resources/**" location="/resources/" />

</beans>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 13


Section 2

SPRING CONTROLLER

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 14


Implementing Controllers
Defining a controller with @Controller
 The @Controller annotation indicates that a particular class serves the role
of a controller.
 The @Controller annotation acts as a stereotype for the annotated class,
indicating its role. The dispatcher scans such annotated classes for mapped
methods and detects @RequestMapping annotations.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 15


Implementing Controllers
 Mapping Requests With @RequestMapping
 Use the @RequestMapping annotation to map URLs such as
/appointments onto an entire class or a particular handler method.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 16


Spring Controller
 @GetMapping is specialized version of @RequestMapping annotation
that acts as a shortcut for @RequestMapping(method =
RequestMethod.GET).
 @GetMapping annotated methods handle the HTTP GET requests
matched with given URI expression. e.g.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 17


Spring Controller
 @PostMapping is specialized version of @RequestMapping annotation
that acts as a shortcut for @RequestMapping(method =
RequestMethod.POST).
 @PostMapping annotated methods handle the HTTP POST requests
matched with given URI expression. e.g.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 18


Section 3

RESOLVING VIEWS

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 19


Resolving Views
 There are 2 interfaces that are important to the way Spring
handle views: ViewResolver and View.
 The ViewResolver provides a mapping between view names and
actual views.
 The View interface addresses the preparation of the request and
hands the request over to one of the view technologies.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 20


Resolving Views
 Resolving views with the ViewResolver interface:
 Spring Web MVC controllers resolves logical view name either
explicitly (e.g., by returning a String, View, or ModelAndView) or
implicitly (i.e., based on conventions).
 In Spring, 'logical view name' represents Views and it is resolved by
a view resolver.
 Resolving views with the ViewResolver interface:
ViewResolver Description

AbstractCachingViewResolver This view resolver caches views.

XmlViewResolver This view resolver uses configuration file written in XML for
view resolution.

ResourceBundleViewResolver This view resolver use ResourceBundle, represented by bundle


base name, to resolve view. Generally bundle is defined in a
properties file, situated in the classpath.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 21


Resolving Views
ViewResolver Description

UrlBaseViewResolver This view resolver uses “logical view name” returned to find
actual view.

InternalResourceViewResolver This view resolver is the subclass of UrlBasedViewResolver and


also support InternalResourceView and also subclass such as
JstlView and TilesView.

VelocityViewResolver/ This view resolver is the subclass of UrlBasedViewResolver


FreeMarkerViewResolver which supports VelocityView, FreeMarkerView and its custom
subclass.

ContentNegotiatingViewResolver This view resolver is the implementation of the ViewResolver


interface which resolves view on the basis of request file name
or Accept header

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 22


Resolving Views
 Create spring-servlet.xml under the src/main/webapp/WEB-INF
folder and define the beans.
 Example : Configuration for InternalResourceViewResolver

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>

 Example : Configuration for TilesViewResolver

<bean id="viewResolver"
class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 23


Resolving Views: XmlViewResolver
 XmlViewResolver is used to resolve “view name” based on view beans
in the XML file.
 By default, XmlViewResolver will loads the view beans from /WEB-
INF/views.xml.
 This location can be overridden through the “location” property,
 File spring-servlet.xml:
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
</bean>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 24


Resolving Views: Controller
 A controller class, returns a view, named “WelcomePage“.

public class WelcomeController extends AbstractController{

@Override
protected ModelAndView handleRequestInternal(
HttpServletRequest request,HttpServletResponse response)
throws Exception {

ModelAndView model = new ModelAndView("WelcomePage");

return model;
}
}

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 25


Resolving Views: XmlViewResolver
 The “view bean” is just a normal Spring bean declared in
the Spring’s bean configuration file, where
 “id” is the “view name” to resolve.
 “class” is the type of the view.
 “url” property is the view’s url location.
 File : spring-views.xml
<bean id="WelcomePage"
class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/pages/WelcomePage.jsp" />
</bean>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 26


Resolving Views: ResourceBundleViewResolver
 ResourceBundleViewResolver is used to resolve “view named” based
on view beans in “.properties” file.
 By default, ResourceBundleViewResolver will loads the view beans from
file views.properties
 This location can be overridden through the “basename” property.
 File spring-servlet.xml:

<bean class="org.springframework.web.servlet.view.
ResourceBundleViewResolver">
<property name="basename" value= "spring-views" />
<property name="order" value="0" />
</bean>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 27


Resolving Views: Controller
 A controller class, returns a view, named “WelcomePage“.
public class WelcomeController extends AbstractController {

@Override
protected ModelAndView handleRequestInternal(
HttpServletRequest request,HttpServletResponse response)
throws Exception {

ModelAndView model = new ModelAndView("WelcomePage");

return model;
}
}

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 28


Resolving Views: ResourceBundleViewResolver
 Declare each view bean as a normal resource bundle style (key &
message), where
 “WelcomePage” is the view name to match.
 “.(class)” is the type of view.
 “.url” is the view’s URL location.
 File spring-views.properties:

course_list.(class) = org.springframework.web.servlet.view.JstlView
course_list.url = /views/pages/course_list.jsp
WelcomePage.(class) = org.springframework.web.servlet.view.JstlView
WelcomePage.url = /views/pages/WelcomePage.jsp

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 29


Spring MVC Using Java Configuration
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "fa.training.controller" })
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 30


Spring MVC Using Java Configuration
Annotation configuration:
 @EnableWebMvc: enables default Spring MVC configuration and
registers Spring MVC infrastructure components expected by the
DispatcherServlet.
 @Configuration: indicates that a class declares one or
more @Bean methods and may be processed by the Spring container
to generate bean definitions and service requests for those beans at
runtime.
 @ComponentScan annotation is used to specify the base packages to
scan. Any class which is annotated with @Component and
@Configuration will be scanned.
 InternalResourceViewResolver helps in mapping the logical view
names to directly view files under a certain pre-configured directory.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 31


Section 3

SPRING @AUTOWIRED

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 32


Enabling @Autowired Annotations
 The Spring framework enables automatic dependency injection.
 By declaring all the bean dependencies in a Spring configuration file,
Spring container can autowire relationships between collaborating
beans. This is called Spring bean autowiring.
 To use Java-based configuration in our application, let's enable
annotation-driven injection to load our Spring configuration:
@Configuration
@ComponentScan(basePackages = { "fa.training.controller" })
public class WebMvcConfig {}

//or to activate the dependency injection annotations in Spring XML files.

<context:component-scan base-package=" fa.training.controller"/>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 33


@Autowired on Properties
 Let’s see how we can annotate a property using @Autowired. This
eliminates the need for getters and setters.
 First, let's define a fooFormatter bean:

 Then, we'll inject this bean into the FooService bean


using @Autowired on the field definition:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 34


@Autowired on Setters and Constructors
 The setter method is called with the instance of FooFormatter when
FooService is created:

 An instance of FooFormatter is injected by Spring as an argument to


the FooService constructor:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 35


Spring MVC Autowire
 With Standard code:
AddressController

AddressServiceImpl AddressService
------ ------
+ getAllAddress() + getAllAddress()

public class AddressController {


AddressService addressService = new AddressServiceImpl();

public List<Address> getAllAddress(){


return addressService.getAllAddress();
}
}

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 36


Spring Web MVC Autowire
 With Autowire:
AddressController

AddressServiceImpl AddressService
------ ------
+ getAllAddress() + getAllAddress()

@Controller
public class AddressController {

@Autowired
private AddressService addressService;

@RequestMapping(value="/addressList", method= RequestMethod.GET)


public String getAllAddress(ModelMap modelMap){
List<Address> listOfAddress = addressService.getAllAddress();
modelMap.addAttribute("addresses", listOfAddress);

return "address_list";
}
}
43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 37
Section 4

SPRING JDBCTEMPLATE

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 38


Spring JdbcTemplate
 Spring JdbcTemplate is a powerful mechanism to connect
to the database and execute SQL queries.
Problems of We need to write a lot of code before and after executing the
JDBC API: query, such as creating connection, statement, closing
resultset, connection etc.
We need to perform exception handling code on the database
logic.

We need to handle transaction.

Repetition of all these codes from one to another database


logic is a time consuming task.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 39


Spring Jdbc Approaches
 Spring framework provides following approaches for JDBC
database access:
 JdbcTemplate
 NamedParameterJdbcTemplate
 SimpleJdbcTemplate
 SimpleJdbcInsert and SimpleJdbcCall

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 40


JdbcTemplate class

It is the central class in the Spring JDBC support classes.

It takes care of creation and release of resources such as creating and closing of
connection object etc. So it will not lead to any problem if you forget to close the
connection.

It handles the exception and provides the informative exception messages by the
help of excepion classes defined in the org.springframework.dao package.

We can perform all the database operations by the help of JdbcTemplate class
such as insertion, updation, deletion and retrieval of the data from the database.

Let's see the methods of spring JdbcTemplate class.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 41


JdbcTemplate class
Method Description
public int update(String query) is used to insert, update and delete records.

public int update(String query, is used to insert, update and delete records using
Object... args) PreparedStatement using given arguments.
public void execute(String query) is used to execute DDL query.

public T execute(String sql, executes the query by using PreparedStatement callback.


PreparedStatementCallback action)
public T query(String sql, is used to fetch records using ResultSetExtractor.
ResultSetExtractorrse)

public List query(String sql, is used to fetch records using RowMapper.


RowMapper rse)

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 42


DriverManagerDataSource class
 The DriverManagerDataSource is used to contain the information
about the database such as driver class name, connnection URL,
username and password.
 Need to provide the reference of DriverManagerDataSource object in the
JdbcTemplate class for the datasource property.
 Declare datasource bean:

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


<property name="dataSource" ref="dataSource" />
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName“
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://1WDDIEUNT1-LT:1433;databaseName=FAMS" />
<property name="username" value="sa" />
<property name="password" value="12345678" />
</bean>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 43


Section 5

SPRING MVC FIRST EXAMPLE

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 44


Spring MVC First Example
There are given 5 steps for creating the spring MVC
application.
The steps are as follows:
 Create the request /respone pages
 Create the bean/controller/service/dao class
 Provide the entry of controller in the web.xml file
 Define the bean in the xml file
 Start server and deploy the project

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 45


Directory Structure using Maven

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 46


Required Maven Dependency
 Add maven dependency in pom.xml file.
<properties>
<spring.version>5.2.10.RELEASE</spring.version>
</properties> Áp dụng cho XML
<dependency> Configuration
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 47


Required Maven Dependency
 Add maven dependency in pom.xml file.
<!-- Spring JDBC -->  You can add the needful dependencies.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- MS SQL Server -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>7.4.1.jre8</version>
</dependency>
</dependencies>
<build>
<finalName>FRESHERACADEMY</finalName>
</build>
</project>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 48


Table definition
 We are assuming that you have created the following table
inside the FAMS database.
CREATE TABLE [dbo].[Users](
[user_id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[user_name] [varchar](50) NOT NULL,
[email] [varchar](50) NOT NULL,
[password] [varchar](50) NOT NULL,
[enabled] TINYINT NOT NULL DEFAULT 1
)

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 49


(1) Create the request/respone pages
 Create login.jsp:
<body>
<form action="login" method="post" name="loginForm">
User Name: <input type="text" name="userName">
Password: <input type="password" name="password">
<input type="submit" value="Login">
</form>
</body>

 And index.jsp:
<body>
<h2>Welcome <span>${userName}</span>! </h2>
</body>
</html>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 50


(2) Create the bean class

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 51


(2) Create the controller class

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 52


(2) Create the service class

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 53


(2) Create the dao class

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 54


(3) Provide the entry of controller in the web.xml file

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 55


(4) Define the bean in the xml file
 Create spring-servlet.xml under the /WEB-INF folder and define the
beans.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 56


(4) Define the bean in the xml file

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 57


(5) Start server and deploy the project

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 58


(5) Start server and deploy the project

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 59


SUMMAY

• Introduction to Spring Web MVC


1

• Spring Autowrite
2

• JdbcTemplate
3

• Spring MVC First Example


4

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 60


Thank
you

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher


61
61
Academy - Internal Use
HIBERNATE AND
SPRING MVC INTEGRATION
Instructor:

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 1


Table Content
•@ModelAttribute annotation, Model, ModelMap class
1
•Spring JdbcTemplate
2
•Spring Web MVC and Hibernate ORM
3

•Spring @Pathvariable Annotation


4
•Build a simple Web App (CRUD)
5

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 2


Learning Goals
 After the course, attendees will be able to:

Understand Spring Web MVC Framework and Hibernate


ORM Integration.
Know how to write a Web application.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 3


Section 1
- @MODELATTRIBUTE ANNOTATION
- MODEL, MODELMAP AND MODELANDVIEW CLASSES

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 4


@ModelAttribute Annotation
 The @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.
 Method Argument:
 When used as a method argument, it indicates the argument should be
retrieved from the model: the arguments fields should be populated from
all request parameters that have matching names.
 Example: In the code snippet that follows the employee model attribute is
populated with data from a form submitted to the saveEmployee endpoint.

@RequestMapping(value = "/saveEmployee", method = RequestMethod.POST)


public String submit(@ModelAttribute("employee") Employees employee) {
// Code that uses the employee object

return "employeeView";
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 5


@ModelAttribute Annotation
 Method Level:
 When the annotation is used at the method level it indicates the
purpose of that method is to add one or more model attributes.

@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("msg",
"Welcome to the Netherlands!");
}

 Spring-MVC will always make a call first to that method, before it


calls any request handler methods.
 That is, @ModelAttribute methods are invoked before the controller
methods annotated with @RequestMapping are invoked.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 6


Model class
 The model works a container that contains the data of the application. A
data can be in any form such as objects, strings, information from the
database, etc.
 The model can supply attributes used for rendering views.
 To provide a view with usable data, we simply add this data to
its Model object.
 Maps with attributes can be merged with Model instances:

@GetMapping("/showViewPage")
public String passParametersWithModel(Model model) {
Map<String, String> map = new HashMap<>();
map.put("spring", "mvc");
model.addAttribute("message", “Welcome to Spring framework");
model.mergeAttributes(map);
return "viewPage";
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 7


ModelMap class
 Just like the Model interface above, ModelMap is also used to pass
values to render a view.
 The advantage of ModelMap is it gives us the ability to pass a collection
of values and treat these values as if they were within a Map.
 ModelMap class subclasses LinkedHashMap. It add some methods for
convenience.
 ModelMap uses as generics and checks for null values.
@RequestMapping("/helloworld")
public String hello(ModelMap map) {
String helloWorldMessage = "Hello world from FA!";
String welcomeMessage = "Welcome to FA!";
map.addAttribute("helloMessage", helloWorldMessage);
map.addAttribute("welcomeMessage", welcomeMessage);

return "hello";
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 8


ModelAndView
 This interface allows us to pass all the information required
by Spring MVC in one return.
@GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
ModelAndView modelAndView = new ModelAndView("viewPage");
modelAndView.addObject("message", "Welcome to FA");
return modelAndView;
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 9


Section 2

@COMPONENT VS @REPOSITORY
AND @SERVICE IN SPRING

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 10


Introduction
 In most typical applications, we have distinct layers like data access,
presentation, service, business, etc.
 In each layer, we have various beans. Simply put, to detect them
automatically. Spring uses classpath scanning annotations. Then, it
registers each bean in the ApplicationContext.
 @Component: is a generic stereotype for any Spring-managed
component.
 @Service: annotates classes at the service layer
 @Repository: annotates classes at the persistence layer, which will
act as a database repository.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 11


Examples:
 @Service:
public interface UserService {
User login(User user) throws Exception;
}
@Service("userService")
public class UserServiceImpl implements UserService {
// TODO Auto-generated method stub
}

 @Repository
public interface UserDao {
User login(User user) throws Exception;
}

@Repository("userDao")
@Transactional
public class UserDaoImpl implements UserDao {

@Autowired
private SessionFactory sessionFactory;
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 12


Section 3

SPRING JDBCTEMPLATE

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 13


Spring JdbcTemplate
 Spring JdbcTemplate is a powerful mechanism to connect
to the database and execute SQL queries.
Problems of We need to write a lot of code before and after executing the
JDBC API: query, such as creating connection, statement, closing
resultset, connection etc.
We need to perform exception handling code on the database
logic.

We need to handle transaction.

Repetition of all these codes from one to another database


logic is a time consuming task.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy -


14
Internal Use
Spring Jdbc Approaches
 Spring framework provides following approaches for JDBC
database access:
 JdbcTemplate
 NamedParameterJdbcTemplate
 SimpleJdbcTemplate
 SimpleJdbcInsert and SimpleJdbcCall

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy -


15
Internal Use
JdbcTemplate class

It is the central class in the Spring JDBC support classes.

It takes care of creation and release of resources such as creating and closing of
connection object etc. So it will not lead to any problem if you forget to close the
connection.

It handles the exception and provides the informative exception messages by the
help of excepion classes defined in the org.springframework.dao package.

We can perform all the database operations by the help of JdbcTemplate class
such as insertion, updation, deletion and retrieval of the data from the database.

Let's see the methods of spring JdbcTemplate class.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy -


16
Internal Use
JdbcTemplate class
Method Description
public int update(String query) is used to insert, update and delete records.

public int update(String query, is used to insert, update and delete records using
Object... args) PreparedStatement using given arguments.
public void execute(String query) is used to execute DDL query.

public T execute(String sql, executes the query by using PreparedStatement callback.


PreparedStatementCallback action)
public T query(String sql, is used to fetch records using ResultSetExtractor.
ResultSetExtractorrse)

public List query(String sql, is used to fetch records using RowMapper.


RowMapper rse)

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy -


17
Internal Use
DriverManagerDataSource class
 The DriverManagerDataSource is used to contain the information
about the database such as driver class name, connnection URL,
username and password.
 Need to provide the reference of DriverManagerDataSource object in the
JdbcTemplate class for the datasource property.
 Declare datasource bean:

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


<property name="dataSource" ref="dataSource" />
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName“
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://1WDDIEUNT1-LT:1433;databaseName=FAMS" />
<property name="username" value="sa" />
<property name="password" value="12345678" />
</bean>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy -


18
Internal Use
Section 4

HIBERNATE AND SPRING MVC INTEGRATION

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 19


Add dependencies

<!-- Spring ORM -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 20


Create a Data Source Bean
 Spring provides many ways to establish connection to a database and
perform operations such as retrieval of records, insertion of new
records and updating / deletion of existing records.
 The most basic of them is using DriverManagerDataSource.

<!-- DataSourse -->


<bean id="dataSource“
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://localhost:1433;
databaseName=HumanResourceDB" />
<property name="username" value="sa" />
<property name="password" value="12345678" />
</bean>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 21


Create a Session Factory Bean
 For using Hibernate 5 with Spring, we have to
use org.springframework.orm.hibernate5.LocalSessionFactoryBean.

<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource"
ref="dataSource" /> <!-- Dependency Injection -->
<property name="packagesToScan" value="fa.training.entities" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 22


Transaction Management
 Enable the transaction support:
<tx:annotation-driven
transaction-manager="transactionManager" />

<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 23


@Transactional
 With Spring @Transactional, the above code gets reduced to simply
this:

@Transactional
public void businessLogic() {
... use entity manager inside a transaction ...
}

 By using @Transactional, many important aspects such as transaction


propagation are handled automatically.
 In this case if another transactional method is called by
businessLogic(), that method will have the option of joining the ongoing
transaction.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 24


Entity class
 Create User class:
@Entity
@Table(name = "USERS")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")
private long userId;

@Pattern(regexp="^[A-Za-z0-9_]+$", message="{user.name.rex}")
@Size(max = 30, min = 8, message = "{user.name.invalid}")
@NotEmpty(message = "Please enter username")
@Column(name = "USERNAME", nullable = false, unique = true)
private String username;

@Column(name = "PASSWORD")
private String password;

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)


// @PrimaryKeyJoinColumn
private UserDetail userDetail;

// constructors and getter/setter methods

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25


Service classes
 Create service class:
public interface UserService {
void save(User user);

List<User> list();
}

@Service
public class UserServiceImp implements UserService {
@Autowired
private UserDao userDao;

public void save(User user) {


userDao.save(user);
}

public List<User> list() {


return userDao.list();
}
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 26


DAO classes
 Create DAO class:
public interface UserDao {
void save(User user);
List<User> list();
}

@Repository
@Transactional
public class UserDaoImp implements UserDao {

@Autowired
private SessionFactory sessionFactory;

@Override
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}

@Override
public List<User> list() {
TypedQuery<User> query = sessionFactory.getCurrentSession()
.createQuery("from User");
return query.getResultList();
}
}
09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27
Build a simple Web App
 Demo!

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 28


Section 5

SPRING @PATHVARIABLE ANNOTATION

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 29


A Simple Mapping
 The @PathVariable annotation can be used to handle template
variables in the request URI mapping, and use them as method
parameters.
 A simple use case of the @PathVariable annotation would be an
endpoint that identifies an entity with a primary key:

@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesById(@PathVariable String id) {
return "ID: " + id;
}

 A simple GET request to /api/employees/{id} will invoke getEmployeesById with


the extracted id value:

http://localhost:8080/api/employees/111
---- ID: 111

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 30


Specifying the Path Variable Name
 If the path variable name is different, we can specify it in the
argument of the @PathVariable annotation:

@GetMapping("/api/employeeswithvariable/{id}")
@ResponseBody
public String getEmployeesByIdWithVariableName(@PathVariable("id")
String employeeId) {
return "ID: " + employeeId;
}

 We can also define the path variable name


as @PathVariable(value=”id”) instead of PathVariable(“id”) for clarity.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 31


Multiple Path Variables in a Single Request
 Depending on the use case, we can have more than one path variable
in our request URI for a controller method, which also has multiple
method parameters:

@GetMapping("/api/employees/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndName(@PathVariable String id,
@PathVariable String name) {
return "ID: " + id + ", name: " + name;
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 32


Multiple Path Variables in a Single Request
 We can also handle more than one @PathVariable parameters
using a method parameter of type java.util.Map<String, String>:
@GetMapping("/api/employeeswithmapvariable/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndNameWithMapVariable(
@PathVariable Map<String, String> pathVarsMap) {
String id = pathVarsMap.get("id");
String name = pathVarsMap.get("name");
if (id != null && name != null) {
return "ID: " + id + ", name: " + name;
} else {
return "Missing Parameters";
}
}

 Example:

http://localhost:8080/api/employees/1/bar
---- ID: 1, name: bar

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 33


@PathVariable as Not Required
 Since method parameters annotated by @PathVariables are mandatory
by default, it doesn't handle the requests sent
to /api/employeeswithrequired path:
 You can set required = false:
@GetMapping(value = { "/api/employeeswithrequiredfalse",
"/api/employeeswithrequiredfalse/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequiredFalse(
@PathVariable(required = false) String id) {
if (id != null) {
return "ID: " + id;
} else {
return "ID missing";
}
}

http://localhost:8080/api/employeeswithrequiredfalse
---- ID missing

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 34


SUMMAY

•@ModelAttribute annotation, Model, ModelMap class


1

2
•Spring JdbcTemplate

3
•Spring Web MVC and Hibernate ORM

4
• Spring @Pathvariable Annotation

5
•Build a simple Web App (CRUD)

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 35


Thank you

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 36


SPRING MVC FRAMEWORK
COMPONENTS
Instructor:

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 1


Table Content
• Spring @RequestParam Annotation
1

• Spring Form tags


2

• @SessionAttributes or @SessionAttribute
3

• Spring Expression Language (SpEL)


4

• RedirectView and RedirectAttributes


5

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 2


Learning Goals
 After the course, attendees will be able to:

Understand Spring Web MVC Framework and its core


technologies.
Know how to write a Web application with Spring MVC
Framework.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 3


Section 1

SPRING @REQUESTPARAM ANNOTATION

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 4


A Simple Mapping
 We can use @RequestParam to extract query parameters,
form parameters, and even files from the request.
 In this example, we used @RequestParam to extract
the id query parameter.
@GetMapping("/api/foos")
public String getFoos(@RequestParam String id) {
return "ID: " + id;
}

 A simple GET request would invoke getFoos:


http://localhost:8080/api/foos?id=abc
----ID: abc

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 5


Specifying the Request Parameter Name
 Sometimes we want these to be different, though.
 Fortunately, we can configure the @RequestParam name using
the name attribute:

@PostMapping("/api/foos")
public String addFoo( @RequestParam(name = "id") String fooId,
@RequestParam String name) {
return "ID: " + fooId + " Name: " + name;
}

 We can also do @RequestParam(value = “id”) or just @RequestParam(“id”).

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 6


Optional Request Parameters
 Method parameters annotated with @RequestParam are
required by default.
 This means that if the parameter isn’t present in the request,
we'll get an error:
GET /api/foos HTTP/1.1
-----
400 Bad Request
Required String parameter 'id' is not present

 We can configure our @RequestParam to be optional,


though, with the required attribute:
@GetMapping("/api/foos")
public String getFoos(@RequestParam(required = false)
String id) {
return "ID: " + id;
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 7


Optional Request Parameters
 In this case, both:
http://localhost:8080/api/foos?id=abc
----ID: abc
And
http://localhost:8080/api/foos
----ID: null

 will correctly invoke the method.


 When the parameter isn't specified, the method parameter is
bound to null.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 8


Using Java 8 Optional
 Alternatively, we can wrap the parameter in Optional:
@GetMapping("/api/foos")
public String getFoos(@RequestParam Optional<String> id) {
return "ID: " + id.orElseGet(() -> "not provided");
}

 In this case, we don't need to specify the required


attribute.
 And the default value will be used if the request parameter is
not provided:

http://localhost:8080/api/foos
---- ID: not provided

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 9


Mapping a Multi-Value Parameter
 A single @RequestParam can have multiple values:
@GetMapping("/api/foos")
public String getFoos(@RequestParam List<String> id) {
return "IDs are " + id;
}

 And Spring MVC will map a comma-delimited id


parameter:
http://localhost:8080/api/foos?id=1,2,3
----IDs are [1,2,3]
 or a list of separate id parameters:
http://localhost:8080/api/foos?id=1&id=2
----IDs are [1,2]

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 10


Section 2

SPRING MVC JSP FORM TAGS

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 11


Introduction
 Spring provides a comprehensive set of data binding-aware
tags for handling form elements when using JSP and Spring
Web MVC, such as form tag, text fields tag, select tag,
check-box(s), radio box(s), password tag, button tag, errors
tag etc.
 Spring’s form tag library
•The form tag •The select tag
•The input tag •The option tag
•The checkbox tag •The options tag
•The checkboxes tag •The textarea tag
•The radiobutton tag •The hidden tag
•The radiobuttons tag •The errors tag
•The password tag •HTML5 tags

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 12


Spring MVC Form Tags
 To use the tags from this library, add the following directive
to the top of your JSP page:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

 The form tag


 This tag renders an HTML 'form' tag and exposes a binding path to
inner tags for binding.
 It puts the command object in the PageContext so that the command
object can be accessed by inner tags. All the other tags in this library
are nested tags of the form tag.
 When the form is loaded, spring MVC will class
user.getFirstName() and getLastName() (getter methods).
 When the form is submitted, Spring MVC will call
user.setFirstName() and user.setLastName() methods.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13


Spring MVC Form Tags
 Example:
<form:form modelAttribute = "user">
<table>
<tr>
<td>First Name:</td>
<td>
<form:input path="firstName" />
</td>
</tr>
<tr>
<td>Last Name:</td>
<td>
<form:input path="lastName" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 14


The checkbox tag
 This tag renders an HTML 'input' tag with type 'checkbox'.
 Give an entity class:
Entity
@Table(name = "Preferences")
public class Preferences {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "receive_news_letter")
private boolean receiveNewsletter;
private String[] interests;
@Column(name = "favourite_word")
private String favouriteWord;

// constructors and getter/setter methods


}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 15


The checkbox tag
 Form:
<form:form method="POST" action="${pageContext.request.contextPath}/subscription"
modelAttribute="preferences">
<table>
<tr>
<td>Subscribe to newsletter?:</td>
<%-- Approach 1: Property is of type java.lang.Boolean --%>
<td><form:checkbox path="receiveNewsletter" /></td>
</tr>

<tr>
<td>Interests:</td>
<%-- Approach 2: Property is of an array or of type java.util.Collection --%>
<td>Quidditch:
<form:checkbox path="interests" value="Quidditch" />
Herbology:
<form:checkbox path="interests" value="Herbology" />
Defence Against the Dark Arts:
<form:checkbox path="interests" value="Defence Against the Dark Arts" />
</td>
</tr>

<tr>
<td>Favourite Word:</td>
<%-- Approach 3: Property is of type java.lang.Object --%>
<td>Magic:
<form:checkbox path="favouriteWord" value="Magic" />
</td>
</tr>

</table>
</form:form>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 16


Controller
 Controller class:
@Controller
public class PreferencesController {

@PostMapping("/subscription")
public String subcription(
@ModelAttribute("preferences") Preferences preferences,
Model model) {
LogUtils.getLogger().info(preferences);

return "newsletter_subscription";
}

 Results:

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 17


The checkboxes tag
 This tag renders multiple HTML 'input' tags with type
'checkbox'.
<form:form>
<table>
<tr>
<td>Interests:</td>
<td>
<%-- Property is of an array or of type java.util.Collection --%>
<form:checkboxes path="preferences.interests" items="${interestList}" />
</td>
</tr>
</table>
</form:form>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 18


The radiobutton and radiobuttons tags
 radiobutton tag renders an HTML 'input' tag with type
'radio'.
<tr>
<td>Gender:</td>
<td>Male: <form:radiobutton path="gender" value="M" /> <br />
Female: <form:radiobutton path="gender" value="F" />
</td>
</tr>

 radiobuttons tag renders multiple HTML 'input' tags with


type 'radio'. For example:
<tr>
<td>Gender:</td>
<td>
<form:radiobuttons path="gender" items="${genderOptions}" />
</td>
</tr>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 19


The select tag
 This tag renders an HTML 'select' element.
 It supports data binding to the selected option as well as the
use of nested option and options tags.
<tr>
<td>Skills:</td>
<td><form:select path="skills" items="${skills}" /></td>
</tr>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 20


Section 3

@SESSIONATTRIBUTES OR
@SESSIONATTRIBUTE

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 21


Introduction
 When developing web applications, we often need to refer to
the same attributes in several views.
 For example, we may have shopping cart contents that
need to be displayed on multiple pages.
 A good location to store those attributes is in the user's
session.
 Have 2 different strategies for working with a session
attribute:
 Using a scoped proxy
 Using the @SessionAttributes annotation

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 22


@SessionAttributes
 @SessionAttributes annotation is used to store the model attribute in
the session. This annotation is used at controller class level.
@SessionAttributes("user")
public class LoginController {
@ModelAttribute("user")
public User setUpUserForm() {
return new User();
}
}
 @SessionAttribute annotation is used to retrieve the existing attribute
from session that is managed globally and it is used at method
parameter as shown follows.
@GetMapping("/info")
public String userInfo(@SessionAttribute("user") User user) {
//... //... return "user";
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 23


Controller
@Controller
@SessionAttributes("user")
public class UserController {

/**
* Add user in model attribute.
*/
@ModelAttribute("user")
public User setUpUserForm() {
return new User();
}

@PostMapping("/dologin")
public String doLogin(@ModelAttribute("user") User user, Model model) {

// Implement your business logic


if ("admin".equals(user.getUsername())
&& "admin".equals(user.getPassword())) {

return "index";
} else {
model.addAttribute("message", "Login failed. Try again.");
return "login";
}
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 24


Controller
/*
* Get user from session attribute
*/
@GetMapping("/info")
public String userInfo(@SessionAttribute("user") User user) {

System.out.println("User Name: " + user.getUsername());

return "index";
}
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25


View
 Login.jsp
<form:form action="${pageContext.request.contextPath}/dologin" method="post" modelAttribute="user">
<h2 class="text-center">Log in</h2>
<label style="color: red">${errorMessage}</label><!-- JSP Expression -->
<div class="form-group">
<input type="text" name="username" class="form-control"
placeholder="Username" required="required">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control"
placeholder="Password" required="required">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Log in</button>
</div>
<div class="clearfix">
<label class="float-left form-check-label"><input type="checkbox"> Remember me</label>
<a href="#" class="float-right">Forgot Password?</a>
</div>
</form:form>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 26


Section 4

SPRING EXPRESSION LANGUAGE (SpEL)

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27


Introduction
 Spring Expression Language (SpEL) is a powerful
expression language, which can be used for querying and
manipulating an object graph at runtime.
 SpEL supports standard mathematical operators, relational
operators, logical operators, conditional operators, collections and
regular expressions, etc.
 It can be used to inject a bean or a bean property into another bean.
 Method invocation of a bean is also supported.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 28


SpEL Examples
 Example 1: The logical operators, (&&) or (||) and not (!), are supported.
The textual equivalents can also be used.
 (1) First let’s define the MyOtherGlass POJO:
package fa.training.entities;

public class MyOtherGlass {


private boolean empty;
private boolean halfEmpty;
private int volume;
private int maxVolume;
private boolean largeGlass;

public MyOtherGlass() {

}
// getter and setter moethod
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 29


SpEL Examples
 (2) Let’s now create our spring configuration file where we define the
smallGlass bean and the largeGlass bean.

<bean id="smallGlass" class="fa.training.entities.MyOtherGlass">


<constructor-arg name="volume" value="5" />
<constructor-arg name="maxVolume" value="10" />
<property name="largeGlass"
value="#{smallGlass.maxVolume ge 20 and
smallGlass.maxVolume le 30}" />
</bean>

<bean id="largeGlass" class="fa.training.entities.MyOtherGlass">


<constructor-arg name="volume" value="5" />
<constructor-arg name="maxVolume" value="30" />
<property name="largeGlass"
value="#{largeGlass.maxVolume ge 20 and
largeGlass.maxVolume le 30}" />
</bean>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 30


SpEL Examples
 (3) Test
LogUtils.getLogger().info(smallGlass.isLargeGlass());

LogUtils.getLogger().info(largeGlass.isLargeGlass());

 Results:
[INFO ] 2020-11-14 15:12:47.678 [http-nio-8080-exec-2]
LogUtils - false
[INFO ] 2020-11-14 15:12:47.680 [http-nio-8080-exec-2]
LogUtils - true

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 31


SpEL Examples
 Example 2:
<bean id="officeAddress" class="fa.training.entities.Address">
<property name="number" value = "101" />
<property name="street" value = "#{'M I Road'}" />
<property name="city" value = "Jaipur" />
<property name="state" value = "Rajasthan" />
<property name="pinCode" value = "#{'302001'}" />
</bean>

<bean id="employee" class="fa.training.entities.Employee">


<property name="empId" value = "1001" />
<property name="empName" value = "Ram" />
<!-- Bean reference through SpEL -->
<property name="officeAddress" value = "#{officeAddress}" />
<property name="officeLocation" value = "#{officeAddress.city}" />
<!-- Method invocation through SpEL -->
<property name="employeeInfo" value = "#{officeAddress.getAddress('Ram')}" />
</bean>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 32


SpEL - properties files
 Create DBConfig.properties file:
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=DBName
username=sa
password=12345678

 spring-servlet.xml file:
<!– Properties Spring -->
<bean class="org.springframework.beans.factory.config
.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:DBConfig.properties</value>
</list>
</property>
</bean>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 33


SpEL - properties files
 spring-servlet.xml file:
 The context:property-placeholder tag is used to externalize
properties in a separate file.
 It automatically configures PropertyPlaceholderConfigurer, which
replaces the ${} placeholders, which are resolved against a specified
properties file (as a Spring resource location).

<context:property-placeholder
location="classpath:data.properties, classpath:DBConfig.properties"
ignore-unresolvable="true" />

 Default resource location: src/main/resources.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 34


SpEL - properties files
 spring-servlet.xml file:
<!-- DataSourse -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.
DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 35


SpEL Using Annotation
 SpEL expressions begin with the # symbol, and are wrapped in braces:
#{expression}.
 Properties can be referenced in a similar fashion, starting with a $
symbol, and wrapped in braces: ${property.name}.
@Value("#{19 + 1}") // 20
private double add;

@Value("#{'String1 ' + 'string2'}") // "String1 string2"


private String addString;

@Value("#{20 - 1}") // 19
private double subtract; @Value("#{36 div 2}") // 18, the same as for / operator
private double divideAlphabetic;
@Value("#{10 * 2}") // 20
private double multiply; @Value("#{37 % 10}") // 7
private double modulo;
@Value("#{36 / 2}") // 19
private double divide; @Value("#{37 mod 10}") // 7, the same as for % operator
private double moduloAlphabetic;

@Value("#{2 ^ 9}") // 512


private double powerOf;

@Value("#{(2 + 2) * 2 + 9}") // 17
private double brackets;

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 36


SpEL Using Annotation
 Example: The @Component annotation for registering the
bean and @Value for setting values into bean properties.
@Component @Component
public class Address { public class Person {
@Value("100") @Value("#{'Suresh'}")
private String houseNo; private String name;
@Value("The Mall") @Value("34")
private String street; private int age;
@Value("Shimla") // SpEL Bean reference
private String city; @Value("#{address}")
@Value("HP") private Address address;
private String state; @Value("#{address.city}")
// As SpEL literal private String personCity;
@Value("#{'171004'}") // SpEL Method invocation
private String pinCode; @Value("#{person.getInfo()}")
private String personInfo;
// getter and setter methods
} // getter and setter methods
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 37


SpEL Using Annotation - properties files
 Create a data.properties file:
technic_name=Java Web,Android,.Net,C/C++,Angular,React
MSG1=Sorry, your username or password is incorrect. Please try again!
MSG2=Username must be not empty!
MSG3=Password must be not empty!
MSG4=You must input all required fields!
MSG5=Wrong format!

 We will add some fields to read the configuration from employee.properties using @Value
annotation. @Controller
 Example: @SessionAttributes("user")
@PropertySource(value = "classpath:data.properties")
public class UserController {

@Value("#{'${MSG1}'}")
private String msg1;
@Value("#{'${MSG2}'}")
private String msg2;
@Value("#{'${MSG3}'}")
private String msg3;
@Value("#{'${MSG4}'}")
private String msg4;
@Value("#{'${MSG5}'}")
private String msg5;

@Value("#{'${technic_name}'.split(',')}")
private List<String> technics;
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 38


Section 4

REDIRECTVIEW TO ADD/FETCH FLASH


ATTRIBUTES USING REDIRECTATTRIBUTES

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 39


RedirectAttributes class
 A specialization of the Model interface that controllers can use to select
attributes for a redirect scenario.

 This interface also provides a way to add flash attributes and they will
be automatically propagated to the "output" FlashMap of the current
request.

 A RedirectAttributes model is empty when the method is called and is


never used unless the method returns a redirect view name or a
RedirectView.

 After the redirect, flash attributes are automatically added to the model
of the controller that serves the target URL.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 40


Methods
 addFlashAttribute:("key", "value")
 Flash Attributes are attributes which lives in session for short time.
 It is used to propagate values from one request to another request and then
automatically removed.
 Handling flash attributes are achieved using FlashMap and
FlashMapManager.
 But in annotated spring MVC controller, it can be achieved with
RedirectAttributes.

 addAttribute(“attributeName”, “attributeValue”)
 Add the supplied attribute under the supplied name.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 41


Add Flash Attributes

@RequestMapping(value = "mybook", method = RequestMethod.GET)


public ModelAndView book() {
return new ModelAndView("book", "book", new Book());
}

@RequestMapping(value = "/save", method = RequestMethod.POST)


public RedirectView save(@ModelAttribute("book") Book book,
RedirectAttributes redirectAttrs) {
redirectAttrs.addAttribute("msg", "Hello World!");
redirectAttrs.addFlashAttribute("book", book.getBookName());
redirectAttrs.addFlashAttribute("writer", book.getWriter());

RedirectView redirectView = new RedirectView();


redirectView.setContextRelative(true);
redirectView.setUrl("/hello/{msg}");
return redirectView;
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 42


Fetch Flash Attributes
 To fetch flash attributes we have two approaches.
 The first one is by using Model as an argument in the
@RequestMapping method and fetch the flash attribute as below.

model.asMap().get("key");

@RequestMapping(value = "/hello/{msg}", method = RequestMethod.GET)


public String hello(Model model, RedirectAttributes redirectAttrs,
@PathVariable("msg") String msg, HttpServletRequest request) {
System.out.println("Message:" + msg);

System.out.println("Fetch Flash Attributes By using Model");


System.out.println("Book Name:" + model.asMap().get("book"));
System.out.println("Writer:" + model.asMap().get("writer"));

return "redirect:/success.jsp";
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 43


SUMMARY
• Spring @RequestParam Annotation
1

• Spring Form tags


2

• @SessionAttributes or @SessionAttribute
3

• Spring Expression Language (SpEL)


4

• RedirectView and RedirectAttributes


5

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 44


Thank you

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy -


45
Internal Use
Spring Validation
& Interceptor
Instructor:

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 1


Table Content

• Spring Mvc Form Validation


1

• Interceptor
2

• Spring MVC Exception Handling


3

• Practice time
4

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 2


Learning Goals
 After the course, attendees will be able to:

Understand the importance of validation

Implement validation in Spring MVC

Understand how Interceptor works

Create and use Interceptor

Protect private resources interceptor application to

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 3


Section 1

FORM VALIDATION USING


JAVA BEAN VALIDATION API

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 4


FORM VALIDATION
 To make sure the data inputted from users, the software must check
inputted data is valid or not. Spring provides vary and easy way to
validation user input.
 Form Validation using JSR-303 validation annotations, hibernate-
validators, providing internationalization support using MessageSource.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 5


What is validation in web aplication
 Is pre-processing to make sure the application recived
corrected data

Java script validator


User input
data

Spring form-validation

Controller

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 6


FORM VALIDATION
 Invalid input will cause unpredictable errors. Therefore,
control of input data always plays an important role in the
application.
 Common errors
 Leave the input box blank ...
 Incorrect email format, creditcard, url ...
 Incorrect type of integer, real number, date and time ...
 Minimum value, maximum value, within ...
 Unlike passwords, correct captcha, identical code
 Not as expected of some calculations ...

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 7


Form Validation Advantage

•Prevent user enter wrong value to system. For example:


Security user not allowed to wrong email look like
info@fsoft.com.vn

Friendly to user •User will be suggested the correct value

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 8


How to do?

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 9


(1) Required Maven Dependency
 Add maven dependency in pom.xml file.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 10


(2) XML Config
spring-mvc-servlet.xml

You make sure that


<mvc:annotaion-
drive/> is existed

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 11


Entity class
User set validator annotaion to entity/bean
Or use existed one
Define a validator
from hibernate

Phone validator

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 12


Controller

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13


In view

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 14


Section 2

SPRING MVC EXCEPTION HANDLING

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 15


Using XML configuration
 This approach uses XML to configure exceptions handling declaratively.
Consider the following bean declaration in Spring’s application context file:
<bean class="org.springframework.web.servlet.handler.
SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">MathError</prop>
</props>
</property>
</bean>

 That will map any exceptions of type java.lang.ArithmeticException (or its sub
types) to the view named MathError.
 During execution of a Spring controller, if such an exception is thrown, the client
will be redirected to the mapped view: /views/MathError.jsp:

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 16


Using XML configuration
 Controller:
@Controller
@RequestMapping("/doMath")
public class MathController {
@RequestMapping(method = RequestMethod.GET)
public ModelAndView calculateSum(@RequestParam int a, @RequestParam int b) {
ModelAndView model = new ModelAndView("MathResult");

model.addObject("sum", (a + b));
model.addObject("subtract", (a - b));
model.addObject("multiply", (a * b));
model.addObject("divide", (a / b));

return model;
}
}

 In this code, there are two possible exceptions:


 Either a or b is not a number.
 b is zero, so the operation a / b will throw a java.lang.ArithmeticException exception.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 17


Using XML configuration
 Following is code of the MathResult.jsp page:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Math Result</title>
</head>
<body>
<center>
<b>Sum: ${sum} </b><br/>
<b>Subtract: ${subtract} </b><br/>
<b>Multiply: ${multiply} </b><br/>
<b>Divide: ${divide} </b><br/>
</center>
</body>
</html>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 18


Using XML configuration
 Code of the MathError.jsp page:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
</head>
<body>
<h2>
Mathematical Error: ${exception} <br />
</h2>
</body>
</html>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 19


Using XML configuration
 Output when testing the application with two numbers a = 2000 and b =
100:

 If we pass b = 0, then the MathError.jsp page will be displayed:

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 20


Using exception handler method
 This approach uses the @ExceptionHandler annotation to annotate a method in controller
class to handle exceptions raised during execution of the controller’s methods.
 Consider the following controller class:
@Controller
public class FileUploadController {

@RequestMapping(value = "/uploadFile", method = RequestMethod.GET)


public String doFileUpload(@RequestParam int a) throws IOException, SQLException {

// handles file upload stuff...


if (a == 1) {
throw new IOException("Could not read upload file.");
} else if (a == 2) {
throw new SQLException("Database exception!!!");
}

return "done";
}

@ExceptionHandler({IOException.class, java.sql.SQLException.class})
public ModelAndView handleIOException(Exception ex) {
ModelAndView model = new ModelAndView("IOError");

model.addObject("exception", ex.getMessage());

return model;
}
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 21


Using exception handler method
 The method doFileUpload() may throw an IOException, and the handler
method is declared as follows:
@ExceptionHandler(IOException.class)
public ModelAndView handleIOException(IOException ex) {
ModelAndView model = new ModelAndView("IOError");

model.addObject("exception", ex.getMessage());

return model;
}

 This handleIOException() method will be invoked whenever an exception of


type java.io.IOException (or its sub types) is raised within the controller class.
 Spring will pass the exception object into the method’s argument.
 It’s also possible to specify a list of exception classes in the
@ExceptionHanlder annotation, for example:

ExceptionHandler({IOException.class, java.sql.SQLException.class})

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 22


Spring @ExceptionHandler Global exception handling

 If we want to centralize the exception handling logic to one class which is


capable to handle exceptions thrown from any handler class/ controller
class – then we can use @ControllerAdvice annotation.
 Example:
 (1) Custom Exception Class: Let’s create a simple custom exception class.
In this class, we have defined the “error code” and “error message” member
variables for specifying the user-defined error messages
@Component
public class MyException extends RuntimeException {

private static final long serialVersionUID = 1L;

private String errCode;


private String errMsg;

public MyException() {
}
// getter and setter methods
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 23


Spring @ExceptionHandler Global exception handling

 (2) Global Exception Handler Class:


@ControllerAdvice
public class ExceptionControllerAdvice {

@ExceptionHandler(MyException.class)
public ModelAndView handleMyException(MyException mex) {

ModelAndView model = new ModelAndView();


model.addObject("errCode", mex.getErrCode());
model.addObject("errMsg", mex.getErrMsg());
model.setViewName("error/generic_error");
return model;
}

@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception ex) {

ModelAndView model = new ModelAndView();


model.addObject("errMsg", "This is a 'Exception.class' message.");
model.setViewName("error/generic_error");
return model;

}
}

 Notes: generic_error is a view name. Ex: error/generic_error.jsp.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 24


Spring @ExceptionHandler Global exception handling

 (3) Controller Class:


@Controller
public class ExceptionCtrl {

@RequestMapping(value = "/exception/{type}", method = RequestMethod.GET)


public String exception(@PathVariable(name = "type") String exception)
throws IOException {

if (exception.equalsIgnoreCase("error")) {
throw new MyException("A1001",
"This is a custom exception message.");
} else if (exception.equalsIgnoreCase("io-error")) {
throw new IOException();
} else {
return "success";
}
}
}

 If the user provides a /error request, the controller method will throw the MyException, and the
ExceptionControllerAdvice.handleMyException() method will be invoked to handle the exception.
 If the user provides a /io-error request, the controller method throw the IOException, and the
ExceptionControllerAdvice.handleException() method will be invoked to handle the exception.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25


@ResponseStatus
 You also can throw an Exception declared with @ResponseStatus
annotation:
 (1) I created a class named ResourceNotFoundException that extends from
RuntimeException and I putted this annotation over the class definition:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {

 (2) I created this method in my exception's controller class:


@ControllerAdvice
public class ExceptionControllerAdvice {

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {

return "notFoundJSPPage";
}
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 26


@ResponseStatus
 Controller class example:
@Controller
public class ExceptionCtrl {

@RequestMapping(value = "/exception/{type}", method = RequestMethod.GET)


public String exception(@PathVariable(name = "type") String exception)
throws IOException {

if (exception.equalsIgnoreCase("error")) {
throw new MyException("A1001", "This is a custom exception message.");
} else if (exception.equalsIgnoreCase("io-error")) {
throw new IOException();
} else if (exception.equalsIgnoreCase("404")) {
throw new ResourceNotFoundException();
} else {
return "success";
}
}
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27


Section 3

SPRING INTERCEPTOR

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 28


What is SPRING interceptor?
 Spring Interceptor are used to intercept client requests and
process them

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 29


Interceptor structure
derived class from HandlerInterceptorAdapter

Run BEFORE action method

false will not run action method

Run AFTER action method and BEFORE view

Run AFTER view

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 30


Interceptor process

request preHandle() Action

postHandle()

View
response afterCompletion()

 If we want to handle a task before the action executed, we have to


write code in preHandle.
 If we want to prepare something for View, we write code in
postHandle method.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 31


An Example of interceptor
 Create class and extend HandlerInterceptorAddaptor

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 32


Configure interceptor
 Interceptors, after being built, need to config in Spring
configuration file (.xml)
 The following declaration LoggerInterceptor will filter all
actions
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.springmvc.LoggerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 33


Implementing controller and view
 Controller class:

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 34


Run the project and see the result
 Run home / index.htm and see the output from Console:

 Through the results we see the order of execution

preHandle()=>index()=>postHandle()=>index.jsp=>afterCompletion()

Interceptor Action Interceptor View Interceptor

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 35


More: Interceptor configuration
 Sometimes Interceptor is built just to filter some actions, not
all actions.
 The following configuration allows only LoggerInterceptor to
filter home/index.htm and home/about.htm actions:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/home/index.htm" />
<mvc:mapping path="/home/about.htm" />
<bean class="com.springmvc.LoggerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 36


More: Interceptor configuration
 Another situation is that we want to filter all actions in the
HomeController except for home/ index.htm:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/home/**" />
<mvc-exclude:mapping path="/home/about.htm" />
<bean class="com.springmvc.LoggerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

 Here we see that <mvc: exclude-mapping> is used to


exclude unfiltered actions and ** is a symbol for any group
of characters.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 37


An issue when implement security
 The yellow actions of the following two controllers are only
accessible after logging in

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 38


Resolve the issue
 Implement SecurityInterceptor to filters all actions of the
two controllers except for those that do not fill in yellow.
 The SecurityInterceptor must run before requesting the
action and will do the following:
 Check that the session has an attribute named user or not? If not,
redirect to user/ login.htm.
 On user/login.htm, after successful login, you need to create a user
attribute in the session.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 39


Resolve the issue

<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/**" />
<mvc:mapping path="/order/**" />
<mvc-exclude:mapping path="/user/login.htm" />
<mvc-exclude:mapping path="/user/register.htm" />
<mvc-exclude:mapping path="/user/forgot-passowrd.htm" />
<mvc-exclude:mapping path="/user/active.htm" />
<bean class="com.springmvc.LoggerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 40


Resolve the issue
 This interface module belongs to the layout but needs to
load data from the database.
 Problem: Where to write code to feed this module?
 Write in every action of every controller because every view needs
this data.
 Write in Interceptor's postHandle() that filters all actions. Obviously
this option is very optimal.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 41


Load shared data issue

Login Logout

This interface module belongs to the layout but needs Product A


to load data from the database. Product B
Problem: Where to write code to feed this module? Product C
 Write in every action of every controller because
every view needs this data. Product D
 Write in Interceptor's postHandle () that filters all
actions. Obviously this option is very optimal.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 42


Summary
 Study the importance of Validation
 Implement validator
 Handling Exception in Spring Web MVC
 Learn Interceptor
 Implement Interceptor
 Configure Interceptor to filter actions
 Interceptor application to protect privacy functions.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 43


Thank you

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 44


SPRING BOOT BASICS

Instructor:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 1


Table Content

1 •Introduction

• Starter template
2

• Bootstrap the application


3

• Spring Boot Annotations


4

5 •Spring Boot JSP View Resolver

•Spring Boot Devtools


6

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 2


Learning Goals
 After the session, attendees will be able to:

Understand Spring Boot Framework and its core


technologies.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 3


Section 1

INTRODUCTION

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 4


Introduction
 Spring Boot is a Spring module that provides the RAD (Rapid
Application Development) feature to the Spring framework.
 Spring Boot is an open source Java-based framework used to create a
micro Service.
 Micro Service is an architecture that allows the developers to develop and
deploy services independently.
 Each service running has its own process and this achieves the lightweight
model to support business applications.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 5


Introduction
 Spring Boot is a project that is built on the top of the Spring Framework.
It provides an easier and faster way to set up, configure, and run both
simple and web-based applications.
 Spring Boot offers the following advantages to its developers
 Easy to understand and develop spring applications
 Increases productivity
 Reduces the development time

 Spring Boot is the combination of Spring Framework and Embedded


Servers.
 We can use Spring STS IDE or Spring Initializr to develop Spring Boot
Java applications.
09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 6
Prerequisite of Spring Boot
 To create a Spring Boot application, following are the prerequisites. In
this tutorial, we will use Spring Tool Suite (STS) IDE.
 Java 1.8
 Maven 3.0+
 Spring Framework 5.0.0.BUILD-SNAPSHOT
 An IDE (Spring Tool Suite) is recommended.
 Spring Boot Features:
 Web Development
 SpringApplication
 Application events and listeners
 Admin features
 Externalized Configuration
 Properties Files
 YAML Support
 Type-safe Configuration
 Logging
 Security
09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 7
Section 2

SETUP

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 8


Spring Boot Starters
 First, let's use Spring Initializr to generate the base for our
project.
 Handling dependency management is a difficult task for
big projects.
 What is starter template?
 Spring Boot starters are templates that contain a collection of all
the relevant transitive dependencies that are needed to start a
particular functionality.
 For example, If you want to create a Spring Web MVC application
then in a traditional setup, you would have included all required
dependencies yourself. It leaves the chances of version
conflict which ultimately result in more runtime exceptions.
 Note that all Spring Boot starters follow the same naming
pattern spring-boot-starter- *, where * indicates that it is a type of
the application.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 9


Spring Boot Starters
 With Spring boot, to create MVC application all you need to import is
spring-boot-starter-web dependency.

<!-- Spring web brings all required dependencies


to build web application. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

 Notes:
 This dependency, internally imports all given dependencies and add to your project.
 Notice how some dependencies are direct, and some dependencies further refer to other starter
templates which transitively downloads more dependencies.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 10


Spring Boot Starters
 Examples
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 11


Spring Boot Starter Parent
 The spring-boot-starter-parent dependency is the parent POM
providing dependency and plugin management for Spring Boot-based
applications.
 It contains the default versions of Java to use, the default versions of
dependencies that Spring Boot uses, and the default configuration of the
Maven plugins.

<!-- Parent pom is mandatory to control versions


of child dependencies -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 12


Popular templates and their transitive dependencies

STARTER DEPENDENCIES

spring-boot-starter spring-boot, spring-context, spring-beans

spring-boot-starter-jersey jersey-container-servlet-core, jersey-container-servlet, jersey-server


spring-boot-starter-actuator spring-boot-actuator, micrometer-core
spring-boot-starter-aop spring-aop, aspectjrt, aspectjweaver
spring-boot-starter-data-rest spring-hateoas, spring-data-rest-webmvc
spring-boot-starter-hateoas spring-hateoas
spring-boot-starter-logging logback-classic, jcl-over-slf4j, jul-to-slf4j
spring-boot-starter-log4j2 log4j2, log4j-slf4j-impl
spring-boot-starter-security spring-security-web, spring-security-config
spring-test, spring-boot,junit,mockito, hamcrest-library, assertj,
spring-boot-starter-test
jsonassert, json-path

spring-boot-starter-web-services spring-ws-core

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13


Section 3

SPRING BOOT ANNOTATIONS

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 14


Introduction
 The spring boot annotations are mostly placed in:
 org.springframework.boot.autoconfigure and
 org.springframework.boot.autoconfigure.condition packages.
 @SpringBootApplication annotation:
 Spring boot is mostly about auto-configuration.
 @SpringBootApplication annotation enable all able things in one
step.
 It enables the three features:
• @EnableAutoConfiguration: enable auto-configuration mechanism.
• @ComponentScan: enable @Component scan.
• @SpringBootConfiguration: register extra beans in the context.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 15


@SpringBootApplication annotation
 The java class annotated with @SpringBootApplication is the main
class of a Spring Boot application and application starts from here.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.
SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {


SpringApplication.run(Application.class, args);
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 16


Bootstrap the application
 To run the application, we need to use @SpringBootApplication annotation.
Behind the scenes, that’s equivalent[tươngđương] to @Configuration,
@EnableAutoConfiguration, and @ComponentScan together.

 It enables the scanning of config classes, files and load them into spring
context.

 In below example, execution start with main() method. It start loading all the
config files, configure them and bootstrap the application based on application
properties in application.properties file in /resources folder.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 17


What You Need
 A favorite text editor or IDE
 JDK 1.8 or later
 Gradle 4+ or Maven 3.2+
 You can also import the code straight into your IDE:
 Spring Tool Suite (STS)
 IntelliJ IDEA
 For all Spring applications, you should start with the Spring
Initializr: https://start.spring.io/

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 18


Use STS
 Step 1: Spring Starter Project:

 Step 2: provide the name, group, and package of the project. We have
provided:
 Name: bfams
 Group: fa.training
 Package: fa.training

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 19


Use STS
 Choose the Spring Boot Version 2.0.1 and technologies:

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 20


Use Spring Initializr
 The Initializr offers a fast way to pull in all the dependencies you need for an application
and does a lot of the set up for you.
 This example needs the Rest Repositories, Spring Data JPA, and H2 dependencies. The
following image shows the Initializr set up for this sample project:

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 21


Project Structure
 RestSpringBootApplication.java
package fa.training;
import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.
SpringBootApplication;
@SpringBootApplication
public class Bfams2Application {
public static void main(String[] args) { SpringApplication.
run(Bfams2Application.class, args);
}
}
 application.properties

spring.datasource.url=jdbc:sqlserver://localhost;databaseName=FAMS1
spring.datasource.username=sa
spring.datasource.password=12345678
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.
SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto =none

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 22


Run the launch application and check logs
 Let’s start running it with the simplest option–running as a Java application.
 In your IDE, right-click on the application class and run it as Java Application.
 For getting insight of registered beans, I have added modified the launch
application as below.

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.0)

2020-11-20 16:46:40.403 INFO 920 --- [ main] fa.training.ServletInitializer : Starting ServletInitializer v0.0.1-SNAPSHOT using Java 1.8.0_211 on LPP00065422A with PID 920 (C:\Users\dieunt1\ecli
2020-11-20 16:46:40.422 INFO 920 --- [ main] fa.training.ServletInitializer : No active profile set, falling back to default profiles: default
2020-11-20 16:46:44.897 INFO 920 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-11-20 16:46:45.001 INFO 920 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 45 ms. Found 0 JPA repository interfaces.
2020-11-20 16:46:47.752 INFO 920 --- [ main] o.a.c.c.C.[.[.[/hrm_springbootwebmvc] : Initializing Spring embedded WebApplicationContext
2020-11-20 16:46:47.753 INFO 920 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 7055 ms
2020-11-20 16:46:49.504 INFO 920 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-11-20 16:46:50.121 INFO 920 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-11-20 16:46:50.956 WARN 920 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. E
2020-11-20 16:46:51.281 INFO 920 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.23.Final
2020-11-20 16:46:55.186 INFO 920 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-11-20 16:46:55.747 INFO 920 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: c770fe80-3a6f-4135-bcac-18dd4651db20

2020-11-20 16:46:57.510 INFO 920 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...


2020-11-20 16:46:57.703 INFO 920 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilte
org.springframework.security.web.authentication.logout.LogoutFilter@17c544e9, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@707172a8, org.springframework.security.web.authentic
org.springframework.security.web.savedrequest.RequestCacheAwareFilter@146629c0, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4bfc4be1, org.springframework.security.web.authenti
org.springframework.security.web.access.intercept.FilterSecurityInterceptor@1fdc3182]
2020-11-20 16:46:58.289 INFO 920 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-11-20 16:46:58.291 INFO 920 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-11-20 16:46:58.364 INFO 920 --- [ main] fa.training.ServletInitializer : Started ServletInitializer in 20.812 seconds (JVM running for 50.503)
2020-11-20 16:46:58.950 INFO 920 --- [ main] org.apache.jasper.servlet.TldScanner : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete lis
2020-11-20 16:46:59.053 INFO 920 --- [ main] org.apache.coyote.ajp.AjpNioProtocol : Starting ProtocolHandler ["ajp-nio-8009"]
2020-11-20 16:46:59.067 INFO 920 --- [ main] org.apache.catalina.startup.Catalina : Server startup in [49,222] milliseconds
2020-11-20 16:47:01.131 INFO 920 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-11-20 16:47:01.803 INFO 920 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/hrm_springbootwebmvc] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-11-20 16:47:01.804 INFO 920 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-11-20 16:47:01.813 INFO 920 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
2020-11-20 16:47:02.510 INFO 920 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect
2020-11-20 16:47:05.947 INFO 920 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-11-20 16:47:06.035 INFO 920 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 23


Section 4

SPRING BOOT WEB APP

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 24


What is starter template?
 Add a dependency to compile JSP files:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>

<!-- To compile JSP files -->


<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25


Spring Boot JSP View Resolver
 To resolve JSP files location, you can have two approaches.
 Add entries in application.properties

 Configure InternalResourceViewResolver to serve JSP pages


package fa.training.controller;

@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfiguration implements WebMvcConfigurer {

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);

return viewResolver;
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 26


Spring Boot JSP View Resolver
 Configure to serve JSP pages:
@Override
public void addResourceHandlers(
ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 27


Spring Boot Web Controller
 Create a controller class is the same as the controller class in Spring
Web MVC: using @Controller, @Get/@PostMapping, @Autowired, ...
@Controller
public class InitController {

@GetMapping("/")
public String init(Model model) {

model.addAttribute("user", new User());

return "login";
}

@GetMapping("/index")
public String initIndex(Model model) {

return "index";
}
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 28


Serving static content
 Spring Boot automatically adds static web resources located within any
of the following directories:
 /META-INF/resources/
 /resources/
 /static/
 /public/
 The directories are located in the classpath or in the root of the
ServletContext.
 Example: the following structure of a Web
application which serves index1.html,
index2.html and index3.html from three
different locations:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 29


Serving static content
 Using the View Controller to map URL with resources
 ViewControllerRegistry registers a View Controller.
 It is used when we just need to map a URL with a view
using addViewController(String urlPath).
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);

registry.addViewController("/savepassword")
.setViewName("savepassword.html");
registry.addViewController("/login")
.setViewName("login.html");
registry.addViewController("/")
.setViewName("loggedin/index.html");

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 30


Serving static content
 Accessing Javascript and css in Spring Boot
 Css and javascript (.js) files are static resources and Spring Boot maps it by
default in your /resources/static folder.
 So for example, define a file style.css file in the folder
src/main/resources/static/css with a minimal content:

h1 {
background-color: green;
color: red;
text-align: center;
}

<html>
<head>
<link href="/css/style.css"
rel="stylesheet">
</head>
<h1>Spring boot example</h1>
</html>

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 31


Spring Boot Devtools
 The spring-boot-devtools dependency provided the auto-reload of UI
in browser whenever there is change in some code.
 pom.xml file:
<!-- devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

 Automatic UI refresh
 The spring-boot-devtools module includes an embedded LiveReload server
that can be used to trigger a browser refresh when a resource is changed.
 Precondition is that your browser should have supported extention for it.
 By default, live reload is enabled
application.properties
spring.devtools.livereload.enabled = false # Set false to disable live reload

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 32


SUMMAY

1 •Introduction

2 • Starter template

3 • Bootstrap the application

4 • Spring Boot Annotations

5 •Spring Boot JSP View Resolver

6 •Spring Boot Devtools

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 33


Thank you

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 34


34
SPRING DATA JPA
Instructor:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 1


Table Content

1 • Introduction

2 • Spring Data JPA Interface

3 • How to Use Spring Data JPA interfaces

4 • Query methods

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 2


Learning Goals
 After the session, attendees will be able to:

Understand Spring Data JPA Framework and its core


technologies.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 3


Section 1

INTRODUCTION

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 4


Introduction
 Spring Data is a module of Spring Framework. The goal of
Spring Data repository abstraction is to significantly reduce
the amount of boilerplate code required to implement
data access layers for various persistence stores.
 Java Persistence API (JPA) is Java’s standard API
specification for object-relational mapping. Spring Data JPA
is a part of Spring Data and it supports Hibernate 5,
OpenJPA 2.4, and EclipseLink 2.6.1.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 5


What Spring Data JPA?
 Spring Data JPA is NOT a JPA provider.
 It is a library/framework that adds an extra layer of abstraction on the top
of our JPA provider (like Hibernate).
 If we decide to use Spring Data JPA, the repository layer of our
application contains three layers that are described in the following:

 Spring Data JPA provides support for creating JPA repositories by extending
the Spring Data repository interfaces.
 Spring Data Commons provides the infrastructure that is shared by the
datastore-specific Spring Data projects.
 The JPA Provider (like hibernate) implements the Java Persistence API.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 6


Repositories/interfaces
 Spring Data Commons and Spring Data JPA

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 7


Repositories/interfaces
 It contains technology-neutral repository interfaces as well
as a metadata model for persisting Java classes.
 Spring Data Commons project provides the following
interfaces:
 Repository<T, ID extends Serializable> interface
 CrudRepository<T, ID extends Serializable> interface
 PagingAndSortingRepository<T, ID extends Serializable> interface
 QueryDslPredicateExecutor interface

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 8


Section 2

SPRING DATA JPA INTERFACE

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 9


Repository interface
 The Repository<T, ID extends Serializable> interface is a
marker interface that has two purposes:
 It captures the type of the managed entity and the type of the entity’s
id.
 It helps the Spring container to discover the “concrete” repository
interfaces during classpath scanning.
 Let's look at the source code of the Repository interface.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 10


CrudRepository interface
 The CrudRepository<T, ID extends Serializable> interface provides CRUD
operations for the managed entity.
 Let's look at the methods/APIs that the CrudRepository interface
provides:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 11


CrudRepository interface
 Let's look at the usage of each method with description.
 long count() - Returns the number of entities available.
 void delete(T entity) - Deletes a given entity.
 void deleteAll() - Deletes all entities managed by the repository.
 void deleteAll(Iterable<? extends T> entities) - Deletes the given entities.
 void deleteById(ID id) - Deletes the entity with the given id.
 boolean existsById(ID id) - Returns whether an entity with the given id exists.
 Iterable findAll() - Returns all instances of the type.
 Iterable findAllById(Iterable ids) - Returns all instances of the type with the given IDs.
 Optional findById(ID id) - Retrieves an entity by its id.
 save(S entity) - Saves a given entity.
 Iterable saveAll(Iterable entities) - Saves all given entities.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 12


PagingAndSortingRepository inteface
 The PagingAndSortingRepository<T, ID extends Serializable> interface is an extension of CrudRepository
to provide additional methods to retrieve entities using the pagination and sorting
abstraction.
package org.springframework.data.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

@NoRepositoryBean
public interface PagingAndSortingRepository < T, ID > extends CrudRepository < T, ID > {
/**
* Returns all entities sorted by the given options.
*
* @param sort
* @return all entities sorted by the given options
*/
Iterable < T > findAll(Sort sort);
/**
* Returns a {@link Page} of entities meeting the paging restriction provided in the
{@code Pageable} object.
*
* @param pageable
* @return a page of entities
*/
Page < T > findAll(Pageable pageable);
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 13


QueryDslPredicateExecutor interface
 The QueryDslPredicateExecutor interface is not a “repository interface”. It declares the
methods that are used to retrieve entities from the database by using QueryDsl Predicate
objects.
 Let's look at the methods/APIs that the QueryDslPredicateExecutor interface provides:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 14


Spring Data JPA Interfaces
 Spring Data JPA module deals with enhanced support for JPA based data access layers.
 Spring Data JPA project provides the following interfaces:
 JpaRepository<T, ID extends Serializable> interface
 JpaSpecificationExecutor interface
 JpaRepository interface:
 The JpaRepository<T, ID extends Serializable> interface is a JPA specific repository interface
that combines the methods declared by the common repository interfaces behind a single interface.
 Let's look at the methods/APIs that the JpaRepository interface provides:

package org.springframework.data.jpa.repository;

import java.util.List;

import javax.persistence.EntityManager;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;

@NoRepositoryBean
public interface JpaRepository < T, ID > extends PagingAndSortingRepository < T, ID > ,
QueryByExampleExecutor < T > {

List < T > findAll();

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 15


JpaRepository interface
List < T > findAll(Sort sort);

List < T > findAllById(Iterable < ID > ids);

<S extends T > List < S > saveAll(Iterable < S > entities);

void flush();

<S extends T > S saveAndFlush(S entity);

void deleteInBatch(Iterable < T > entities);

void deleteAllInBatch();

T getOne(ID id);

@Override <
S extends T > List < S > findAll(Example < S > example);

@Override <
S extends T > List < S > findAll(Example < S > example, Sort sort);
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 16


JpaSpecificationExecutor interface
 The JpaSpecificationExecutor interface is not a “repository interface”. It declares
the methods that are used to retrieve entities from the database by using
Specification objects that use the JPA criteria API.
 Let's look at the methods/APIs that the JpaSpecificationExecutor interface
provides:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 17


Pagination and Sorting
 Example to access our Products, we'll need a ProductRepository:
public interface ProductRepository extends
PagingAndSortingRepository<Product, Integer> {

List<Product> findAllByPrice(double price, Pageable pageable);


}

 Create or obtain a PageRequest object, which is an implementation of


the Pageable interface
 Pass the PageRequest object as an argument to the repository method we intend to
use
 We can create a PageRequest object by passing in the requested page
number and the page size. Here the page count starts at zero:

Pageable firstPageWithTwoElements = PageRequest.of(0, 2);

Pageable secondPageWithFiveElements = PageRequest.of(1, 5);

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 18


Pagination and Sorting
 Similarly, to just have our query results sorted, we can
simply pass an instance of Sort to the method:
Page<Product> allProductsSortedByName =
productRepository.findAll(Sort.by("name"));

 What if we want to both sort and page our data?


Pageable sortedByName =
PageRequest.of(0, 3, Sort.by("name"));

Pageable sortedByPriceDesc =
PageRequest.of(0, 3,
Sort.by("price").descending());

Pageable sortedByPriceDescNameAsc =
PageRequest.of(0, 5,
Sort.by("price").descending()
.and(Sort.by("name")));

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 19


Section 3

HOW TO USE SPRING DATA JPA INTERFACES

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 20


How to Use Spring Data JPA interfaces
 (1) Create a repository interface and extend one of the repository
interfaces provided by Spring Data.

 (2) Add custom query methods to the created repository


interface (if we need them that is).

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 21


How to Use Spring Data JPA interfaces
 (3) Set up Spring to create proxy instances for those
interfaces, either with JavaConfig or with XML configuration.
 To use Java configuration, create a class similar to the following:

 To use XML configuration, define a bean similar to the following:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 22


How to Use Spring Data JPA interfaces
 (4) Inject the repository interface to another component and use the
implementation that is provided automatically by Spring.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 23


Basic Spring Data JPA Flow

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 24


Section 4

QUERY METHODS

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 25


Query lookup strategies
 The JPA module supports defining a query manually as String or have it
being derived from the method name.
 Query creation:
 The query builder mechanism built into Spring Data repository infrastructure
is useful for building constraining queries over entities of the repository.
 The mechanism strips the prefixes find…By, read…By, query…By,
count…By, and get…By from the method and starts parsing the rest of it.
 You can define conditions on entity properties and concatenate them with
And and Or.
 Examples: Query creation from method names
public interface PersonRepository extends Repository<User, Long> {

List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress,


String lastname);

// Enables the distinct flag for the query


List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname,
String firstname);

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 26


Query creation
 Examples: Query creation from method names

List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname,


String firstname);

// Enabling ignoring case for an individual property


List<Person> findByLastnameIgnoreCase(String lastname);

// Enabling ignoring case for all suitable properties


List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname,
String firstname);

// Enabling static ORDER BY for a query


List<Person> findByLastnameOrderByFirstnameAsc(String lastname);

List<Person> findByLastnameOrderByFirstnameDesc(String lastname);


}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 27


Query creation
 Special parameter handling:
 Besides that the infrastructure will recognize certain specific types
like Pageable and Sort to apply pagination and sorting to your
queries dynamically.

Page<User> findByLastname(String lastname, Pageable pageable);

List<User> findByLastname(String lastname, Sort sort);

List<User> findByLastname(String lastname, Pageable pageable);

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 28


Query creation
 Query generated:
 Query creation from method names

public interface UserRepository extends Repository<User, Long> {

List<User> findByEmailAddressAndLastname(String emailAddress,


String lastname);
}

 We will create a query using the JPA criteria API from this but essentially this
translates into the following query:

select u from User u where u.emailAddress = ?1


and u.lastname = ?2

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 29


Query creation
 Supported keywords inside method names
Keyword Sample JPQL snippet

And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2

Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2

findByFirstname,findByFirstnameIs,
Is,Equals … where x.firstname = 1?
findByFirstnameEquals

Between findByStartDateBetween … where x.startDate between 1? and ?2

LessThan findByAgeLessThan … where x.age < ?1

LessThanEqual findByAgeLessThanEqual … where x.age <= ?1

GreaterThan findByAgeGreaterThan … where x.age > ?1

GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1

After findByStartDateAfter … where x.startDate > ?1

… … …

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 30


Using JPA NamedQueries
 Annotation configuration
 Annotation configuration has the advantage of not needing another
configuration file to be edited, probably lowering maintenance costs.
 You pay for that benefit by the need to recompile your domain class
for every new query declaration.
 Annotation based named query configuration

@Entity
@Table(name = "USERS")
@NamedQuery(name = "User.findByEmailAddress",
query = "select u from User u where u.emailAddress = ?1")
public class User {

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 31


Using JPA NamedQueries
 Annotation configuration
 Declaring interfaces:
 To allow execution of these named queries all you need to do is to
specify the UserRepository as follows:

public interface UserRepository extends


JpaRepository<User, Long> {
List<User> findByLastname(String lastname);

User findByEmailAddress(String emailAddress);

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 32


Using @Query
 Using named queries to declare queries for entities is a valid approach
and works fine for a small number of queries.
 As the queries themselves are tied to the Java method that executes
them you actually can bind them directly using the Spring Data JPA
@Query annotation rather than annotating them to the domain class.
 This will free the domain class from persistence specific information and
co-locate the query to the repository interface.
 Declare query at the query method using @Query

public interface UserRepository extends


JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 33


SUMMARY

1 • Introduction

2 • Spring Data JPA Interface

3 • How to Use Spring Data JPA interfaces

4 • Query methods

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 34


Thank you

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 35


35
SPRING BOOT RESTful
WEB SERVICE
Instructor:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 1


Table Content

•Introduction
1

• Initializing a RESTful Web Service Project


2

• RequestBody and ResponseBody


3

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 2


Learning Goals
 After the session, attendees will be able to:

Know how to write a RESTful API web service with Spring


Boot.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 3


Section 1

INTRODUCTION

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 4


Introduction
 REST is the acronym for REpresentational State Transfer.
 REST is an architectural style for developing applications
that can be accessed over the network.
 REST architectural style was brought in light by Roy Fielding
in his doctoral thesis in 2000.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 5


Introduction
 RESTful web services try to define services using the different concepts
that are already present in HTTP. The main goal of RESTful web
services is to make web services more effective.
 We can build REST services with both XML and JSON. JSON is more
popular format with REST.
 It can be accessed through a Uniform Resource Identifier (URI)

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 6


Introduction
 Need of REST API
 Sharing data between two or more systems has always been a
fundamental requirement of software development.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 7


Introduction
 Why Restful
 Heterogeneous[không đồng nhất] languages and environments:
• It enables web applications that are built on various programming languages to
communicate with each other.
• With the help of Restful services, these web applications can reside on different
environments, some could be on Windows, and others could be on Linux.
 Example:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 8


Introduction
 Methods of REST API
 All of us working with the technology of the web, do CRUD
operations

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 9


Introduction
 Methods of REST API
 Example

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 10


Introduction
 For example, if we want to perform the following actions in
the social media application, we get the corresponding
results.
 POST /users: It creates a user.
 GET /users/{id}: It retrieves the detail of a user.
 GET /users: It retrieves the detail of all users.
 DELETE /users: It deletes all users.
 DELETE /users/{id}: It deletes a user.
 GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.
 POST / users/{id}/ posts: It creates a post of the user.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 11


Introduction
 HTTP also defines the following standard status code:
 404: RESOURCE NOT FOUND
 200: SUCCESS
 201: CREATED
 401: UNAUTHORIZED
 500: SERVER ERROR
 RESTful Service Constraints
 There must be a service producer and service consumer.
 The service is stateless.
 The service result must be cacheable.
 The interface is uniform and exposing resources.
 The service should assume a layered architecture.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 12


Restful Web Services and SOAP
 SOAP is a protocol whereas REST is an architectural style.
 SOAP server and client applications are tightly coupled and bind with the
WSDL contract whereas there is no contract in REST web services
and client.
 Learning curve is easy for REST when compared to SOAP web
services.
 REST web services request and response types can be XML, JSON,
text etc. whereas SOAP works with XML only.
 JAX-RS is the Java API for REST web services whereas JAX-WS is the
Java API for SOAP web services.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 13


REST API Implementations
 There are two major implementations of JAX-RS API.
 Jersey: Jersey is the reference implementation provided by Sun. For using
Jersey as our JAX-RS implementation, all we need to configure its servlet in
web.xml and add required dependencies. Note that JAX-RS API is part of
JDK not Jersey, so we have to add its dependency jars in our application.
 RESTEasy: RESTEasy is the JBoss project that provides JAX-RS
implementation.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 14


JSON format
 JSON Data - A Name and a Value
var myJSON = '{"name":"John", "age":31, "city":"New York"}';

 Arrays in JSON Objects


{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}

 Nested Arrays in JSON Objects


myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 15
Section 2

INITIALIZING A RESTFUL WEB


SERVICE PROJECT

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 16


Creating a RESTful Web Service
 The steps to create a RESTful Web Service with Spring
Boot:
1 Create the Spring Boot Project

2 Define Database configurations

3 Create an Entity Class

4 Create JPA Data Repository layer

5 Create Rest Controllers and map API requests

6 Build and run the Project

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 17


Create the Spring Boot Project
 First, go to https://start.spring.io/ and create a project with
below settings

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 18


Create the Spring Boot Project
 Dependencies
 Web: Full-stack web development with Tomcat
 DevTools: Spring Boot Development Tools
 JPA: Java Persistence API including spring-data-JPA, spring-orm, and
Hibernate
 MySQL/SQL Server: MySQL JDBC driver/MS SQL Server Driver SQL

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 19


Define Database Configurations
 Next, create the database name in database server and define
connection properties application.properties:
 MySQL Server:
## Database Properties
spring.datasource.url = jdbc:mysql://localhost:3306/db?useSSL=false
spring.datasource.username = root
spring.datasource.password = root

## Hibernate Properties
# The SQL dialect makes Hibernate generate better
# SQL for the chosen database
spring.jpa.properties.hibernate.dialect =
org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)


spring.jpa.hibernate.ddl-auto = update

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 20


Define Database Configurations
 application.properties MS SQL Server:

spring.datasource.url=jdbc:sqlserver://localhost;
databaseName=HumanResourceDB
spring.datasource.username=sa
spring.datasource.password=12345678
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc
.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto =update

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 21


Create Entity Class
 The @Entity annotation specifies that the class is an entity and is mapped to a
database table.
@Entity
@Table(name = "USERS")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")
private long userId;

@Column(name = "USERNAME", unique = true)


private String username;

@Column(name = "PASSWORD")
private String password;

// getter and setter methods


}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 22


JSON  Java
 How to convert the JSON object into a Java one and vice versa:
 The spring-boot-starter-web has built in jackson-databind, which helps to
convert JSON into Java object and vice versa.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 23


Create JPA Data Repository Layer
 @Repository annotation indicates that an annotated class
is a repository, which is an abstraction of data access and
storage.
 Example
public interface JobRepository extends
JpaRepository<Jobs, String> {

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 24


Restful Web Services Annotations
 @RestController:
 The @RestController annotation was introduced in Spring 4.0 to simplify the creation
of RESTful web services.
 It's a convenience annotation that combines @Controller and @ResponseBody
– which eliminates the need to annotate every request handling method of the
controller class with the @ResponseBody annotation

 @Path: used to specify the relative path of class and methods. We can get the
URI of a webservice by scanning the Path annotation value.
 @GET, @PUT, @POST, @DELETE and @HEAD: used to specify the HTTP
request type for a method.
 @Produces, @Consumes: used to specify the request and response types.
 @PathParam: used to bind the method parameter to path value by parsing it.

09e-BM/DT/FSOFT - ©FPT SOFTWARE – Fresher Academy - Internal Use 25


Create Rest Controllers
 @RestController annotation marks the class as web controller, capable
of handling the requests
 Example
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Autowired
private UserService userService;

/**
* Create user user.
*
* @param user the user
* @return the user
*/
@PostMapping("/add")
public User create(@Valid @RequestBody User user) {
return userService.save(user);
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 26


Create Rest Controllers
 @PostMapping annotation marks the POST method
 Example

/**
* Create user user.
* @param user the user
* @return the user
*/
@PostMapping("/add")
public User create (@Valid @RequestBody User user) {
return userService.save(user);
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 27


Create Rest Controllers
 @PutMapping annotation marks the PUT method
 Example
@PutMapping("/update/{id}")
public ResponseEntity<User> update(@PathVariable("id") long userId,
@RequestBody User userDetail) {

userService.findById(userId).orElseThrow(
() -> new ResourceNotFoundException("User not found: "
+ userId, "404"));

final User updatedUser = userService.save(userDetail);

return ResponseEntity.ok(updatedUser);

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 28


Create Rest Controllers
 @DeleteMapping annotation marks the DELETE method
 Example
@DeleteMapping("/delete/{id}")
public Map<String, Boolean> delete(@PathVariable(value = "id")
long userId) throws Exception {
User user = userService.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException(
"User not found: " + userId, "404"));

userService.delete(user);

Map<String, Boolean> response = new HashMap<>();


response.put("deleted", Boolean.TRUE);

return response;

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 29


Build and Run the Project
 Right click on project -> Run As -> Run on Server

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 30


Test
 Use Postman App to get services:

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 31


Section 3

@REQUESTBODY AND @RESPONSEBODY

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 32


@RequestBody
 The @RequestBody annotation maps the HttpRequest body to a
transfer or domain object, enabling automatic deserialization of the
inbound HttpRequest body onto a Java object.
@RestController
@RequestMapping("/api/v1/user")
public class UserRestController {

@Autowired
private UserService userService;

/**
* The method to insert a new user into User table in DB.
*/
@PostMapping("/add")
public User create(@Valid @RequestBody User user) {
return userService.save(user);
}
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 33


@RequestBody
 Spring automatically deserializes the JSON into a Java type, assuming
an appropriate one is specified.
 By default, the type we annotate with the @RequestBody annotation
must correspond to the JSON sent from our client-side controller:

public class User {

private long userId;

private String username;

private String password;

// setter and getter methods


}

 Here, the object we use to represent the HttpRequest body maps to


our User object.

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 34


@ResponseBody
 The @ResponseBody annotation tells a controller that the
object returned is automatically serialized into JSON and
passed back into the HttpResponse object.
 Suppose we have a custom Response object:
public class ResponseTransfer {
private String text;

// standard getters/setters
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 35


@ResponseBody
 Next, the associated controller can be implemented:
@RestController
@RequestMapping("/api/v1/user")
public class UserRestController {

@Autowired
ExampleService exampleService;

@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(
@RequestBody User user) {
return new ResponseTransfer("Thanks For Posting!!!");
}
}
 In the developer console of our browser or using a tool like Postman, we
can see the following response:
{"text":"Thanks For Posting!!!"}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 36


Setting the Content Type
 When we use the @ResponseBody annotation, we're still able to
explicitly set the content type that our method returns.
 We can use the @RequestMapping‘s produces attribute. Note that
annotations like @PostMapping, @GetMapping, etc. define aliases for
that parameter.
@PostMapping(value = "/content",
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseTransfer postResponseJsonContent(
@RequestBody LoginForm loginForm) {
return new ResponseTransfer("JSON Content!");
}

 We used the MediaType.APPLICATION_JSON_VALUE constant.


Alternatively, we can use application/json directly:
produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }
produces = { "application/json" , "application/xml" }

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 37


Section 4
RESPONSEENTITY
TO MANIPULATE THE HTTP RESPONSE

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 38


ResponseEntity
 ResponseEntity represents the whole HTTP response: status code,
headers, and body. As a result, we can use it to fully configure the
HTTP response.
 ResponseEntity is a generic type. Consequently, we can use any type as
the response body:

@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello World!",
HttpStatus.OK);
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 39


ResponseEntity
 Since we specify the response status programmatically, we
can return with different status codes for different scenarios:
@GetMapping("/age")
public ResponseEntity<String> age(
@RequestParam("yearOfBirth") int yearOfBirth) {

if (isInFuture(yearOfBirth)) {
return new ResponseEntity<>(
"Year of birth cannot be in the future",
HttpStatus.BAD_REQUEST);
}

return new ResponseEntity<>(


"Your age is " + calculateAge(yearOfBirth),
HttpStatus.OK);
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 40


ResponseEntity
 We can set HTTP headers:

@GetMapping("/customHeader")
public ResponseEntity<String> customHeader() {

HttpHeaders headers = new HttpHeaders();


headers.add("Custom-Header", "foo");

return new ResponseEntity<>(


"Custom header set", headers, HttpStatus.OK);
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 41


ResponseEntity
 ResponseEntity provides two nested builder interfaces:
HeadersBuilder and its subinterface, BodyBuilder.
 Therefore, we can access their capabilities through the static methods
of ResponseEntity.

@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok("Hello World!");
}
 For the most popular HTTP status codes we get static methods:

BodyBuilder accepted();
BodyBuilder badRequest();
BodyBuilder created(java.net.URI location);
HeadersBuilder<?> noContent();
HeadersBuilder<?> notFound();
BodyBuilder ok();

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 42


ResponseEntity
 We can use the BodyBuilder status(HttpStatus status) and
the BodyBuilder status(int status) methods to set any HTTP status.
 With ResponseEntity<T> BodyBuilder.body(T body) we can set the
HTTP response body:

@GetMapping("/age")
ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
if (isInFuture(yearOfBirth)) {
return ResponseEntity.badRequest()
.body("Year of birth cannot be in the future");
}

return ResponseEntity.status(HttpStatus.OK)
.body("Your age is " + calculateAge(yearOfBirth));
}

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 43


Thank you

09e-BM/DT/FSOFT - ©FPT Software Academy - Internal Use 44


44

You might also like