You are on page 1of 122

JAVA/JEE

PROGRAMMING PART 2

ESIGELEC
February 2023

João Pavão/Pedro Mestre


UTAD, 2023
1
PERSONAL PRESENTATION

• Name: João Pavão


• University: UTAD
(Universidade de Trás-os-Montes e Alto Douro)
at Vila Real
• Country: Portugal (PT)

2
PERSONAL PRESENTATION

• Name: João Pavão


• University: UTAD
(Universidade de Trás-os-Montes e Alto Douro)
at Vila Real
• Country: Portugal (PT)

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?

A servlet is a Java class that:


• Is processed on server;
• Use HTTP protocol (HTTP/1.1 – RFC 2616; HHTP/2 – RFC 7540):
• Can read HTML’s FORM data
• Generates HTML that is returned to the client
• Can use cookies and sessions

6
HOW DOES
THE SERVLET
WORK?

7
SERVLET LIFE CYCLE

http://www.javachain.com/servlet-life-cycle/)
8
SERVLET LIFECYCLE

When a request is mapped to a Servlet, the container performs the following


steps:
• If an instance of the Servlet does not exist, the web container:
–Loads the Servlet class;
–Creates an instance of the Servlet class;
–Initializes the Servlet instance by calling the init() method.
• The container invokes the service method, passing request and response
objects.
• If it needs to remove the Servlet, the container finalizes the Servlet by
calling the servlet's destroy() method.

9
QUESTION

How many Servlet instances will exist in


the server memory, if we have N clients
using the service simultaneously?

10
WHAT IS HTTP?

HTTP (HyperText Transfer Protocol):

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

HTTP (HyperText Transfer Protocol):

• Uses the Client/Server Model and It is a Request/Response protocol, based on two types
of messages:

– Requests, sent by clients;

– Responses, sent by servers.

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)

• Java EE 7 (June 12, 2013)

• Java EE 8 (September 21, 2017) ← Support for HTTP/2

• New version: Jakarta EE (Java EE was renamed) – Version 10

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

• The Java EE platform uses a


distributed multitiered model.

• Application logic is divided


into several components
according to their function.

• Application components are


installed on several machines,
depending on the tier to
which they belong.

(Enterprise
28

Information System)
Presentation-oriented
WEB TIER APPLICATIONS

Web components are part of Web applications (WebApps),


which are dynamic extensions of an application server.
WebApps can be:
• Presentation-oriented: A presentation-oriented web
application generates interactive web pages (HTML, CSS, etc)
and dynamic content in response to requests.
Service-oriented
• Service-oriented: A service-oriented web application
implements the endpoint of a web service (e.g. RESTful Web {“username”:“Pedro”,
services); “email”:“xxxxx@utad.pt”,
“id”: “12345”}
In this course we’ll going to talk about “Presentation-
oriented” WebApps
29
WEB TIER

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

Servlets are best suited for:

• Service-oriented applications;

• Control functions of a presentation-oriented application (for example


dispatching requests).

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

• doDelete – to handle a DELETE request.


• doGet - to handle a GET request.
• doHead – to handle an HTTP HEAD request.
• doOptions – to handle a OPTIONS request.
• doPost – to allow a servlet to handle a POST request.
• doPut – to allow a servlet to handle a PUT request.
• doTrace – to handle a TRACE request.

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

Information about the request is sent to the service method using a


HttpServletRequest object.
All requests implement the ServletRequest interface that allows web
modules to access information about:

• Parameters sent from clients to web applications;


• Object-valued attributes, used to share information;
• Protocol information;

• Localization related information.


HttpServletRequest also has methods to get Cookies and get the HTTP
method (GET, POST, etc).

42
PROCESSING REQUESTS

Some examples:

protected void doGet(HttpServletRequest req, HttpServletResponse resp){



String email = req.getParameter(“email”);

request.setAttribute(“validLogin”,true);
String encoding = req.getCharacterEncoding();
int remotePort = req.getRemotePort();

}
43
PROCESSING REQUESTS

Getting parameters sent in the request

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

Getting request headers

To get the request headers, we use the methods:

•String getHeader(String name)

•int getIntHeader(String name)

•long getDateHeader(String name)

•Enumeration<String> getHeaderNames()

•Enumeration<String> getHeaders(java.lang.String name)


45
PROCESSING REQUESTS

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”);

Note: for all scopes we also have:


Enumeration<String> getAttributeNames()
https://tomcat.apache.org/tomcat-9.0-doc/servletapi/javax/servlet/ServletContext.html
49
CODE EXAMPLES

There are more imports here…

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

Get an output stream to send data to the client

(…)
PrintWriter out = resp.getWriter();
(…)
out.println("<body>");
out.println("<div> Hello </div>");
out.println("</body>");

53
SERVLET RESPONSE

Setting the response type


(…)
PrintWriter out = resp.getWriter();
(…)
resp.setContentType("text/plain");
out.println("Hello!");
(…)

The above code changes the “Content-type” HTTP header to “text/plain”.


A complete list of content types can be found at: http://www.iana.org/assignments/media-
types/media-types.xhtml

54
SERVLET RESPONSE

Setting Status code



resp.setStatus(403); DEPRECATED

...
The above line of code is equivalent to:
resp.setStatus(HttpServletResponse.SC_FORBIDDEN); DEPRECATED

resp.sendError(HttpServletResponse.SC_FORBIDDEN, ”Forbiden: My message here");


(consider to use a try catch block with this instruction)
The full list of SC_….. fields can be found at: https://tomcat.apache.org/tomcat-9.0-
doc/servletapi/javax/servlet/http/HttpServletResponse.html

55
SERVLET RESPONSE

Setting the HTTP headers

Methods available to set the response headers are:


void setDateHeader(String name, long date)
void setHeader(String name, String value)
void setIntHeader(String name, int value)

Example:
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
resp.setHeader("Content-Disposition","attachment; filename=MyFile.txt");
out.println("Hello!");

56
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

If HTTP is stateless, how do we deal with the


information that we will need later?

59
QUESTION

If HTTP is stateless, how do we deal with the


information that we will need later?

Cookies → Data is stored on the client side.

Sessions → Data is stored on the server side.

60
COOKIES

There are several kinds of cookies:

61
COOKIES

There are several kinds of cookies:

62
COOKIES – GOING DEEP

What are cookies?


Because HTTP is a stateless protocol, we must have a method to store
information that might be needed later:.
We can store:
• session information on the server (we are going to see this in the next
lecture;
• information state on the client in the form of a cookie.
Cookies are small pieces of data, consisting in key/value pairs that are stored on
the client side.
When a server sends a cookie to a client, it expects that the client returns that
cookie in all subsequent HTTP transactions.
63
HOW DO WE MANAGE COOKIES AND

SESSIONS USING

64
COOKIES – GOING DEEP

From the persistence point of view, we can have:

Session cookies – as its name suggests are kept by the client only for the
duration of the session.

Permanent cookies – Unlike session cookies, are used to keep long-term


information and are store in persistent storage. These cookies are lost when
they expire.

65
CREATING COOKIES

How to create a cookie?

...

Cookie cookie = new Cookie("userName", "Pedro");

cookie.setMaxAge(-1); //this is a session cookie

resp.addCookie(cookie);

...

66
CREATING COOKIES

How to retrieve a cookie?

An example:

Cookie[] cookies = req.getCookies();


String user = null;

for (Cookie c : cookies){


if (c.getName().equals("userName")){
user = c.getValue(); // gets “Pedro”
}
}
67
CREATING COOKIES

How to retrieve a cookie?

Another example:

Cookie[] cookies = req.getCookies();


String user = null;

Map<String,Cookie> cookieJar = new Hashtable<>();

for (Cookie c : cookies){


cookieJar.put(c.getName(), c);
}

user = cookieJar.get("userName").getValue();
68
CREATING COOKIES

How to change the value of a cookie?


// First get the existing cookies, and see if your cookie (named TheCookie) is
// there
Cookie[] cookies = request.getCookies();
Cookie newCookie = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(”TheCookie")) {
newCookie = cookie;
break;
}
}
}
69
CREATING COOKIES

How to change the value of a cookie?


// If your cookie is there, set the new value for the cookie;
if (newCookie != null) {
newCookie.setValue(“newValue”);
}

// Add the updated cookie back to the response


response.addCookie(newCookie);

70
TRACKING SESSION INFORMATION

HTTP is stateless → it “forgets” the client requests after each transaction.

How can we store important information? We can use:

• Cookies (on the client side );

• Store session information on the server (we must have “extra” objects that store
these data).

It’s HTTP that is stateless, not the server!

To support applications that need to maintain state, Java Servlet technology provides
an API for managing sessions.

71
TRACKING SESSION INFORMATION

Sessions are represented by an instance of the HttpSession object.


We can access to a session object using the getSession method of a request object (if the request
does not have a session, it creates one).
HttpSession session = req.getSession();
Some methods of HttpSession:
Object getAttribute(String name)
Enumeration<String> getAttributeNames()
long getCreationTime()
String getId()
void invalidate()
void setMaxInactiveInterval(int interval)

72
STILL HAVE A QUESTION THOUGH…

How can we associate the session with the client?

73
STILL HAVE A QUESTION THOUGH…

How can we associate the session with the client?


Two solutions:

• We can use cookies Example:JSESSIONID=22562577CE80EF3B1DAAA0E48F2B6392


• We can encode the session id in links
http://localhost:8080/ServletTest/service;jsessionid=829F8836C240B51DD2F074259F242
833

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?

We learned about this

Now we will talk about this

76
WHAT IS A JSP?

A JSP page is a text document that contains two types of text:


• Static data,
• JSP elements, which construct dynamic content.

JSP are more suitable for Presentation-oriented Web Applications.

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:

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


<% String name = (String) request.getAttribute("userName"); %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>A JSP Page</title>
</head>
<body>
<h1> Hello <%= name %>!</h1>
</body>
</html>

78
JSP LIFECYCLE

When a client makes a request that is mapped to a JSP:

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

• Loads the servlet class;

• Instantiates an instance of the servlet class;

• Initializes the servlet instance by calling the jspInit() method.

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

• Static content (HTML, CSS, etc);

• JSP Directives;

• JSP Scripting elements.

• JSP Action Tags.

82
JSP DIRECTIVES

<%@ directive attribute="value" %>

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

A JSP declaration is used to declare variables and methods.


Syntax:
<%! scripting-language-declaration %>
Example :
<%!
private int someValue;
public void jspInit() {
//code to run at JSP init.
}
public void jspDestroy() {
//cleanup code.
}
%>

84
JSP SCRIPLETS

JSP scriptlet are used to contain any valid code fragment. Syntax:

<% scripting-language-statements %>


Example (inside a html page):

<%
List<String> messages = dao.getMessages();
for (String msg : messages){
%>

<p> <%= msg %> </p>

<%
}
%>

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

<%@ include ... %> ← executed at time of conversion (it is static).

In some situations, we might need to dynamically include other resource. We


can do this using the jsp:include action tag.

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

Now, how do we do that?

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:

RequestDispatcher dispatcher = request.getRequestDispatcher("/resource.jsp");


dispatcher.forward(request, response);

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:

• The client requests the resource;


• The server responds with a 302-status code and sends the Location of the
resource to load in an HTTP header;
• The client loads the new resource.

Using forward, there is a single HTTP transaction:


• Client sends request;
• Server forwards the request to another Servlet or JSP;
• The latter responds to the client.

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):

On the “sender” servlet.



Data data = new Data();
HttpSession session = request.getSession();
...
session.setAttribute("DataObject", 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):

On the “receiver” servlet.


...
HttpSession session = request.getSession();
Data data;
if (session.getAttribue(“DataObject”)!= null){
data = (Data) session.getAttribute("DataObject");
}

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):

On the “sender” servlet.



Data data = new Data();
request.setAttribute("DataObject", data);

96
HOW TO SHARE DATA? – EXAMPLE 2

Using a request scope object (assuming that we have a Java class called
Data):

On the “receiver” servlet.

...
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

Now lets learn this

We also learned about this

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() {}

JDBC – public boolean connect() {


try {
CONNECT conn = DriverManager.getConnection(url,username, password);

TO DB } catch (SQLException ex) {


return false;
}
return true;
}

No need for constructor in this example.

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;

JDBC – public DAO() {}

CONNECT public boolean connect() {


TO DB try {
conn = DriverManager.getConnection(url,username,password);
} catch (SQLException ex) {
return false;
}
return true;
}

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()) {

String query = "select * from user where name=? and password=?";


try {
PreparedStatement ps = c.prepareStatement(query);
ps.setString(1, user);
ps.setString(2, password);
JDBC –
ACCESS ResultSet rs = ps.executeQuery();
return rs.next();
METHOD
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}

}
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

Another solution to this part

We also learned about this

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:

Student table: Student.java file:


ID first_name last_name email
1 William Adama billadama@galactica.cp
2 Kara Trace karatrace@galactica.cp
JAVA

112
STEP 1
THE
MODEL

getters and setters


for each field
113
114

getters and
setters for each
field
And so on…
MODEL
STEP 1
THE
STEP 2 - THE HANDLER (DAO)

Let's call this class StudentDAO.java. This class will not


take a static connection to the database. Instead, for
each thread of the servlet this class will ask for a connection
to the database that lives in a Tomcat’s pool of connections (
STEPS 3 and 4 - we’ll se later how this is setup in Tomcat)

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

You might also like