Professional Documents
Culture Documents
PROGRAMMING PART 2
ESIGELEC
February 2023
2
PERSONAL PRESENTATION
3
UTAD UNIVERSITY
• University: UTAD
(Universidade de Trás-os-Montes e Alto Douro)
at Vila Real
4
SERVLET AND HTTP
A Quick Overview
5
WHAT IS A SERVLET?
6
HOW DOES
THE SERVLET
WORK?
7
SERVLET LIFE CYCLE
http://www.javachain.com/servlet-life-cycle/)
8
SERVLET LIFECYCLE
9
QUESTION
10
WHAT IS HTTP?
• Is transaction-oriented;
• Is stateless;
• Typically uses TCP as transport protocol (can be implemented over any other protocol);
• Default TCP port is 80 (any other port can be used though! In the labs we will use port
8080);
11
WHAT IS HTTP?
• Uses the Client/Server Model and It is a Request/Response protocol, based on two types
of messages:
12
HTTP
REQUEST
METHODS
13
HTTP
MESSAGES
GENERAL
TEMPLATE
14
HTTP
MESSAGE
HEADERS
15
POST http://servername.com/acc/create HTTP/1.1
Host: servername.com
firstName=Joao&lastName=Pavao
HTTP
REQUEST
MESSAGES
EXAMPLES
16
POST http://servername.com/acc/create HTTP/1.1
Host: servername.com
firstName=Joao&lastName=Pavao
HTTP
REQUEST
MESSAGES
EXAMPLES
17
GET http://www.utad.pt?firstname=Joao&lastname=Pavao HTTP/1.1
Host: www.utad.pt
HTTP
REQUEST
MESSAGES
EXAMPLES
18
GET http://www.utad.pt?firstname=Joao&lastname=Pavao HTTP/1.1
Host: www.utad.pt
HTTP
REQUEST
MESSAGES
EXAMPLES
19
HTTP/1.1 200 OK
Cache-Control: private
Date: Sat, 14 Jan 2012 04:00:08 GMT
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.0 X-AspNet-Version:
HTTP 2.0.50727 X-Powered-By: ASP.NET
RESPONSE Connection: close
MESSAGE Content-Length: 17151
EXAMPLE <html>
<head>…
<body>
</body
</html>
20
H T T P S TAT U S
CODES’
RANGE
21
HTTP
S TAT U S
CODES
22
HTTP
S TAT U S
CODES
23
JAKARTA ENTERPRISE EDITION
25
JAVA EE
Java EE versions:
• Java EE 6 (December 10, 2009)
26
JAKARTA EE
If we had to implement a full Web based application form the scratch, we would
have too many things to deal with. Some examples:
–Processing requests;
–Build responses;
–Multi-threading;
–…
• Jakarta EE provides to us services and APIs to deal with those “issues” and let
us focus on the business components and logic of our application.
• Jakarta EE uses the Java Programming Language and the Java Virtual Machine.
Slide based on: Java Platform, Enterprise Edition: The Java EE Tutorial. See:http://docs.oracle.com/javaee/7/tutorial/ 27
JA K A RTA E E
A R CH IT ECT UR E
(Enterprise
28
Information System)
Presentation-oriented
WEB TIER APPLICATIONS
Slide based on: Java Platform, Enterprise Edition: The Java EE Tutorial. See:http://docs.oracle.com/javaee/7/tutorial/ 30
WEB TIER
Slide based on: Java Platform, Enterprise Edition: The Java EE Tutorial. See:http://docs.oracle.com/javaee/7/tutorial/ 31
WEB TIER
Slide based on: Java Platform, Enterprise Edition: The Java EE Tutorial. See:http://docs.oracle.com/javaee/7/tutorial/ 32
WEB TIER
Slide based on: Java Platform, Enterprise Edition: The Java EE Tutorial. See:http://docs.oracle.com/javaee/7/tutorial/ 33
WEB TIER
Slide based on: Java Platform, Enterprise Edition: The Java EE Tutorial. See:http://docs.oracle.com/javaee/7/tutorial/ 34
SERVLETS AND THE MVC
• Service-oriented applications;
They can be used to build presentation-oriented web applications, but JSP (Java
Server Pages) are more suitable.
We can implement MVC (Model View Controller) using Servlets and JSP → the
JSP is the View, and the Servlet implements the Controller.
35
WEB TIER:
MVC ARCHITECTURE
36
Servlet Initialization
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@WebServlet("/Example")
public class Example extends HttpServlet{
HOW TO
...
CREATE A
SERVLET? }
37
Servlet Lifecycle
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@WebServlet("/Example")
public class Example extends HttpServlet{
HOW TO
public void init(ServletConfig config){
CREATE A
SERVLET? ...
}
public void destroy(){
...
}
}
38
SERVLET’S SERVICE METHODS
In this course we are going to use “doPost” and “doGet” in lab classes.
39
Service Methods
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@WebServlet("/Example")
HOW TO public class Example extends HttpServlet{
CREATE A protected void doGet(HttpServletRequest req,
SERVLET? ...
HttpServletResponse resp){
}}
40
SERVLETS – REQUESTS, RESPONSE AND
SHARING INFORMATION
41
PROCESSING REQUESTS
42
PROCESSING REQUESTS
Some examples:
Parameters/Data sent from the client to the server, either by POST or GET (query
string in URL) are retrieved using the method:
String getParameter(String name)
To retrieve multiple values:
String[] getParameterValues(String name)
Note that the return type is a String or String[]. You need to convert it to the correct
type.
We also have the method Enumeration<String> getAttributeNames() to
get the names of the attributes.
44
PROCESSING REQUESTS
•Enumeration<String> getHeaderNames()
Servlets can share information with other modules (e.g. other Servlets) using
scope objects.
Information is shared using Attributes. Access to attributes is made by using the
getAttribute and setAttribute methods of the class representing the scope.
We have following Scopes:
• Web context
• Session
• Request
• Page (not in Servlet).
46
PROCESSING REQUESTS
Web context
Sharing information with other modules of the same Context (There is one
context per "web application" per Java Virtual Machine).
…
ServletContext context = req.getServletContext();
context.setAttribute(“dbHost”,”localhost”);
…
String dbHost = (String) context.getAttribute(“dbHost”);
...
https://tomcat.apache.org/tomcat-9.0-doc/servletapi/javax/servlet/ServletContext.html
47
PROCESSING REQUESTS
Session
Sharing information with other modules of the same Session (Provides a way to
identify a user across more than one page request or visit to a Web site and to
store information about that user.).
…
HttpSession session = req.getSession();
session.setAttribute(“email”,”pmestre@utad.pt”);
…
String email = (String) session.getAttribute(“email”);
…
https://tomcat.apache.org/tomcat-9.0-doc/servletapi/javax/servlet/ServletContext.html
48
PROCESSING REQUESTS
Request
Sharing information with other modules processing the same Request;
…
req.setAttribute(“email”,”pmestre@utad.pt”);
…
String email = (String) req.getAttribute(“email”);
…
50
CODE EXAMPLES
51
SERVLET RESPONSE
A Servlet response contains information sent from the server to the client. Servlet responses
implement the ServletResponse interface that has methods to:
• Get an output stream that is used to send data to the client;
• Set the response type (e.g. text/plain);
• Indicate whether to buffer output;
• Set localization information;
HttpServletResponse objects have methods to:
• Set the HTTP headers;
• Status codes;
• Set Cookies.
52
SERVLET RESPONSE
(…)
PrintWriter out = resp.getWriter();
(…)
out.println("<body>");
out.println("<div> Hello </div>");
out.println("</body>");
53
SERVLET RESPONSE
54
SERVLET RESPONSE
...
The above line of code is equivalent to:
resp.setStatus(HttpServletResponse.SC_FORBIDDEN); DEPRECATED
55
SERVLET RESPONSE
Redirection
A servlet can redirect a client to another resource (internal or external), by using
the sendRedirect method.
Example:After successful login, redirect the user to the home page:
...
resp.sendRedirect("home");
….
Is equivalent to:
resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
resp.setHeader("Location", "home");
57
COOKIES& TRACKING SESSION
INFORMATION
58
QUESTION
59
QUESTION
60
COOKIES
61
COOKIES
62
COOKIES – GOING DEEP
SESSIONS USING
64
COOKIES – GOING DEEP
Session cookies – as its name suggests are kept by the client only for the
duration of the session.
65
CREATING COOKIES
...
resp.addCookie(cookie);
...
66
CREATING COOKIES
An example:
Another example:
user = cookieJar.get("userName").getValue();
68
CREATING COOKIES
70
TRACKING SESSION INFORMATION
• Store session information on the server (we must have “extra” objects that store
these data).
To support applications that need to maintain state, Java Servlet technology provides
an API for managing sessions.
71
TRACKING SESSION INFORMATION
72
STILL HAVE A QUESTION THOUGH…
73
STILL HAVE A QUESTION THOUGH…
It is a good practice to call the encodeURL(URL) of the response object to rewrite URLs. If cookies
are disabled, encodeURL will add the session id to the URL.
74
JSP – JAVA SERVER PAGES
75
REMEMBER THE MVC ARCHITECTURE?
76
WHAT IS A JSP?
When a JSP file is invoked for the first time, it is “converted” into a servlet
(at the server).
77
WHAT IS JSP?
A simple example:
78
JSP LIFECYCLE
• The web container checks the JSP and its corresponding servlet ages;
• If the servlet is older than the JSP file, then the container converts the JSP into
a servlet class and compiles this class.
After these steps, the life cycle is the same as for Servlets.
79
JSP LIFECYCLE
If an instance of the servlet (of the JSP) does not exist, the container:
The container invokes the _jspService() method, passing request and response objects.
If the container needs to remove the JSP page’s Servlet, it calls the jspDestroy() method.
80
JSP FILE CONTENTS
81
JSP FILE CONTENTS
• JSP Directives;
82
JSP DIRECTIVES
Directives:
• <%@ page ... %> – for page-dependent attributes;
• <%@ include ... %> – to include a file during the translation phase.
<%@ include file="filename" >
• <%@ taglib ... %> – Declares a tag library, containing custom tags for
different actions (not covered in this course).
83
JSP SCRIPTINGS
84
JSP SCRIPLETS
JSP scriptlet are used to contain any valid code fragment. Syntax:
<%
List<String> messages = dao.getMessages();
for (String msg : messages){
%>
<%
}
%>
85
JSP EXPRESSIONS
A JSP expression is used to insert the value of an expression, into the data returned
to the client (in string format). Syntax:
<%= scripting-language-expression %>
Example:
<%
List<String> messages = dao.getMessages();
for (String msg : messages){
%>
<p> <%=msg%></p>
<%
}
%>
86
FORWARDING AND INCLUDE ACTIONS
Example:
<jsp:include page="page.jsp"/>
87
FORWARDING AND INCLUDE ACTIONS
Another useful action tag is jsp:forward that allows us to forward the request to
another resource.The service will be provided by the new resource (servlet or JSP).
Examples:
<jsp:forward page="/service.jsp" />
Or:
<jsp:forward page="/service.jsp">
<jsp:param name="user" value="Pedro" />
</jsp:forward>
88
IMPLICIT OBJECTS
There is a set of explicit objects available in JSP scripting. These are created during the
conversion and are available to the service methods:
• out – javax.servlet.jsp.JspWriter
• request – javax.servlet.http.HttpServletRequest
• response – javax.servlet.http.HttpServletResponse
• Session – javax.servlet.http.HttpSession
• application – javax.servlet.ServletContext
• page – java.lang.Object
• pageContext – javax.servlet.jsp.PageContext
• config – javax.servlet.ServletConfig
89
BACK TO MVC….
We l
earn
ed ab
out t
h is
tt hi s
ou
ab
e arne d
al sol
We 90
REQUEST FORWARD IN SERVLET
We have seen the sendRedirect(location) method to redirect output to a new resource. Example:
response.sendRedirect(“page.jsp”);
In some situations, we need to forward the request to another resource and not do a redirect.
Example:
This is a good practice when redirecting the flow from a servlet to a jsp page.
91
SHOULD I USE REDIRECT OR DISPATCH?
With sendRedirect(location), the client makes two requests, therefore there are
two HTTP transactions:
92
HOW TO SHARE DATA?
If we use sendRedirect(location) :
• Use cookies;
• Use a session scope object;
(seen in previous lectures).
If we use forward(request,response):
• Use a request scope object.
• Use a session scope object;
Remember that if we use a session scope object it will exist until you destroy the
session or/and the object (session.removeAttribute(String attr)).
93
HOW TO SHARE DATA? – EXAMPLE 1
Using a session scope object (assuming that we have a Java class called Data):
Note that we can use the above code in JSP, but because of implicit objects
we do not need HttpSession session = request.getSession() in JSP.
94
HOW TO SHARE DATA? – EXAMPLE 1
Using a session scope object (assuming that we have a Java class called Data):
Note that we can use the above code in JSP, but because of implicit objects
we do not need HttpSession session = request.getSession() in JSP.
95
HOW TO SHARE DATA? – EXAMPLE 2
Using a request scope object (assuming that we have a Java class called Data):
96
HOW TO SHARE DATA? – EXAMPLE 2
Using a request scope object (assuming that we have a Java class called
Data):
...
Data data;
if (request.getAttribute(“DataObject”)!= null){
data = (Data) request.getAttribute("DataObject");
}
97
DATABASE ACCESS
98
BACK TO MVC….
We l
earn
ed ab
out t
h is
tt hi s
ou
ab
e arne d
al sol
We 99
DATABASE ACCESS - SOLUTION 1
100
JDBC Client Machine
Web Application Client Tier
Clients Client
Java EE Server
Java Java
Java Application
Servlets Server Server
Pages Faces
JDBC Web Tier
JDBC
Database Server
EIS Tier
Databases
101
public class DAO {
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException ex) {
JDBC – }
ex.printStackTrace();
LOAD THE }
DRIVER …
}
Note that we are using the Static Block to load the Driver!
102
private String url = "jdbc:mysql://localhost/myDB";
private String username = "dbuser";
private String password = "1234";
Connection conn = null;
public DAO() {}
103
If you have problems because of the server Timezone:
private String url =
"jdbc:mysql://localhost/myDB?serverTimezone=Europe/Paris";
private String username = "dbuser";
private String password = "1234";
Connection conn = null;
104
public void close() {
if (conn != null) {
try {
JDBC – conn.close();
DISCONNECT } catch (SQLException ex) {
FROM DB ex.printStackTrace();
}
}
}
105
public boolean validateUser(String user, String password) {
if (connect()) {
}
return false;
}
106
public List<String> getMessages() {
List<String> messages = new ArrayList<>();
if (connect()) {
String query = "select * from messages";
try {
PreparedStatement ps = c.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while(rs.next()){
JDBC – String message = rs.getString(“message”);
ACCESS messages.add(message);
}
METHOD } catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
}
return messages;
}
107
DATABASE ACCESS - SOLUTION 2
This solution is based on a Chád Darby’s Udemy course (http://www.luv2code.com/)
108
ANOTHER SOLUTION, THE SAME MVC….
We l
earn
ed ab
out t
h is
tt hi s
ou
ab
e arne d
al sol
We 109
ANOTHER SOLUTION, THE SAME MVC….
110
SOLUTION 2
FOUR STEPS
1. Write a java class to hold the data format for each table in the data base (this will
be the MODEL);
2. Write a java class helper to connect to the database (this is the same as a DAO);
3. Upload the jar driver file (mysql-connector-java-version.jar) to the server (put it in
WEB-INF/lib folder);
4. Define the file context.xml file in the server to create a pool of connections, in
the META-INF folder;
5. Adjust the servlet to use this connection.
111
STEP 1 - THE MODEL
For this example, we assume that we have a database on place with just this
simple table. These are Cadets (Students) at Galactica BattleShip:
112
STEP 1
THE
MODEL
getters and
setters for each
field
And so on…
MODEL
STEP 1
THE
STEP 2 - THE HANDLER (DAO)
115
THE
( DA O )
STEP 2 -
HANDLER
Th
ref is da
ere tas
fro nce our
m c
Se cam e’s
rvl es
et
116
STEP 2 -
Thi
THE
HANDLER
s m onnec
the
( DA O )
eth
c
od tions
to c
lose
Methods to
manipulate data
117
STEP 2 -
ata on!
THE
HANDLER d
( DA O ) t he acti
e
Se EL in
O D
M
118
An Object “Student”,
properly formatted is
STEP 2 - requested to be inserted
THE on to database
HANDLER
( DA O )
119
STEP 2 -
THE
HANDLER
( DA O )
120
STEPS 3 AND 4
You should put the java connector and a context.xml file, defining the connections
pool in the proper folders on the project. Pay attention to connector version that
should be compatible with Tomcat version and MySql version.
121
STEP 4 – DEFINING THE
CONTEXT.XML
122
ST E P 5
@Resource annotation
injects the connections
pool for our database in
the dataSource
We
crea
te
here the DA
data , pas O fr
thre So urce si n g om
ad t th e
akes (pool). E
a co a
nnec ch
tion
123