JAVA EE DEVELOPMENT (JSP and Servlets)

125
JSP and SERVLET Creating Web Applications by www.javathlon.com

description

Java and J2EE is the most used technologies in enterprise web development. Telecom operators, service providers are using these technlogies; banking and insurance companies are moving to Java from old generation technologies. https://www.udemy.com/java-web-developmen-with-real-world-development-flow If you want to earn much in web development business, you also need to learn Java web technologies. Java has de facto standart frameworks such as EJB 3.0, Spring and others that can be bound to them. But at heart, they all use the similar JSP/Servlet technology and add some layers above them to speed up the development. You will use them in your daily business but before using them, you must learn the basics and what is going on while using them. Otherwise, you will not be able to find a proper solution to common problems. This course will make you understand the basics of JSP / servlet technlogies, designing a relational database, DB operations, design patterns, working with other developers, and let you know the must-do operations in professional projects such as performance increasing, logging errors. If you want to develop a web-site in a couple of hours without understanding what you are doing, you may go ahead and find other resources. But if you really want to understand what you are doing and learn the theory at the same time, this course will be a great oppurtunity for you. You will develop a real working project. Yow will first write quick and dirty code then you will apply professional patterns one by one while investigating the problems. You will walk through a real development flow: 1- Write a quick and dirty code for doing the job. 2- You will design database tables and high performance queries 3 - You will apply design patterns to make the code reusable and high performance. 4 - You will beautify the user interface with Javascript and CSS tweaks 5- You will add exception handling, logging mechanism for production environment 6- AT THIS STEP, YOU WILL BE HIRED FOR MUCH MUCH HIGHER SALARIES. BECAUSE YOU ARE A REAL PROFESSIONAL.

Transcript of JAVA EE DEVELOPMENT (JSP and Servlets)

Page 1: JAVA EE DEVELOPMENT (JSP and Servlets)

JSP and SERVLETCreating Web Applications

by www.javathlon.com

Page 2: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

Client - Server Web Applications

SERVERCLIENT HTTP PROTOCOL

HTML PAGE PROCESS DATA AND RESPOND WITH RESULT

Page 3: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

Client - Server Web Applications

SERVERCLIENT HTTP PROTOCOL

HTML PAGE PROCESS DATA AND RESPOND WITH RESULT

Page 4: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 5: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

Client - Server Web Applications

SERVERCLIENT HTTP PROTOCOL

HTML PAGE PROCESS DATA AND RESPOND WITH RESULT

Page 6: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

Client - Server Web Applications

CLIENTHTTP PROTOCOL

JSP PAGE

SERVER

PROCESSING UNIT (SERVLET)

PROCESSING UNIT (SERVLET)

PROCESSING UNIT (SERVLET)

DATABASE

Page 7: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

NEED FOR APPLICATION SERVERS

● Dispatch requests● Thread management● Session management● Caching and object pooling

We will use APACHE TOMCAT

Page 8: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 9: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 10: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

TECHNOLOGY STACK

Programming IDE Servlet Container (Application server)

Java Runtime Environment 6

Page 11: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 12: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 13: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 14: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 15: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 16: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 17: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

OBJECT SCOPESin SERVLETCONTEXT

Application Scope

Session scope

Request Scope

Page 18: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

HTTP SESSION OBJECT

Session object

SESSION ID

Attribute map

name1 value1

name2 value2

Page 19: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 20: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 21: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 22: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 23: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 24: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

jsp:getProperty and jsp:setProperty

Gets/sets an attribute of an object with a given id

Page 25: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 26: JAVA EE DEVELOPMENT (JSP and Servlets)

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>

Page 27: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

FULL LIST OF JSTL TAGS

Page 28: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

CLUE

WEB APPLICATION

WEB BROWSER

ask for sth

show result

Page 29: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 30: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 31: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

● Flat files (text or binary)

● Flat file systems

● Non - relational databases (eg. MongoDB)

● Relational databases (eg. MySQL)

WORKING WITH DATABASEDatabase Types

Page 32: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 33: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

WORKING WITH DATABASERelational Databases

Relational Database Systems:Stores the data in tables and relations between those tables.

Page 34: JAVA EE DEVELOPMENT (JSP and Servlets)

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)

Page 35: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 36: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 37: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

DATA TYPES

● String types

● Numeric types

● Date & Time types

● Binary objects

Page 38: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 39: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 40: JAVA EE DEVELOPMENT (JSP and Servlets)

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)

Page 41: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 42: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 43: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

DATABASE DESIGN for the

USER MANAGEMENT MODULE

of QA PLATFORM

Page 44: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

REGISTRATION

Insert a user with● username, ● password ● and other personal details.

Page 45: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

AUTHENTICATION

Check if given username-password pair exists in database.

Page 46: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 47: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 48: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 49: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 50: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

A PRIMER FOR DATA MANIPULATION with SQLUpdate a record

update TABLENAMEset COLUMNNAME = VALUE

update userset user_name= ‘hgklkg45784’

Page 51: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 52: JAVA EE DEVELOPMENT (JSP and Servlets)

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'’

Page 53: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

IN NEXT CHAPTER

● Database Connections● Transactions● What is ACID?● Committing and rolling the transactions

back● DB Engine - Java communication

Page 54: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

DATABASE CONNECTIONS

Database connection is the means by which a database server and its client software communicate with each other.

Page 55: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 56: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 57: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 58: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

DB CONNECTION POOL USAGE

Page 59: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

CONNECTION POOLImplementations in Java

● C3P0

● BoneCP

...

Page 60: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

DATABASE TRANSACTIONS

A unit of work performed within a database management system against a database.

Page 61: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 62: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 63: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 64: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

ACIDProperties that a transaction must have

Isolation:

Before committing a transaction, modifications should not be visible to another transaction.

Page 65: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 66: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

DATABASE DESIGN for the

USER ROLE MANAGEMENT MODULE

Page 67: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

User Role- Permissions Logic

MODERATOR

MODIFY POST DELETE POST CREATE POST

USER 1

USER 2

Page 68: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 69: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 70: JAVA EE DEVELOPMENT (JSP and Servlets)

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)

Page 71: JAVA EE DEVELOPMENT (JSP and Servlets)

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?

Page 72: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 73: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 74: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 75: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 76: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 77: JAVA EE DEVELOPMENT (JSP and Servlets)

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 +

Page 78: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 79: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 80: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

Page 81: JAVA EE DEVELOPMENT (JSP and Servlets)

IMPLEMENTING JAVA WEB APPLICATION

Page 82: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 83: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 84: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 85: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

ResultSet

Holds the database result row by row

Holds the metadata of the DB result (count, column names, etc)

JDBC CLASSES

Page 86: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

JAVA - MYSQL TYPE CORRESPONDENCE

Page 87: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

RESULT SET OBJECT

talha ocakci talhaocakci

paul auster paulauster

... ... ...

VALUES METADATA

Count

Column types

Schema name

Table name

...

POINTER

Page 88: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 89: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 90: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 91: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 92: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 93: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 94: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 95: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

GET GENERATED KEYS

29

VALUES

POINTER

preparedStatement.getGeneratedKeys() returns a Result Set with one column and one row:

Page 96: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

WORKING IN PROFESSIONAL SOFTWARE DEVELOPMENT TEAMS

Page 97: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 98: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 99: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 100: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 101: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 102: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 103: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 104: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 105: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

BIG PICTURE of DESIGN PATTERNS

Page 106: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

CORRECT USAGE DOSE of PATTERNS

Page 107: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 108: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 109: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 110: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 111: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 113: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 114: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

BEFORE AJAX

Page 115: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

AFTER AJAX (Async Javascript & XML)

Page 116: JAVA EE DEVELOPMENT (JSP and Servlets)

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)

Page 117: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

XMLHttpRequest object

Page 118: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 119: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 120: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 121: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

XMLHttpRequest Status codes

CODE STATUS

200 SUCCESSFUL

301 MOVED PERMANENTLY

403 FORBIDDEN

404 NOT FOUND

Page 122: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com

XMLHttpRequest Handling Successful State

Successful state means

● readyState = 4● status = 200

Page 123: JAVA EE DEVELOPMENT (JSP and Servlets)

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

Page 124: JAVA EE DEVELOPMENT (JSP and Servlets)

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.

Page 125: JAVA EE DEVELOPMENT (JSP and Servlets)

www.javathlon.com