JAVA EE DEVELOPMENT (JSP and Servlets)
-
Upload
talha-ocakci -
Category
Technology
-
view
414 -
download
3
description
Transcript of JAVA EE DEVELOPMENT (JSP and Servlets)
JSP and SERVLETCreating Web Applications
by www.javathlon.com
www.javathlon.com
Client - Server Web Applications
SERVERCLIENT HTTP PROTOCOL
HTML PAGE PROCESS DATA AND RESPOND WITH RESULT
www.javathlon.com
Client - Server Web Applications
SERVERCLIENT HTTP PROTOCOL
HTML PAGE PROCESS DATA AND RESPOND WITH RESULT
www.javathlon.com
HTTP PROTOCOLSTANDART BEHAVIOURS
● GET methodAsk server for a resource via a URI(HTML page, image, MP3 etc)
● POST methodSent a web form to server and get a resource
● Other methodsHEAD, PUT, DELETE, TRACE
www.javathlon.com
Client - Server Web Applications
SERVERCLIENT HTTP PROTOCOL
HTML PAGE PROCESS DATA AND RESPOND WITH RESULT
www.javathlon.com
Client - Server Web Applications
CLIENTHTTP PROTOCOL
JSP PAGE
SERVER
PROCESSING UNIT (SERVLET)
PROCESSING UNIT (SERVLET)
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
RemindersHow 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
RemindersHow 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
SERVLETHttp Servlet Request
Return an HTML content
Return a multimedia file
Redirect the client to a page
Forward request to another servletGet 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/htmlUse: PrintWriter object of HTTPServletResponse
Content-Type: application/pdf, image/jpeg...Use: OutputStream object of HTTPServletResponse
Content-Type: noneUse: sendRedirect() method
Content-Type: noneUse: 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/htmlUse: PrintWriter object of HTTPServletResponse
Content-Type: application/pdf, image/jpeg...Use: OutputStream object of HTTPServletResponse
Content-Type: noneUse: sendRedirect() method
Content-Type: noneUse: 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
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
They are the objects that you can use inside scriptlets
www.javathlon.com
OBJECT SCOPESin SERVLETCONTEXT
Application Scope
Session scope
Request Scope
www.javathlon.com
HTTP SESSION OBJECT
Session object
SESSION ID
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/htmlUse: PrintWriter object of HTTPServletResponse
Content-Type: application/pdf, image/jpeg...Use: OutputStream object of HTTPServletResponse
Content-Type: noneUse: sendRedirect() method
Content-Type: noneUse: 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:useBeanSearches 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.MemberInfoscope="session">
</jsp:useBean>
request.getSession().getParameter(“memberInfo”)
<jsp:useBean id="memberInfo"class="com.qapro.register.MemberInfscope="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 BASICSJava 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 RelationIterating 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.
WEB APPLICATION
DATABASEUSER INTERFACE
sends input
select
delete & update
insert
shows result
www.javathlon.com
WORKING WITH DATABASEDescription
A database is any file or file system that you can ● store your data ● manipulate data● search for a desired
item
www.javathlon.com
● Flat files (text or binary)
● Flat file systems
● Non - relational databases (eg. MongoDB)
● Relational databases (eg. MySQL)
WORKING WITH DATABASEDatabase Types
www.javathlon.com
WORKING WITH DATABASEWhy 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 DATABASERelational Databases
Relational Database Systems:Stores the data in tables and relations between those tables.
www.javathlon.com
WORKING WITH DATABASERelational 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)
www.javathlon.comWORKING WITH RELATIONAL DATABASESFirst example - Tables and columns
Keep track of all money transfers in a bank. You need to store this data permanently.
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
DB TABLE (MONEY TRANSFER)
ROW 1 ROW 2
attribute value
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
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);
WORKING WITH RELATIONAL DATABASESCreating table structures
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
www.javathlon.comWORKING WITH RELATIONAL DATABASESFirst 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
www.javathlon.comWORKING WITH RELATIONAL DATABASESFirst example - Data normalization
Sender Client data121
Receiver name George
Receiver surname Harrison
Receiver account no 12045872
Amount 400
Currency USD
Date 1.2.2014
Sender Client data121
Receiver name Ringo
Receiver surname Starr
Receiver account no 13698985
Amount 500
Currency USD
Date 1.3.2014
Client id 121
Client name John
Client surname Lennon
Client account no 79879878978
Client data
● 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
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
Dependent entities should reference to the owner entity for data integration.
2
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
REGISTRATIONDB 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
REGISTRATIONCREATE 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`))
www.javathlon.comA PRIMER FOR DATA MANIPULATION with SQLInsert 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')
www.javathlon.comA PRIMER FOR DATA MANIPULATION with SQLPrimary 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 SQLUpdate a record
update TABLENAMEset COLUMNNAME = VALUE
update userset user_name= ‘hgklkg45784’
www.javathlon.com
A PRIMER FOR DATA RETRIEVAL with SQLRetrieve 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.
www.javathlon.comA PRIMER FOR DATA RETRIEVAL with SQLRestrict records
select COLUMN1,COLUMN2from TABLENAMEwhere COLUMN1 = VALUEand/or COLUMN2 = VALUE2
select user_name from userwhere 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 SERVERJava 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 POOLImplementations 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 TRANSACTIONSALL OR NOTHING PRINCIPLE
TRANSACTION
1. Open connection2. Begin transaction3. Debit $100 to Groceries Expense Account
4. Credit $100 to Checking Account
5. Commit transaction
6. Close connection
www.javathlon.com
ACIDProperties 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
ACIDProperties 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
ACIDProperties that a transaction must have
Isolation:
Before committing a transaction, modifications should not be visible to another transaction.
www.javathlon.com
ACIDProperties 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- PermissionsLogic
Required permissions:1- Deleting posts2- Correcting posts
Required permissions:1- Accepting new users2- Deleting users
John Hopkins isa moderator.A moderator has permissions for1- Deleting posts2- 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 RELATIONALin 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 RELATIONSONE 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 RELATIONSONE 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 RELATIONSONE TO MANY
QUESTION ANSWER 1
● A question may own two answers.● But, an answer can not be given two
multiple questions.
ANSWER 2
ANSWER 3 QUESTION
ONE MANY
www.javathlon.com
TABLE RELATIONSMANY TO MANY
USER TOPIC 1
● A user may follow multiple topics● A topic may be followed by multiple
users.
TOPIC 2
TOPIC 3 USER
MANY MANY
www.javathlon.com
TABLE RELATIONSMANY 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 TABLESInner Join
Both tables must have the same value on joined columns.
eq. Populate list of permissions that a user has.
www.javathlon.com
JOINING TABLESLeft (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
JSP
Get username, email,name, surname of userand post it to servlet
SERVLET
1. Get values from request2. Get DB connection (Create or get one from DB connection pool)3. Start transaction4. Insert user to DB5. Release all resources6. Put message into response6. Redirect to another page
JSP
Show the message inside
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
ResultSet
Holds the database result row by row
Holds the metadata of the DB result (count, column names, etc)
JDBC CLASSES
www.javathlon.com
JAVA - MYSQL TYPE CORRESPONDENCE
www.javathlon.com
RESULT SET OBJECT
talha ocakci talhaocakci
paul auster paulauster
... ... ...
VALUES METADATA
Count
Column types
Schema name
Table name
...
POINTER
www.javathlon.com
RESULT SET OBJECT
talha ocakci talhaocakci
paul auster paulauster
... ... ...
POINTER
resultset.next() method moves the pointer to next row. If reaches to the end it returns false.
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
JSP
Get username, email,name, surname of userand post it to servlet
SERVLET
1. Get values from request2. Get DB connection (Create or get one from DB connection pool)3. Start transaction4. Insert user to DB5. Release all resources6. Put message into response6. Redirect to another page
JSP
Show the message inside
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 POOLSConfiguration
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
29
VALUES
POINTER
preparedStatement.getGeneratedKeys() returns a Result Set with one column and one row:
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 ANDDESIGN 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 Patternsa) Singleton b) Factory c) Prototype d) Builder
2. Behavioural Patternsa) Template b) Mediator
3. J2EE Patternsa) Front Controllerb) DAO Pattern
c) Model View Controllerd) 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 PATTERNWhy 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
1. Resource allocating
2. Execute DB operations Populate Result Set
3. Resource releasing
Concrete class Abstract class
Commit transaction
Close connection
Close PreparedStatement
Close ResultSet
A class extends an abstract class that do the boilerplate things
Get DB Connection
Create PreparedStatement
Start transaction
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
VIEWLAYER
(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 valuesinto entity instances.
www.javathlon.com
RELATION between DAO and TEMPLATE PATTERNS
VIEW CONTROLLERDB LAYER(DAO)MODEL REAL
ENTITYTEMPLATEPATTERN
USED BY
Might be the same type of object or two separate object types that may adapted to each other
Get result set, place basic valuesinto entity instances.
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
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”)
XMLHttpRequest object methods XMLHttpRequest object methods
www.javathlon.com
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.
XMLHttpRequest object methods XMLHttpRequest - readyState
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 PAGEXMLHttpRequestinstance Server
Create
Open
Send
readyStateChange:1
readyStateChange:2
process
readyStateChange:3status : 200
readyStateChange:4status : 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