SlideShare a Scribd company logo
1 of 125
Download to read offline
JSP and SERVLET 
Creating Web Applications 
by www.javathlon.com
www.javathlon.com 
Client - Server Web Applications 
CLIENT SERVER HTTP PROTOCOL 
HTML PAGE PROCESS DATA AND 
RESPOND WITH RESULT
www.javathlon.com 
Client - Server Web Applications 
CLIENT SERVER HTTP PROTOCOL 
HTML PAGE PROCESS DATA AND 
RESPOND WITH RESULT
www.javathlon.com 
HTTP PROTOCOL 
STANDART BEHAVIOURS 
● GET method 
Ask server for a resource via a URI 
(HTML page, image, MP3 etc) 
● POST method 
Sent a web form to server and get a resource 
● Other methods 
HEAD, PUT, DELETE, TRACE
www.javathlon.com 
Client - Server Web Applications 
CLIENT SERVER HTTP PROTOCOL 
HTML PAGE PROCESS DATA AND 
RESPOND WITH RESULT
www.javathlon.com 
Client - Server Web Applications 
CLIENT HTTP PROTOCOL 
JSP PAGE 
PROCESSING UNIT 
(SERVLET) 
PROCESSING UNIT 
(SERVLET) 
SERVER 
PROCESSING UNIT 
(SERVLET) 
DATABASE
www.javathlon.com 
NEED FOR APPLICATION SERVERS 
● Dispatch requests 
● Thread management 
● Session management 
● Caching and object pooling 
We will use APACHE TOMCAT
www.javathlon.com 
Reminders 
How a J2EE project runs? 
● Client side consists of JSP pages. 
A JSP is an HTML page with special tags to get 
or send dynamic data from/to server. 
● Servlets carry business code on server side 
and redirects the client to proper pages as 
result. 
● JSPs and servlets communicate via HTTP 
protocol. Mostly GET and POST methods.
www.javathlon.com 
Reminders 
How a J2EE project runs? 
JSP and servlets are contained in web 
application servers ( servlet containers) such 
as Apache Tomcat. 
We develop configuration files such as web. 
xml to regulate interactions among JSPs, 
servlets and other resources.
www.javathlon.com 
TECHNOLOGY STACK 
Programming IDE Servlet Container 
(Application server) 
Java Runtime Environment 6
www.javathlon.com 
SERVLET MECHANISM 
SERVLET 
Http Servlet Request 
Return an HTML content 
Return a multimedia file 
Redirect the client to a page 
Forward request to another servlet 
Get or Post Method
www.javathlon.com 
HTTPSERVLETREQUEST 
GET method 
POST method 
SERVLET 
When you enter a web address to a web browser, it requests the 
resource by GET method. 
The request body is limited to about 250 characters. 
Sample:https://www.google.com.tr/?q=java&safe=off&output=search 
You need to send a web form for using POST method. The request body 
is limitless
www.javathlon.com 
HTTPSERVLETRESPONSE 
Talha Ocakci 
Return an HTML content 
Return a multimedia file 
Navigate the client to another page 
Forward request to another servlet 
SERVLET 
Request 
Content-Type: text/html 
Use: PrintWriter object of HTTPServletResponse 
Content-Type: application/pdf, image/jpeg... 
Use: OutputStream object of HTTPServletResponse 
Content-Type: none 
Use: sendRedirect() method 
Content-Type: none 
Use: RequestDispatcher object of ServletContext
www.javathlon.com 
HTTPSERVLETRESPONSE 
Return an HTML content 
Return a multimedia file 
Navigate the client to another page 
Forward request to another servlet 
SERVLET 
Request 
Content-Type: text/html 
Use: PrintWriter object of HTTPServletResponse 
Content-Type: application/pdf, image/jpeg... 
Use: OutputStream object of HTTPServletResponse 
Content-Type: none 
Use: sendRedirect() method 
Content-Type: none 
Use: RequestDispatcher object of ServletContext
www.javathlon.com 
SCRIPTLET in JSP 
A scriptlet is a piece of Java-code embedded in the HTML. 
The scriptlet is everything inside the <% %> tags. 
Between these the user can add any valid Scriplet i.e. any 
valid Java Code.
www.javathlon.com 
IMPLICIT OBJECTS in JSP 
They are the objects that you can use inside scriptlets 
application javax.servlet.ServletContext 
out javax.servlet.jsp.JspWriter 
request javax.servlet.ServletRequest 
response javax.servlet.ServletResponse 
session javax.servlet.http.HttpSession 
page java.lang.Object 
servletconfig javax.servlet.ServletConfig
www.javathlon.com 
OBJECT SCOPES 
in SERVLETCONTEXT 
Application Scope 
Request 
Scope 
Session scope
www.javathlon.com 
HTTP SESSION OBJECT 
SESSION ID 
Session object 
Attribute map 
name1 value1 
name2 value2
www.javathlon.com 
HTTPSERVLETRESPONSE 
Talha Ocakci 
Return an HTML content 
Return a multimedia file 
Navigate the client to another page 
Forward request to another servlet 
SERVLET 
Request 
Content-Type: text/html 
Use: PrintWriter object of HTTPServletResponse 
Content-Type: application/pdf, image/jpeg... 
Use: OutputStream object of HTTPServletResponse 
Content-Type: none 
Use: sendRedirect() method 
Content-Type: none 
Use: RequestDispatcher object of ServletContext
www.javathlon.com 
REDIRECTING REQUEST 
Request forwarding and redirection are different 
concepts. 
When you forward a request, request and response 
objects are transferred. Url stays the same. 
When you redirect the request to another 
JSP/servlet, request and response objects are not 
transferred to new object. URL changes to the 
directory of new page.
www.javathlon.com 
Tip for being a wanted J2EE 
developer 
● Avoid using JAVA code inside a JSP file. Use 
JSP directives and JSP actions instead. 
● Avoid using HTML code inside a servlet. 
Instead, use HTML code in JSP page and 
pass values it from the servlet.
www.javathlon.com 
JSP Actions 
● jsp:useBean 
Searches for an objects inside the given scope 
● jsp:getProperty 
● jsp:setProperty 
Gets/sets a value of a given object
www.javathlon.com 
jsp:useBean action 
<jsp:useBean 
id="memberInfo" 
class="com.qapro.register.MemberInfo" 
scope="request"> 
</jsp:useBean> 
request.getParameter(“memberInfo”) 
<jsp:useBean 
id="memberInfo" 
class="com.qapro.register.MemberInfo 
scope="session"> 
</jsp:useBean> 
request.getSession().getParameter(“memberInfo”) 
<jsp:useBean 
id="memberInfo" 
class="com.qapro.register.MemberInf 
scope="application"> 
</jsp:useBean> 
ServletContext sc = getServletContext(); 
sc.getAttribute(“memberInfo”)
www.javathlon.com 
jsp:getProperty and jsp:setProperty 
Gets/sets an attribute of an 
object with a given id
www.javathlon.com 
JSTL BASICS 
Java Server Tag Library 
Provides shorthand notation to access: 
● Attributes of standard servlet objects 
● Bean properties 
We use them, because writing JAVA code 
inside JSP is not a good practice. It is a third 
party library of Apache Foundation.
www.javathlon.com 
JSTL and JAVA Code Relation 
Iterating over a list 
JAVA NOTATION 
<ul> 
<% 
for(int i=0; i<messages.length; i++) { 
String message = messages[i]; 
%> 
<li><%= message %></li> 
<% } %> 
</ul> 
JSTL NOTATION 
<ul> 
<c:forEach var="message” items="${messages}"> 
<li>${message}</li> 
</c:forEach> 
</li>
www.javathlon.com 
FULL LIST OF JSTL TAGS
www.javathlon.com 
CLUE 
WEB APPLICATION 
WEB BROWSER 
ask for sth 
show result
www.javathlon.com 
CLUE 
A basic web application is nothing more than a system that populates data 
from a database, insert into it, modify the data and visualize it. 
USER INTERFACE DATABASE 
WEB APPLICATION 
sends input 
select 
delete & 
update 
insert 
shows result
www.javathlon.com 
WORKING WITH DATABASE 
Description 
A database is any file or 
file system that you can 
● store your data 
● manipulate data 
● search for a desired 
item
www.javathlon.com 
WORKING WITH DATABASE 
Database Types 
● Flat files (text or binary) 
● Flat file systems 
● Non - relational databases (eg. MongoDB) 
● Relational databases (eg. MySQL)
www.javathlon.com 
WORKING WITH DATABASE 
Why use RDBMS? 
Relational Database 
Systems: 
Ease your tasks for 
quickly inserting, 
updating, querying, 
deleting the data you 
have on your hands 
using SQL.
www.javathlon.com 
WORKING WITH DATABASE 
Relational Databases 
Relational Database Systems: 
Stores the data in tables and relations between 
those tables.
www.javathlon.com 
WORKING WITH DATABASE 
Relational Database Structure 
Table: A real world or imaginary entity model 
that has attributes. (A user metadata) 
Row: An instance of a entity model (A user 
instance) 
Column: Attribute of an entity (User’s name) 
Primary key: Identifier of a instance (User’s 
id) 
Foreign key: Dependency of an entity to 
another entity (Reference to user’s question)
WORKING WITH RELATIONAL www.javathlon.com 
DATABASES 
First example - Tables and columns 
Keep track of all money transfers in a bank. You need to store this data permanently. 
ROW 1 ROW 2 
Sender name John 
Sender surname Lennon 
Sender account no 79879878978 
Receiver name Paul 
Receiver surname McCartney 
Receiver account no 12121212121 
Amount 300 
Currency USD 
Date 1.1.2014 
Sender name Kirk 
Sender surname Hammett 
Sender account no 565656565 
Receiver name James 
Receiver surname Hetfield 
Receiver account no 808080801 
Amount 50000 
Currency USD 
Date 3.1.2014 
attribute value 
DB TABLE (MONEY TRANSFER)
www.javathlon.com 
SQL 
(Structured Query Language) 
● DDL (Data Definition Language) 
Used to create or modify tables, data types of 
columns 
● DML (Data Manipulation Language) 
Used to insert, update, delete data and query 
for desired data
www.javathlon.com 
DATA TYPES 
● String types 
● Numeric types 
● Date & Time types 
● Binary objects
www.javathlon.com 
WORKING WITH RELATIONAL 
DATABASES 
Creating table structures 
Done with DDL (Data Definition Language ) 
CREATE TABLE money_transfer( 
transfer_id INTEGER PRIMARY KEY, 
sender_name VARCHAR(50) NULL, 
sender_surname VARCHAR(50) NULL, 
sender_surname VARCHAR(50) NULL, 
sender_account_no VARCHAR(20) NULL, 
receiver_name VARCHAR(50) NULL, 
receiver_surname VARCHAR(50) NULL, 
receiver_account_no VARCHAR(50) NULL, 
amount FLOAT; 
currenct VARCHAR(4) NULL, 
transfer_date DATE NULL 
); 
Sender name John 
Sender surname Lennon 
Sender account no 79879878978 
Receiver name Paul 
Receiver surname McCartney 
Receiver account no 12121212121 
Amount 300 
Currency USD 
Transfer Date 1.1.2014
WORKING WITH RELATIONAL www.javathlon.com 
DATABASES 
First example - Breaking the data into smaller units 
Multiple similar records means lots of repetition and repetition means mess. 
For preventing the repetition, we break the data into multiple columns. 
Sender name John 
Sender surname Lennon 
Sender account no 79879878978 
Receiver name Paul 
Receiver surname McCartney 
Receiver account no 12121212121 
Amount 300 
Currency USD 
Date 1.1.2014 
Sender name John 
Sender surname Lennon 
Sender account no 79879878978 
Receiver name George 
Receiver surname Harrison 
Receiver account no 12045872 
Amount 400 
Currency USD 
Date 1.2.2014 
Sender name John 
Sender surname Lennon 
Sender account no 79879878978 
Receiver name Ringo 
Receiver surname Start 
Receiver account no 13698985 
Amount 500 
Currency USD 
Date 1.3.2014
WORKING WITH RELATIONAL www.javathlon.com 
DATABASES 
First example - Data normalization 
● Basic client data is extracted from the money transfer information. 
● Client data is stored in another table. Identifier of the record inside client table is 
referenced from money transfer table 
Sender Client data 
121 
Receiver name George 
Receiver surname Harrison 
Receiver account no 12045872 
Amount 400 
Currency USD 
Date 1.2.2014 
Sender Client data 
121 
Receiver name Ringo 
Receiver surname Starr 
Receiver account no 13698985 
Amount 500 
Currency USD 
Date 1.3.2014 
Client data 
Client id 121 
Client name John 
Client surname Lennon 
Client account no 79879878978 
Client id( Foreign key)
www.javathlon.com Tip for being a wanted J2EE 
developer 
A database table 
SHOULD correspond 
to at least one real 
world or virtual entity. 
DATABASE TABLE DESIGN PRINCIPLES 
1
www.javathlon.com 
Tip for being a wanted J2EE 
developer 
2 
Dependent entities 
should reference to the 
owner entity for data 
integration. 
DATABASE TABLE DESIGN PRINCIPLES
www.javathlon.com 
DATABASE DESIGN 
for the 
USER MANAGEMENT 
MODULE 
of 
QA PLATFORM
www.javathlon.com 
REGISTRATION 
Insert a user with 
● username, 
● password 
● and other personal details.
www.javathlon.com 
AUTHENTICATION 
Check if given username-password pair exists 
in database.
www.javathlon.com 
REGISTRATION 
DB SCHEMA 
STANDART MUST-DOs 
1. Put a primary key. 
2. Put insertion date, 
3. Put active/passive bit 
BUSINESS SPECIFIC 
1. Store username and 
password 
2. Store personal details
www.javathlon.com 
REGISTRATION 
CREATE TABLE 
CREATE TABLE `user` ( 
`user_id` int(11) NOT NULL, 
`user_name` varchar(45) DEFAULT NULL, 
`password` varchar(45) COLLATE DEFAULT 
NULL, 
`is_active` bit(1) DEFAULT NULL, 
`name` varchar(45) DEFAULT NULL, 
`surname` varchar(45) DEFAULT NULL, 
`insert_date` datetime DEFAULT NULL, 
`role_name` varchar(45) DEFAULT NULL, 
PRIMARY KEY (`user_id`) 
)
A PRIMER FOR DATA MANIPULATwwIwO.javNath lon.com 
with SQL 
Insert data 
INSERT INTO TABLENAME 
(first_column,...last_column) 
VALUES (first_value,...last_value); 
INSERT INTO user 
(user_id, user_name, password) 
VALUES (1, 'paul_weller','hzf1234fddf')
A PRIMER FOR DATA MANIPULATwwIwO.javNath lon.com 
with SQL 
Primary key 
insert into user (user_id, user_name, password) values(100, 
'paul_weller','hzf1234fddf') 
Error Code: 1062. Duplicate entry '100' for key 'PRIMARY' 0.000 sec 
Each table HAS TO have a primary key. This lets your database vendor 
to allocate unique space for each record in any tables. 
insert into user ( user_name, password) values 
('eddie_vedder','hzf1234fddf'); 
Each table HAS TO have a primary key. This lets your database vendor 
to allocate unique space for each record in any tables. 
You will see user_id column gets unique values one by one.
www.javathlon.com 
A PRIMER FOR DATA MANIPULATION 
with SQL 
Update a record 
update TABLENAME 
set COLUMNNAME = VALUE 
update user 
set user_name= ‘hgklkg45784’
www.javathlon.com 
A PRIMER FOR DATA RETRIEVAL 
with SQL 
Retrieve all records 
DO NOT use * in select clauses. 
Using * is a good example of cutting corners 
that junior developers do. 
Define which columns you exactly need and 
want to populate.
A PRIMER FOR DATA RETRIEVAL wwwwi.jtavhath lon.com 
SQL 
Restrict records 
select COLUMN1,COLUMN2 
from TABLENAME 
where COLUMN1 = VALUE 
and/or COLUMN2 = VALUE2 
select user_name from user 
where user_name =’'paul_weller'’ and 
password = ‘'hzf1234fddf'’
www.javathlon.com 
IN NEXT CHAPTER 
● Database Connections 
● Transactions 
● What is ACID? 
● Committing and rolling the transactions 
back 
● DB Engine - Java communication
www.javathlon.com 
DATABASE CONNECTIONS 
Database connection is the means by which 
a database server and its client software 
communicate with each other.
www.javathlon.com 
WHY WE NEED DATABASE 
CONNECTIONS? 
We send the commands to DB server and get the results 
via an open DB connection. 
DB SERVER 
Java web 
application DB CONNECTION
www.javathlon.com 
COMMUNICATION BETWEEN JAVA 
AND DATABASE 
Database talks 
SQL, but Java does 
not know how to 
talk in SQL, it 
needs a translator 
called JDBC (Java 
Database 
Connector).
www.javathlon.com 
DB CONNECTION POOLS 
DB connection opening and closing is so 
expensive operations compared to execute 
basic queries. 
Instead of open/close a connection for each 
query, create a bunch of connections* and use 
them over and over again. 
* = Connection pool
www.javathlon.com 
DB CONNECTION POOL USAGE
www.javathlon.com 
CONNECTION POOL 
Implementations in Java 
● C3P0 
● BoneCP 
...
www.javathlon.com 
DATABASE TRANSACTIONS 
A unit of work performed within a database 
management system against a database.
www.javathlon.com 
DATABASE TRANSACTIONS 
ALL OR NOTHING PRINCIPLE 
1. Open connection 
2. Begin transaction 
3. Debit $100 to Groceries Expense Account 
4. Credit $100 to Checking Account 
5. Commit transaction 
6. Close connection 
TRANSACTION
www.javathlon.com 
ACID 
Properties that a transaction must have 
Atomicity: 
Based on “all or nothing” principle 
All statements succeed or all fail in case of 
any power failures, errors, and crashes.
www.javathlon.com 
ACID 
Properties that a transaction must have 
Consistency: 
If, for some reason (eq: programming error), a 
transaction is executed that violates the 
database’s consistency rules, the entire 
transaction will be rolled back and the 
database will be restored to a state consistent 
with those rules. 
eq: NULL inserting to a not-nullable column
www.javathlon.com 
ACID 
Properties that a transaction must have 
Isolation: 
Before committing a transaction, 
modifications should not be visible to another 
transaction.
www.javathlon.com 
ACID 
Properties that a transaction must have 
Durability: 
Durability guarantees that the database will 
keep track of pending changes in such a way 
that the server can recover from an abnormal 
termination.
www.javathlon.com 
DATABASE DESIGN 
for the 
USER ROLE 
MANAGEMENT MODULE
www.javathlon.com 
User Role- Permissions Logic 
MODERATOR 
MODIFY POST DELETE POST CREATE POST 
USER 1 
USER 2
www.javathlon.com 
User Role- Permissions 
Logic 
Required permissions: 
1- Deleting posts 
2- Correcting posts 
Required permissions: 
1- Accepting new users 
2- Deleting users 
John Hopkins is 
a moderator. 
A moderator has 
permissions for 
1- Deleting posts 
2- Correcting 
posts
www.javathlon.com 
Tip for being a wanted J2EE 
developer 
Why not assign the permissions directly to the 
user but assign to a role? 
Because adding or removing the permissions to a 
role, lets the system grant or revoke this 
permission from all the users who belong to this 
role. 
Otherwise you would execute this modification 
on all users and this means a huge cost.
www.javathlon.com 
Requirements: 
● TABLE RELATIONS 
(1 to MANY, MANY to 1, MANY to MANY) 
● SQL JOINS 
(inner join, left join, right join, full join, 
self join)
www.javathlon.com 
THE MEANING OF RELATIONAL 
in RELATIONAL DATABASES 
One object may belong to how many other 
owner objects? 
One object may own to how many other 
dependent objects?
www.javathlon.com 
TABLE RELATIONS 
ONE TO ONE 
USER USER-DETAILS 
(Country, Height, Weight ...) 
If you safely can add the columns in one 
table to another relation means 1-1.
www.javathlon.com 
TABLE RELATIONS 
ONE TO ONE 
OPTION 1 
USER TABLE 
USER ID USER NAME COUNTRY REGISTRATION 
DATE 
HEIGHT WEIGHT TIMEZONE 
USER TABLE 
USER ID USER NAME REGISTRATION 
DATE 
USER DETAILS TABLE 
USER ID HEIGHT WEIGHT COUNTRY 
OPTION 2
www.javathlon.com 
TABLE RELATIONS 
ONE TO MANY 
ONE MANY 
QUESTION ANSWER 1 
● A question may own two answers. 
● But, an answer can not be given two 
multiple questions. 
ANSWER 2 
QUESTION ANSWER 3
www.javathlon.com 
TABLE RELATIONS 
MANY TO MANY 
MANY MANY 
USER TOPIC 1 
● A user may follow multiple topics 
● A topic may be followed by multiple 
users. 
TOPIC 2 
USER TOPIC 3
www.javathlon.com 
TABLE RELATIONS 
MANY TO MANY 
USER TABLE 
USER ID USER NAME USER NICKNAME 
1 Talha Ocakçı talhaocakci 
2 James Dio dio 
TOPIC TABLE 
TOPIC ID TOPIC NAME 
1 Geography 
2 History 
USER FOLLOWED TOPICS 
USER ID TOPIC ID FOLLOW TIME 
1 1 10.06.2014 
2 1 18.06.2014 
2 2 18.07.2014
www.javathlon.com 
JOINING TABLES 
To retrieve and combine different attributes of 
an entity from several tables. 
SELECT CLAUSE + 
FROM CLAUSE + 
JOIN CLAUSE (multiple) + 
WHERE CLAUSE +
www.javathlon.com 
JOINING TABLES 
Inner Join 
Both tables must have the same value on 
joined columns. 
eq. Populate list of permissions that a user 
has.
www.javathlon.com 
JOINING TABLES 
Left (Outer) Join 
If a row in table 1 does not have a match in 
table 2, it still exists in result set.
www.javathlon.com
IMPLEMENTING 
JAVA WEB APPLICATION
www.javathlon.com 
WHAT WE WILL DO? 
1. Without caring of user interface design, 
focus on the technical details. 
2. Find the most time consuming phases in 
development and ease them professionally
www.javathlon.com 
REGISTER USER 
Get username, email, 
name, surname of user 
and post it to servlet 
JSP 
1. Get values from request 
2. Get DB connection 
(Create or get one from DB 
connection pool) 
3. Start transaction 
4. Insert user to DB 
5. Release all resources 
6. Put message into 
response 
6. Redirect to another 
page 
SERVLET 
Show the 
message inside 
JSP
www.javathlon.com 
JDBC CLASSES 
Statement 
● Contains a static SQL statement 
● Not reusable 
PreparedStatement: 
● Contains precompiled SQL statement. 
● Used to efficiently execute this statement 
multiple times by just setting parameters.
www.javathlon.com 
JDBC CLASSES 
ResultSet 
Holds the database result row by row 
Holds the metadata of the DB result (count, 
column names, etc)
www.javathlon.com 
JAVA - MYSQL TYPE 
CORRESPONDENCE
www.javathlon.com 
RESULT SET OBJECT 
VALUES METADATA 
talha ocakci talhaocakci 
paul auster paulauster 
... ... ... 
Count 
Column 
types 
Schema 
name 
Table name 
... 
POINTER
www.javathlon.com 
RESULT SET OBJECT 
resultset.next() method moves the pointer to next row. 
If reaches to the end it returns false. 
talha ocakci talhaocakci 
paul auster paulauster 
... ... ... 
POINTER 
Initially, it points to the very beginning of the ResultSet 
object but not the first row. To get the first row, you 
need to invoke next() before iterating.
www.javathlon.com 
REGISTER USER 
Get username, email, 
name, surname of user 
and post it to servlet 
JSP 
1. Get values from request 
2. Get DB connection 
(Create or get one from DB 
connection pool) 
3. Start transaction 
4. Insert user to DB 
5. Release all resources 
6. Put message into 
response 
6. Redirect to another 
page 
SERVLET 
Show the 
message inside 
JSP
www.javathlon.com 
CONNECTION POOLS 
Created on servlet containers (Tomcat 7) or 
application servers (JBOSS, Glassfish, etc..) 
and can be access by JNDI 
Created with C3P0 independent from a servlet 
container or an application server.
www.javathlon.com 
CONNECTION POOLS 
Configuration 
Min connection size: Whatever happens, 
connection number will not drop below this. 
Max connection: Number of connection can 
not exceed this number. 
Timeout: If idle time of a connection exceeds 
this time, it returns back to pool 
automatically.
www.javathlon.com 
INITIALIZE RESOURCE WHILE 
BOOTSTRAPPING 
● Mark your servlet for automatic invoking 
while bootstrapping the application in 
deployment descriptor. 
marker: load-on-startup tag. 
● Initialize resources in init() method of 
servlet.
www.javathlon.com 
EMAIL VALIDATION 
1- Insert the new user record to user table 
2- Insert a related record to email-validation 
table including user id and validation code. 
3- Email the validation url including the 
validation code to user’s email. 
4- When sent link is clicked, check the 
validation code in url against the one in DB.
www.javathlon.com 
EMAIL VALIDATION 
When a connection is created, it is in 
auto-commit mode. 
The way to allow two or more 
statements to be grouped into a 
transaction is to disable the auto-commit 
mode.
www.javathlon.com 
GET GENERATED KEYS 
preparedStatement.getGeneratedKeys() 
returns a Result Set with one column and 
one row: 
POINTER 
VALUES 
29
www.javathlon.com 
WORKING IN PROFESSIONAL 
SOFTWARE DEVELOPMENT TEAMS
www.javathlon.com 
WORKING IN A TEAM 
If team members use; 
● Different approaches to similar problems 
● Different relations between software 
layers... 
There will be chaos later on.
www.javathlon.com 
WORKING IN PROFESSIONAL 
SOFTWARE DEVELOPMENT TEAMS 
Why do we use design patterns? 
Developers agree on the best solutions and 
apply them for similar problems.
www.javathlon.com 
SOFTWARE ARCHITECTURE AND 
DESIGN PATTERNS 
Design patterns 
ensure the project 
will not fail by the 
time passing. If you 
don’t obey the 
rules, the failure 
underneath will be 
observed.
www.javathlon.com 
DESIGN PATTERN and STRATEGY 
Design Pattern: Describes a solution to a 
common problem in a context. 
Strategy: The real implementation of the 
pattern
www.javathlon.com 
EXAMPLES in SOFTWARE 
ENGINEERING 
Problem: I create huge objects over and 
over again, so project consumes so much 
memory. 
Solution: Use a single instance 
and reuse it whenever possible. 
Pattern: Singleton pattern 
Meaning: Create one and use it over and 
over. 
Example: Our DB connection pool
www.javathlon.com 
EXAMPLES in SOFTWARE 
ENGINEERING 
Problem: I have too many controllers 
(servlets), so I lost the control of 
redirecting the requests. 
Solution: Use a common class to 
redirect all requests so that you can 
manage in just one place. 
Pattern: Front controller pattern 
Example: DispatcherServlet in Spring 
framework
www.javathlon.com 
EXAMPLES in SOFTWARE 
ENGINEERING 
Problem: I forgot to release 
the resources after DB 
operations and I don’t want to 
copy and paste the same code 
to everywhere. 
Solution: Move the 
boilerplate code to another 
common class. 
Pattern: Template pattern 
Example: We will implement 
now.
www.javathlon.com 
BIG PICTURE of DESIGN PATTERNS 
1. Creational Patterns 
a) Singleton 
b) Factory 
c) Prototype 
d) Builder 
2. Behavioural Patterns 
a) Template 
b) Mediator 
3. J2EE Patterns 
a) Front Controller 
b) DAO Pattern 
c) Model View Controller 
d) View Helper 
and so on...
www.javathlon.com 
BIG PICTURE of DESIGN PATTERNS
www.javathlon.com 
CORRECT USAGE DOSE of PATTERNS
www.javathlon.com 
IMPLEMENT TEMPLATE PATTERN 
Why we need them? 
1- You will possibly forget common operations 
like closing DB connection, Prepared 
Statement and ResultSet. 
2- You will repeatedly copy tens of lines of 
initialization, resource cleaning code for 
simple queries.
www.javathlon.com 
IMPLEMENT TEMPLATE PATTERN 
A class extends an abstract class that do the boilerplate things 
Concrete class Abstract class 
1. Resource allocating 
2. Execute DB operations 
Populate Result Set 
3. Resource releasing 
Get DB Connection 
Create PreparedStatement 
Start transaction 
Commit transaction 
Close connection 
Close PreparedStatement 
Close ResultSet
www.javathlon.com 
DATA ACCESS OBJECT PATTERN 
Problem: 
1- You should separate business and DB operations. 
In service layer, you should just deal with business. 
Not with DB specific ugly code, connections, etc. 
2- You need a real entity object but not a 
collection of low level strings, numbers, booleans… 
3- You need to run unit tests.
www.javathlon.com 
DATA ACCESS OBJECT PATTERN 
VIEW 
LAYER 
(Shows 
model’s 
attributes) 
SERVICE 
LAYER 
(Combines multiple 
DAOs if required) 
DB LAYER 
(DAO) 
Each class deal 
with just one DB 
table 
MODEL REAL 
ENTITY 
Get result set, place basic 
values 
into entity instances.
www.javathlon.com 
RELATION between DAO and 
TEMPLATE PATTERNS 
VIEW CONTROLLER 
DB LAYER 
MODEL (DAO) REAL 
ENTITY 
TEMPLATE 
PATTERN 
USED BY 
Get result set, place basic values 
into entity instances. 
Might be the same type of object or two separate 
object types that may adapted to each other
www.javathlon.com 
● DAO Connection Scoping 
○ Method Scope 
○ Instance Scope 
○ Thread Scope
www.javathlon.com 
UNIT TESTING DAO LAYER 
Unit testing means executing a method 
without an application server. 
1- Using JUnit 
2- (Fake unit testing) Simply by using an main 
class.
www.javathlon.com 
BEFORE AJAX
www.javathlon.com 
AFTER AJAX (Async Javascript & XML)
www.javathlon.com 
XMLHttpRequest object 
Provides the ability to 
1- Send asynchronous requests to the server 
side. 
2- Be noticed in each step of the flow (request 
sent, headers received, loading, done, error 
occurred)
www.javathlon.com 
XMLHttpRequest object
www.javathlon.com 
XXMMLLHHtttptRpeRqueeqsut eobsjte cotb mjeecthto mdsethods 
open(method, url) 
Ex: open(“POST”, “Voting”) 
setRequestHeader(name, value) 
Ex: setRequestHeader("Content-type", 
"application/x-www-form-urlencoded") 
send(data) 
Ex: send(“questionId=1&type=UP”)
www.javathlon.com 
XXMMLLHHtttptRpeRqueeqsut eobsjte c- tr meeatdhyoSdstate 
Shows the internal state of the XMLHttpRequest instance. 
When it is switched to another state, you are informed via 
a readyStateChangeEvent. You can update your HTML 
page accordingly. 
STATE NUMERIC 
VALUE 
DESCRIPTION 
UNSENT 0 The object has been constructed. 
OPENED 1 The open() method has been successfully invoked 
HEADERS_RECEIVED 2 All redirects (if any) have been followed and all HTTP headers of 
the final response have been received. Several response 
members of the object are now available. 
LOADING 3 The response entity body is being received. 
DONE 4 The data transfer has been completed or something went wrong 
during the transfer
www.javathlon.com 
Communicate with XMLHttpRequest 
Event name Interface Dispatched when… 
readystatechange Event The readyState attribute changes value, except when it changes to 
UNSENT. 
loadstart ProgressEvent The request starts. 
progress ProgressEvent Transmitting data. 
abort ProgressEvent The request has been aborted. For instance, by invoking the abort() 
method. 
error ProgressEvent The request has failed. 
load ProgressEvent The request has successfully completed. 
timeout ProgressEvent The author specified timeout has passed before the request 
completed. 
loadend ProgressEvent The request has completed (either in success or failure).
www.javathlon.com 
XMLHttpRequest 
Status codes 
CODE STATUS 
200 SUCCESSFUL 
301 MOVED PERMANENTLY 
403 FORBIDDEN 
404 NOT FOUND
www.javathlon.com 
XMLHttpRequest 
Handling Successful State 
Successful state means 
● readyState = 4 
● status = 200
www.javathlon.com 
SUCCESSFUL AJAX FLOW 
HTML PAGE 
XMLHttpRequest 
instance Server 
Create 
Open 
Send 
readyStateChange:1 
readyStateChange:2 
process 
readyStateChange:3 
status : 200 
readyStateChange:4 
status : 200 
Manipulate the 
HTML 
send data to server 
send result (JSON, string) 
onReadyStateChange 
event
www.javathlon.com 
AJAX CALL FLOW 
● Create an XMLHttpRequest instance. 
● Configure the url and method 
● Send data 
● Obtain and parse the result 
● Manipulate your HTML page accordingly.
www.javathlon.com

More Related Content

What's hot

Java Servlets
Java ServletsJava Servlets
Java Servlets
Nitin Pai
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 

What's hot (20)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Jsp
JspJsp
Jsp
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 

Viewers also liked

Viewers also liked (7)

Oreilly head-first-servlets-and-jsp
Oreilly head-first-servlets-and-jspOreilly head-first-servlets-and-jsp
Oreilly head-first-servlets-and-jsp
 
Servlets
ServletsServlets
Servlets
 
Heap and stack space in java
Heap and stack space in javaHeap and stack space in java
Heap and stack space in java
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 

Similar to JAVA EE DEVELOPMENT (JSP and Servlets)

Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
b_kathir
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
Geethu Mohan
 

Similar to JAVA EE DEVELOPMENT (JSP and Servlets) (20)

Ajax
AjaxAjax
Ajax
 
PPT
PPTPPT
PPT
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
 
Spatial approximate string search Doc
Spatial approximate string search DocSpatial approximate string search Doc
Spatial approximate string search Doc
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
 
Unit 4 1 web technology uptu
Unit 4 1 web technology uptuUnit 4 1 web technology uptu
Unit 4 1 web technology uptu
 
Java web application development
Java web application developmentJava web application development
Java web application development
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Practical OData
Practical ODataPractical OData
Practical OData
 
PPT on javascript ajax and css and some points related to server
PPT on javascript ajax and css and some points related to serverPPT on javascript ajax and css and some points related to server
PPT on javascript ajax and css and some points related to server
 
4. jsp
4. jsp4. jsp
4. jsp
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Ppt on web development and this has all details
Ppt on web development and this has all detailsPpt on web development and this has all details
Ppt on web development and this has all details
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

JAVA EE DEVELOPMENT (JSP and Servlets)

  • 1. JSP and SERVLET Creating Web Applications by www.javathlon.com
  • 2. www.javathlon.com Client - Server Web Applications CLIENT SERVER HTTP PROTOCOL HTML PAGE PROCESS DATA AND RESPOND WITH RESULT
  • 3. www.javathlon.com Client - Server Web Applications CLIENT SERVER HTTP PROTOCOL HTML PAGE PROCESS DATA AND RESPOND WITH RESULT
  • 4. www.javathlon.com HTTP PROTOCOL STANDART BEHAVIOURS ● GET method Ask server for a resource via a URI (HTML page, image, MP3 etc) ● POST method Sent a web form to server and get a resource ● Other methods HEAD, PUT, DELETE, TRACE
  • 5. www.javathlon.com Client - Server Web Applications CLIENT SERVER HTTP PROTOCOL HTML PAGE PROCESS DATA AND RESPOND WITH RESULT
  • 6. www.javathlon.com Client - Server Web Applications CLIENT HTTP PROTOCOL JSP PAGE PROCESSING UNIT (SERVLET) PROCESSING UNIT (SERVLET) SERVER PROCESSING UNIT (SERVLET) DATABASE
  • 7. www.javathlon.com NEED FOR APPLICATION SERVERS ● Dispatch requests ● Thread management ● Session management ● Caching and object pooling We will use APACHE TOMCAT
  • 8. www.javathlon.com Reminders How a J2EE project runs? ● Client side consists of JSP pages. A JSP is an HTML page with special tags to get or send dynamic data from/to server. ● Servlets carry business code on server side and redirects the client to proper pages as result. ● JSPs and servlets communicate via HTTP protocol. Mostly GET and POST methods.
  • 9. www.javathlon.com Reminders How a J2EE project runs? JSP and servlets are contained in web application servers ( servlet containers) such as Apache Tomcat. We develop configuration files such as web. xml to regulate interactions among JSPs, servlets and other resources.
  • 10. www.javathlon.com TECHNOLOGY STACK Programming IDE Servlet Container (Application server) Java Runtime Environment 6
  • 11. www.javathlon.com SERVLET MECHANISM SERVLET Http Servlet Request Return an HTML content Return a multimedia file Redirect the client to a page Forward request to another servlet Get or Post Method
  • 12. www.javathlon.com HTTPSERVLETREQUEST GET method POST method SERVLET When you enter a web address to a web browser, it requests the resource by GET method. The request body is limited to about 250 characters. Sample:https://www.google.com.tr/?q=java&safe=off&output=search You need to send a web form for using POST method. The request body is limitless
  • 13. www.javathlon.com HTTPSERVLETRESPONSE Talha Ocakci Return an HTML content Return a multimedia file Navigate the client to another page Forward request to another servlet SERVLET Request Content-Type: text/html Use: PrintWriter object of HTTPServletResponse Content-Type: application/pdf, image/jpeg... Use: OutputStream object of HTTPServletResponse Content-Type: none Use: sendRedirect() method Content-Type: none Use: RequestDispatcher object of ServletContext
  • 14. www.javathlon.com HTTPSERVLETRESPONSE Return an HTML content Return a multimedia file Navigate the client to another page Forward request to another servlet SERVLET Request Content-Type: text/html Use: PrintWriter object of HTTPServletResponse Content-Type: application/pdf, image/jpeg... Use: OutputStream object of HTTPServletResponse Content-Type: none Use: sendRedirect() method Content-Type: none Use: RequestDispatcher object of ServletContext
  • 15. www.javathlon.com SCRIPTLET in JSP A scriptlet is a piece of Java-code embedded in the HTML. The scriptlet is everything inside the <% %> tags. Between these the user can add any valid Scriplet i.e. any valid Java Code.
  • 16. www.javathlon.com IMPLICIT OBJECTS in JSP They are the objects that you can use inside scriptlets application javax.servlet.ServletContext out javax.servlet.jsp.JspWriter request javax.servlet.ServletRequest response javax.servlet.ServletResponse session javax.servlet.http.HttpSession page java.lang.Object servletconfig javax.servlet.ServletConfig
  • 17. www.javathlon.com OBJECT SCOPES in SERVLETCONTEXT Application Scope Request Scope Session scope
  • 18. www.javathlon.com HTTP SESSION OBJECT SESSION ID Session object Attribute map name1 value1 name2 value2
  • 19. www.javathlon.com HTTPSERVLETRESPONSE Talha Ocakci Return an HTML content Return a multimedia file Navigate the client to another page Forward request to another servlet SERVLET Request Content-Type: text/html Use: PrintWriter object of HTTPServletResponse Content-Type: application/pdf, image/jpeg... Use: OutputStream object of HTTPServletResponse Content-Type: none Use: sendRedirect() method Content-Type: none Use: RequestDispatcher object of ServletContext
  • 20. www.javathlon.com REDIRECTING REQUEST Request forwarding and redirection are different concepts. When you forward a request, request and response objects are transferred. Url stays the same. When you redirect the request to another JSP/servlet, request and response objects are not transferred to new object. URL changes to the directory of new page.
  • 21. www.javathlon.com Tip for being a wanted J2EE developer ● Avoid using JAVA code inside a JSP file. Use JSP directives and JSP actions instead. ● Avoid using HTML code inside a servlet. Instead, use HTML code in JSP page and pass values it from the servlet.
  • 22. www.javathlon.com JSP Actions ● jsp:useBean Searches for an objects inside the given scope ● jsp:getProperty ● jsp:setProperty Gets/sets a value of a given object
  • 23. www.javathlon.com jsp:useBean action <jsp:useBean id="memberInfo" class="com.qapro.register.MemberInfo" scope="request"> </jsp:useBean> request.getParameter(“memberInfo”) <jsp:useBean id="memberInfo" class="com.qapro.register.MemberInfo scope="session"> </jsp:useBean> request.getSession().getParameter(“memberInfo”) <jsp:useBean id="memberInfo" class="com.qapro.register.MemberInf scope="application"> </jsp:useBean> ServletContext sc = getServletContext(); sc.getAttribute(“memberInfo”)
  • 24. www.javathlon.com jsp:getProperty and jsp:setProperty Gets/sets an attribute of an object with a given id
  • 25. www.javathlon.com JSTL BASICS Java Server Tag Library Provides shorthand notation to access: ● Attributes of standard servlet objects ● Bean properties We use them, because writing JAVA code inside JSP is not a good practice. It is a third party library of Apache Foundation.
  • 26. www.javathlon.com JSTL and JAVA Code Relation Iterating over a list JAVA NOTATION <ul> <% for(int i=0; i<messages.length; i++) { String message = messages[i]; %> <li><%= message %></li> <% } %> </ul> JSTL NOTATION <ul> <c:forEach var="message” items="${messages}"> <li>${message}</li> </c:forEach> </li>
  • 28. www.javathlon.com CLUE WEB APPLICATION WEB BROWSER ask for sth show result
  • 29. www.javathlon.com CLUE A basic web application is nothing more than a system that populates data from a database, insert into it, modify the data and visualize it. USER INTERFACE DATABASE WEB APPLICATION sends input select delete & update insert shows result
  • 30. www.javathlon.com WORKING WITH DATABASE Description A database is any file or file system that you can ● store your data ● manipulate data ● search for a desired item
  • 31. www.javathlon.com WORKING WITH DATABASE Database Types ● Flat files (text or binary) ● Flat file systems ● Non - relational databases (eg. MongoDB) ● Relational databases (eg. MySQL)
  • 32. www.javathlon.com WORKING WITH DATABASE Why use RDBMS? Relational Database Systems: Ease your tasks for quickly inserting, updating, querying, deleting the data you have on your hands using SQL.
  • 33. www.javathlon.com WORKING WITH DATABASE Relational Databases Relational Database Systems: Stores the data in tables and relations between those tables.
  • 34. www.javathlon.com WORKING WITH DATABASE Relational Database Structure Table: A real world or imaginary entity model that has attributes. (A user metadata) Row: An instance of a entity model (A user instance) Column: Attribute of an entity (User’s name) Primary key: Identifier of a instance (User’s id) Foreign key: Dependency of an entity to another entity (Reference to user’s question)
  • 35. WORKING WITH RELATIONAL www.javathlon.com DATABASES First example - Tables and columns Keep track of all money transfers in a bank. You need to store this data permanently. ROW 1 ROW 2 Sender name John Sender surname Lennon Sender account no 79879878978 Receiver name Paul Receiver surname McCartney Receiver account no 12121212121 Amount 300 Currency USD Date 1.1.2014 Sender name Kirk Sender surname Hammett Sender account no 565656565 Receiver name James Receiver surname Hetfield Receiver account no 808080801 Amount 50000 Currency USD Date 3.1.2014 attribute value DB TABLE (MONEY TRANSFER)
  • 36. www.javathlon.com SQL (Structured Query Language) ● DDL (Data Definition Language) Used to create or modify tables, data types of columns ● DML (Data Manipulation Language) Used to insert, update, delete data and query for desired data
  • 37. www.javathlon.com DATA TYPES ● String types ● Numeric types ● Date & Time types ● Binary objects
  • 38. www.javathlon.com WORKING WITH RELATIONAL DATABASES Creating table structures Done with DDL (Data Definition Language ) CREATE TABLE money_transfer( transfer_id INTEGER PRIMARY KEY, sender_name VARCHAR(50) NULL, sender_surname VARCHAR(50) NULL, sender_surname VARCHAR(50) NULL, sender_account_no VARCHAR(20) NULL, receiver_name VARCHAR(50) NULL, receiver_surname VARCHAR(50) NULL, receiver_account_no VARCHAR(50) NULL, amount FLOAT; currenct VARCHAR(4) NULL, transfer_date DATE NULL ); Sender name John Sender surname Lennon Sender account no 79879878978 Receiver name Paul Receiver surname McCartney Receiver account no 12121212121 Amount 300 Currency USD Transfer Date 1.1.2014
  • 39. WORKING WITH RELATIONAL www.javathlon.com DATABASES First example - Breaking the data into smaller units Multiple similar records means lots of repetition and repetition means mess. For preventing the repetition, we break the data into multiple columns. Sender name John Sender surname Lennon Sender account no 79879878978 Receiver name Paul Receiver surname McCartney Receiver account no 12121212121 Amount 300 Currency USD Date 1.1.2014 Sender name John Sender surname Lennon Sender account no 79879878978 Receiver name George Receiver surname Harrison Receiver account no 12045872 Amount 400 Currency USD Date 1.2.2014 Sender name John Sender surname Lennon Sender account no 79879878978 Receiver name Ringo Receiver surname Start Receiver account no 13698985 Amount 500 Currency USD Date 1.3.2014
  • 40. WORKING WITH RELATIONAL www.javathlon.com DATABASES First example - Data normalization ● Basic client data is extracted from the money transfer information. ● Client data is stored in another table. Identifier of the record inside client table is referenced from money transfer table Sender Client data 121 Receiver name George Receiver surname Harrison Receiver account no 12045872 Amount 400 Currency USD Date 1.2.2014 Sender Client data 121 Receiver name Ringo Receiver surname Starr Receiver account no 13698985 Amount 500 Currency USD Date 1.3.2014 Client data Client id 121 Client name John Client surname Lennon Client account no 79879878978 Client id( Foreign key)
  • 41. www.javathlon.com Tip for being a wanted J2EE developer A database table SHOULD correspond to at least one real world or virtual entity. DATABASE TABLE DESIGN PRINCIPLES 1
  • 42. www.javathlon.com Tip for being a wanted J2EE developer 2 Dependent entities should reference to the owner entity for data integration. DATABASE TABLE DESIGN PRINCIPLES
  • 43. www.javathlon.com DATABASE DESIGN for the USER MANAGEMENT MODULE of QA PLATFORM
  • 44. www.javathlon.com REGISTRATION Insert a user with ● username, ● password ● and other personal details.
  • 45. www.javathlon.com AUTHENTICATION Check if given username-password pair exists in database.
  • 46. www.javathlon.com REGISTRATION DB SCHEMA STANDART MUST-DOs 1. Put a primary key. 2. Put insertion date, 3. Put active/passive bit BUSINESS SPECIFIC 1. Store username and password 2. Store personal details
  • 47. www.javathlon.com REGISTRATION CREATE TABLE CREATE TABLE `user` ( `user_id` int(11) NOT NULL, `user_name` varchar(45) DEFAULT NULL, `password` varchar(45) COLLATE DEFAULT NULL, `is_active` bit(1) DEFAULT NULL, `name` varchar(45) DEFAULT NULL, `surname` varchar(45) DEFAULT NULL, `insert_date` datetime DEFAULT NULL, `role_name` varchar(45) DEFAULT NULL, PRIMARY KEY (`user_id`) )
  • 48. A PRIMER FOR DATA MANIPULATwwIwO.javNath lon.com with SQL Insert data INSERT INTO TABLENAME (first_column,...last_column) VALUES (first_value,...last_value); INSERT INTO user (user_id, user_name, password) VALUES (1, 'paul_weller','hzf1234fddf')
  • 49. A PRIMER FOR DATA MANIPULATwwIwO.javNath lon.com with SQL Primary key insert into user (user_id, user_name, password) values(100, 'paul_weller','hzf1234fddf') Error Code: 1062. Duplicate entry '100' for key 'PRIMARY' 0.000 sec Each table HAS TO have a primary key. This lets your database vendor to allocate unique space for each record in any tables. insert into user ( user_name, password) values ('eddie_vedder','hzf1234fddf'); Each table HAS TO have a primary key. This lets your database vendor to allocate unique space for each record in any tables. You will see user_id column gets unique values one by one.
  • 50. www.javathlon.com A PRIMER FOR DATA MANIPULATION with SQL Update a record update TABLENAME set COLUMNNAME = VALUE update user set user_name= ‘hgklkg45784’
  • 51. www.javathlon.com A PRIMER FOR DATA RETRIEVAL with SQL Retrieve all records DO NOT use * in select clauses. Using * is a good example of cutting corners that junior developers do. Define which columns you exactly need and want to populate.
  • 52. A PRIMER FOR DATA RETRIEVAL wwwwi.jtavhath lon.com SQL Restrict records select COLUMN1,COLUMN2 from TABLENAME where COLUMN1 = VALUE and/or COLUMN2 = VALUE2 select user_name from user where user_name =’'paul_weller'’ and password = ‘'hzf1234fddf'’
  • 53. www.javathlon.com IN NEXT CHAPTER ● Database Connections ● Transactions ● What is ACID? ● Committing and rolling the transactions back ● DB Engine - Java communication
  • 54. www.javathlon.com DATABASE CONNECTIONS Database connection is the means by which a database server and its client software communicate with each other.
  • 55. www.javathlon.com WHY WE NEED DATABASE CONNECTIONS? We send the commands to DB server and get the results via an open DB connection. DB SERVER Java web application DB CONNECTION
  • 56. www.javathlon.com COMMUNICATION BETWEEN JAVA AND DATABASE Database talks SQL, but Java does not know how to talk in SQL, it needs a translator called JDBC (Java Database Connector).
  • 57. www.javathlon.com DB CONNECTION POOLS DB connection opening and closing is so expensive operations compared to execute basic queries. Instead of open/close a connection for each query, create a bunch of connections* and use them over and over again. * = Connection pool
  • 59. www.javathlon.com CONNECTION POOL Implementations in Java ● C3P0 ● BoneCP ...
  • 60. www.javathlon.com DATABASE TRANSACTIONS A unit of work performed within a database management system against a database.
  • 61. www.javathlon.com DATABASE TRANSACTIONS ALL OR NOTHING PRINCIPLE 1. Open connection 2. Begin transaction 3. Debit $100 to Groceries Expense Account 4. Credit $100 to Checking Account 5. Commit transaction 6. Close connection TRANSACTION
  • 62. www.javathlon.com ACID Properties that a transaction must have Atomicity: Based on “all or nothing” principle All statements succeed or all fail in case of any power failures, errors, and crashes.
  • 63. www.javathlon.com ACID Properties that a transaction must have Consistency: If, for some reason (eq: programming error), a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules. eq: NULL inserting to a not-nullable column
  • 64. www.javathlon.com ACID Properties that a transaction must have Isolation: Before committing a transaction, modifications should not be visible to another transaction.
  • 65. www.javathlon.com ACID Properties that a transaction must have Durability: Durability guarantees that the database will keep track of pending changes in such a way that the server can recover from an abnormal termination.
  • 66. www.javathlon.com DATABASE DESIGN for the USER ROLE MANAGEMENT MODULE
  • 67. www.javathlon.com User Role- Permissions Logic MODERATOR MODIFY POST DELETE POST CREATE POST USER 1 USER 2
  • 68. www.javathlon.com User Role- Permissions Logic Required permissions: 1- Deleting posts 2- Correcting posts Required permissions: 1- Accepting new users 2- Deleting users John Hopkins is a moderator. A moderator has permissions for 1- Deleting posts 2- Correcting posts
  • 69. www.javathlon.com Tip for being a wanted J2EE developer Why not assign the permissions directly to the user but assign to a role? Because adding or removing the permissions to a role, lets the system grant or revoke this permission from all the users who belong to this role. Otherwise you would execute this modification on all users and this means a huge cost.
  • 70. www.javathlon.com Requirements: ● TABLE RELATIONS (1 to MANY, MANY to 1, MANY to MANY) ● SQL JOINS (inner join, left join, right join, full join, self join)
  • 71. www.javathlon.com THE MEANING OF RELATIONAL in RELATIONAL DATABASES One object may belong to how many other owner objects? One object may own to how many other dependent objects?
  • 72. www.javathlon.com TABLE RELATIONS ONE TO ONE USER USER-DETAILS (Country, Height, Weight ...) If you safely can add the columns in one table to another relation means 1-1.
  • 73. www.javathlon.com TABLE RELATIONS ONE TO ONE OPTION 1 USER TABLE USER ID USER NAME COUNTRY REGISTRATION DATE HEIGHT WEIGHT TIMEZONE USER TABLE USER ID USER NAME REGISTRATION DATE USER DETAILS TABLE USER ID HEIGHT WEIGHT COUNTRY OPTION 2
  • 74. www.javathlon.com TABLE RELATIONS ONE TO MANY ONE MANY QUESTION ANSWER 1 ● A question may own two answers. ● But, an answer can not be given two multiple questions. ANSWER 2 QUESTION ANSWER 3
  • 75. www.javathlon.com TABLE RELATIONS MANY TO MANY MANY MANY USER TOPIC 1 ● A user may follow multiple topics ● A topic may be followed by multiple users. TOPIC 2 USER TOPIC 3
  • 76. www.javathlon.com TABLE RELATIONS MANY TO MANY USER TABLE USER ID USER NAME USER NICKNAME 1 Talha Ocakçı talhaocakci 2 James Dio dio TOPIC TABLE TOPIC ID TOPIC NAME 1 Geography 2 History USER FOLLOWED TOPICS USER ID TOPIC ID FOLLOW TIME 1 1 10.06.2014 2 1 18.06.2014 2 2 18.07.2014
  • 77. www.javathlon.com JOINING TABLES To retrieve and combine different attributes of an entity from several tables. SELECT CLAUSE + FROM CLAUSE + JOIN CLAUSE (multiple) + WHERE CLAUSE +
  • 78. www.javathlon.com JOINING TABLES Inner Join Both tables must have the same value on joined columns. eq. Populate list of permissions that a user has.
  • 79. www.javathlon.com JOINING TABLES Left (Outer) Join If a row in table 1 does not have a match in table 2, it still exists in result set.
  • 81. IMPLEMENTING JAVA WEB APPLICATION
  • 82. www.javathlon.com WHAT WE WILL DO? 1. Without caring of user interface design, focus on the technical details. 2. Find the most time consuming phases in development and ease them professionally
  • 83. www.javathlon.com REGISTER USER Get username, email, name, surname of user and post it to servlet JSP 1. Get values from request 2. Get DB connection (Create or get one from DB connection pool) 3. Start transaction 4. Insert user to DB 5. Release all resources 6. Put message into response 6. Redirect to another page SERVLET Show the message inside JSP
  • 84. www.javathlon.com JDBC CLASSES Statement ● Contains a static SQL statement ● Not reusable PreparedStatement: ● Contains precompiled SQL statement. ● Used to efficiently execute this statement multiple times by just setting parameters.
  • 85. www.javathlon.com JDBC CLASSES ResultSet Holds the database result row by row Holds the metadata of the DB result (count, column names, etc)
  • 86. www.javathlon.com JAVA - MYSQL TYPE CORRESPONDENCE
  • 87. www.javathlon.com RESULT SET OBJECT VALUES METADATA talha ocakci talhaocakci paul auster paulauster ... ... ... Count Column types Schema name Table name ... POINTER
  • 88. www.javathlon.com RESULT SET OBJECT resultset.next() method moves the pointer to next row. If reaches to the end it returns false. talha ocakci talhaocakci paul auster paulauster ... ... ... POINTER Initially, it points to the very beginning of the ResultSet object but not the first row. To get the first row, you need to invoke next() before iterating.
  • 89. www.javathlon.com REGISTER USER Get username, email, name, surname of user and post it to servlet JSP 1. Get values from request 2. Get DB connection (Create or get one from DB connection pool) 3. Start transaction 4. Insert user to DB 5. Release all resources 6. Put message into response 6. Redirect to another page SERVLET Show the message inside JSP
  • 90. www.javathlon.com CONNECTION POOLS Created on servlet containers (Tomcat 7) or application servers (JBOSS, Glassfish, etc..) and can be access by JNDI Created with C3P0 independent from a servlet container or an application server.
  • 91. www.javathlon.com CONNECTION POOLS Configuration Min connection size: Whatever happens, connection number will not drop below this. Max connection: Number of connection can not exceed this number. Timeout: If idle time of a connection exceeds this time, it returns back to pool automatically.
  • 92. www.javathlon.com INITIALIZE RESOURCE WHILE BOOTSTRAPPING ● Mark your servlet for automatic invoking while bootstrapping the application in deployment descriptor. marker: load-on-startup tag. ● Initialize resources in init() method of servlet.
  • 93. www.javathlon.com EMAIL VALIDATION 1- Insert the new user record to user table 2- Insert a related record to email-validation table including user id and validation code. 3- Email the validation url including the validation code to user’s email. 4- When sent link is clicked, check the validation code in url against the one in DB.
  • 94. www.javathlon.com EMAIL VALIDATION When a connection is created, it is in auto-commit mode. The way to allow two or more statements to be grouped into a transaction is to disable the auto-commit mode.
  • 95. www.javathlon.com GET GENERATED KEYS preparedStatement.getGeneratedKeys() returns a Result Set with one column and one row: POINTER VALUES 29
  • 96. www.javathlon.com WORKING IN PROFESSIONAL SOFTWARE DEVELOPMENT TEAMS
  • 97. www.javathlon.com WORKING IN A TEAM If team members use; ● Different approaches to similar problems ● Different relations between software layers... There will be chaos later on.
  • 98. www.javathlon.com WORKING IN PROFESSIONAL SOFTWARE DEVELOPMENT TEAMS Why do we use design patterns? Developers agree on the best solutions and apply them for similar problems.
  • 99. www.javathlon.com SOFTWARE ARCHITECTURE AND DESIGN PATTERNS Design patterns ensure the project will not fail by the time passing. If you don’t obey the rules, the failure underneath will be observed.
  • 100. www.javathlon.com DESIGN PATTERN and STRATEGY Design Pattern: Describes a solution to a common problem in a context. Strategy: The real implementation of the pattern
  • 101. www.javathlon.com EXAMPLES in SOFTWARE ENGINEERING Problem: I create huge objects over and over again, so project consumes so much memory. Solution: Use a single instance and reuse it whenever possible. Pattern: Singleton pattern Meaning: Create one and use it over and over. Example: Our DB connection pool
  • 102. www.javathlon.com EXAMPLES in SOFTWARE ENGINEERING Problem: I have too many controllers (servlets), so I lost the control of redirecting the requests. Solution: Use a common class to redirect all requests so that you can manage in just one place. Pattern: Front controller pattern Example: DispatcherServlet in Spring framework
  • 103. www.javathlon.com EXAMPLES in SOFTWARE ENGINEERING Problem: I forgot to release the resources after DB operations and I don’t want to copy and paste the same code to everywhere. Solution: Move the boilerplate code to another common class. Pattern: Template pattern Example: We will implement now.
  • 104. www.javathlon.com BIG PICTURE of DESIGN PATTERNS 1. Creational Patterns a) Singleton b) Factory c) Prototype d) Builder 2. Behavioural Patterns a) Template b) Mediator 3. J2EE Patterns a) Front Controller b) DAO Pattern c) Model View Controller d) View Helper and so on...
  • 105. www.javathlon.com BIG PICTURE of DESIGN PATTERNS
  • 106. www.javathlon.com CORRECT USAGE DOSE of PATTERNS
  • 107. www.javathlon.com IMPLEMENT TEMPLATE PATTERN Why we need them? 1- You will possibly forget common operations like closing DB connection, Prepared Statement and ResultSet. 2- You will repeatedly copy tens of lines of initialization, resource cleaning code for simple queries.
  • 108. www.javathlon.com IMPLEMENT TEMPLATE PATTERN A class extends an abstract class that do the boilerplate things Concrete class Abstract class 1. Resource allocating 2. Execute DB operations Populate Result Set 3. Resource releasing Get DB Connection Create PreparedStatement Start transaction Commit transaction Close connection Close PreparedStatement Close ResultSet
  • 109. www.javathlon.com DATA ACCESS OBJECT PATTERN Problem: 1- You should separate business and DB operations. In service layer, you should just deal with business. Not with DB specific ugly code, connections, etc. 2- You need a real entity object but not a collection of low level strings, numbers, booleans… 3- You need to run unit tests.
  • 110. www.javathlon.com DATA ACCESS OBJECT PATTERN VIEW LAYER (Shows model’s attributes) SERVICE LAYER (Combines multiple DAOs if required) DB LAYER (DAO) Each class deal with just one DB table MODEL REAL ENTITY Get result set, place basic values into entity instances.
  • 111. www.javathlon.com RELATION between DAO and TEMPLATE PATTERNS VIEW CONTROLLER DB LAYER MODEL (DAO) REAL ENTITY TEMPLATE PATTERN USED BY Get result set, place basic values into entity instances. Might be the same type of object or two separate object types that may adapted to each other
  • 112. www.javathlon.com ● DAO Connection Scoping ○ Method Scope ○ Instance Scope ○ Thread Scope
  • 113. www.javathlon.com UNIT TESTING DAO LAYER Unit testing means executing a method without an application server. 1- Using JUnit 2- (Fake unit testing) Simply by using an main class.
  • 115. www.javathlon.com AFTER AJAX (Async Javascript & XML)
  • 116. www.javathlon.com XMLHttpRequest object Provides the ability to 1- Send asynchronous requests to the server side. 2- Be noticed in each step of the flow (request sent, headers received, loading, done, error occurred)
  • 118. www.javathlon.com XXMMLLHHtttptRpeRqueeqsut eobsjte cotb mjeecthto mdsethods open(method, url) Ex: open(“POST”, “Voting”) setRequestHeader(name, value) Ex: setRequestHeader("Content-type", "application/x-www-form-urlencoded") send(data) Ex: send(“questionId=1&type=UP”)
  • 119. www.javathlon.com XXMMLLHHtttptRpeRqueeqsut eobsjte c- tr meeatdhyoSdstate Shows the internal state of the XMLHttpRequest instance. When it is switched to another state, you are informed via a readyStateChangeEvent. You can update your HTML page accordingly. STATE NUMERIC VALUE DESCRIPTION UNSENT 0 The object has been constructed. OPENED 1 The open() method has been successfully invoked HEADERS_RECEIVED 2 All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available. LOADING 3 The response entity body is being received. DONE 4 The data transfer has been completed or something went wrong during the transfer
  • 120. www.javathlon.com Communicate with XMLHttpRequest Event name Interface Dispatched when… readystatechange Event The readyState attribute changes value, except when it changes to UNSENT. loadstart ProgressEvent The request starts. progress ProgressEvent Transmitting data. abort ProgressEvent The request has been aborted. For instance, by invoking the abort() method. error ProgressEvent The request has failed. load ProgressEvent The request has successfully completed. timeout ProgressEvent The author specified timeout has passed before the request completed. loadend ProgressEvent The request has completed (either in success or failure).
  • 121. www.javathlon.com XMLHttpRequest Status codes CODE STATUS 200 SUCCESSFUL 301 MOVED PERMANENTLY 403 FORBIDDEN 404 NOT FOUND
  • 122. www.javathlon.com XMLHttpRequest Handling Successful State Successful state means ● readyState = 4 ● status = 200
  • 123. www.javathlon.com SUCCESSFUL AJAX FLOW HTML PAGE XMLHttpRequest instance Server Create Open Send readyStateChange:1 readyStateChange:2 process readyStateChange:3 status : 200 readyStateChange:4 status : 200 Manipulate the HTML send data to server send result (JSON, string) onReadyStateChange event
  • 124. www.javathlon.com AJAX CALL FLOW ● Create an XMLHttpRequest instance. ● Configure the url and method ● Send data ● Obtain and parse the result ● Manipulate your HTML page accordingly.