SlideShare a Scribd company logo
1 of 53
Session Tracking in Servlets
• Session simply means a particular interval of time.
• Session Tracking is a way to maintain state (data) of an user. It
is also known as session management in servlet.
• Http protocol is a stateless so we need to maintain state using
session tracking techniques. Each time user requests to the
server, server treats the request as the new request. So we need
to maintain the state of an user to recognize to particular user.
• HTTP is stateless that means each request is considered as the
new request.
Session Tracking Techniques
There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies
• small piece of information that is persisted between the multiple client
requests
• name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
• A web server can assign a unique session ID as a cookie to each web
client and for subsequent requests from the client they can be recognized
using the received cookie.
• used for storing client state
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when
user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when
user closes the browser. It is removed only if user logout or
signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
create Cookie
Cookie ck=new Cookie("user","sony");//creating cookie object
response.addCookie(ck);//adding cookie in the response
delete Cookie
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
} }
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml (web. xml defines mappings between URL paths and the
servlets that handle requests with those paths.)
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Hidden Form Fields:
• a hidden (invisible) textfield is used for maintaining the state of an user
• <input type="hidden" name="sessionid" value="12345">
• we store the information in the hidden field and get it from another
servlet
• when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web
browser sends request back, then session_id value can be used to keep
the track of different web browsers.
URL Rewriting
append some extra data on the end of each URL that identifies the session,
and the server can associate that session identifier with data it has stored
about that session.
http://point.com/file.htm;sessionid=12345
Hidden Form Fields
URL Rewriting
Advantage of URL Rewriting
• It will always work whether cookie is disabled
or not (browser independent).
• Extra form submission is not required on each
pages.
Disadvantage of URL Rewriting
• It will work only with links.
• It can send Only textual information.
• whenever a user starts using our application, we can save a
unique identification information about him, in an object
which is available throughout the application, until its
destroyed.
• So wherever the user goes, we will always have his
information and we can always manage which user is doing
what. Whenever a user wants to exit from your application,
destroy the object with his information.
HttpSession
<form method="post"
action="Validate">
User: <input type="text"
name="user" /><br/>
Password: <input type="text"
name="pass" ><br/>
<input type="submit"
value="submit">
</form>
<web-app..>
<servlet>
<servlet-name>Validate</servlet-name>
<servlet-class>Validate</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Hello "+user);
}
}
DATABASE CONNECTIVITY
– Database connectivity allows the client software to
communicate with the database server software.
– It is an interface that allows communication between the
database and the software application.
– Elements of frontend applications/websites like buttons, fonts,
or menus need to be connected to the database (back-end) to
deliver relevant information to the end-user.
– Database connectivity can be done using different
programming languages such as Java, C++, and HTML
(hypertext markup language).
– By using these languages, one can connect a program to a
particular database and can query data to access and
manipulate them.
Querying the database
• Organized collection of data in a computer
system is a database.
• It stores information in the form of structured
tables that contain rows and columns to
organize the data.
• It is controlled by the management system.
• DBMS enables creation and maintenance of
database.
SQL
– SQL (Structured Query Language) is used for querying the
data stored in a relational database.
– MySQL database and SQL select are some modified
versions of SQL.
– The query is categorized into DDL (Data Definition
Language) and DML (Data Manipulation Language).
– Data Definition Language (DDL):
• The statements used to create the database schema and
the tables are referred to as DDL.
• They can also be used to modify the structure of the table.
For example, CREATE, ALTER and so forth.
– Data Manipulation Language (DML):
• These statements are used to insert records into the table,
update and delete records present in the table.
• For example, INSERT, UPDATE, DELETE and so forth.
Database Driver
• A driver is a computer program that helps
applications to establish database connection.
• There are two standard protocols for
establishing database connectivity name Open
Database Connectivity (ODBC) and Java
Database Connectivity (JDBC).
• These enable applications to access and
manipulate database contents by providing a
generic interface.
Servlet – Database connection
• A Servlet can generate dynamic HTML by
retrieving data from the database and sending
it back to the client as a response.
• We can also update the database based on
data passed in the client HTTP request.
• We will create a simple servlet to
fetch/retrieve data from the database based
on the client’s request.
What is JDBC?
• JDBC is: a Sun trademark
– is often taken to stand for Java Database Connectivity.
– is a Java API for connecting programs written in Java to the data in
relational databases.
– consists of a set of classes and interfaces written in the Java
programming language.
– provides a standard API for tool/database developers and makes it
possible to write database applications using a pure Java API.
– The standard defined by Sun Microsystems, allowing individual
providers to implement and extend the standard with their own JDBC
drivers.
JDBC
• Java is very standardized, but there are many versions of SQL
• JDBC is a means of accessing SQL databases from Java
– JDBC is a standardized API for use by Java programs
– JDBC is also a specification for how third-party vendors should write
database drivers to access specific SQL versions
• JDBC:
– establishes a connection with a database
– sends SQL statements
– processes the results.
The need of an application
• Databases offer structured storing, easy retrieval and processing of data
• The maintenance, however, can be tedious
Suppose you manage a database store on an SQL server. Then you need
to have a knowledge on SQL in order to retrieve or update data. This will
not be that pleasant for you. Will it?
• An application in between can do the job for you
The application will deal with the database while you interact with the
user-friendly GUI
JDBC
• Java Database Connectivity
• Provides a Java API to access SQL databases
The JDBC API
• The JDBC API contains methods to communicate with DBMS or RDBMS
• The JDBC API uses the JDBC driver to carry out it tasks
• The JDBC API & Driver enables a Java application to:
1. Establish a connection with a data source
2. Send queries and update statements to the data source
3. Process the results
Java Program JDBC API JDBC Driver Database
The process of accessing the database
JDBC API
• The JDBC API supports both two-tier and three-tier models for database
access.
• Two-tier model -- a Java applet or application interacts directly with the
database.
• Three-tier model -- introduces a middle-level server for execution of business
logic:
– the middle tier to maintain control over data access.
– the user can employ an easy-to-use higher-level API which is translated by
the middle tier into the appropriate low-level calls.
The JDBC API
• The JDBC API supports both two-tier and three-tier models
Java Application
DBMS
JDBC
Client machine
DBMS – proprietary protocol
Database server
Two-tier model
Java applet or
HTML browser
DBMS
Application
server (Java)
JDBC
Client machine (GUI)
HTTP, RMI, CORBA or other calls
Server machine
(business logic)
DBMS – proprietary protocol
Database server
Three-tier model
JDBC Classes
• java.sql.
– DriverManager
• getConnection
– Connection
• createStatement
– Statement
• execute, executeQuery, executeBatch, executeUpdate
– ResultSet
• next, getString, getInt, getDate, getMetaData
– ResultSetMetadata
• getColumnCount, getColumnName, getColumnType
JDBC Steps
1. Instantiate proper driver
2. Open connection to database
3. Connect to database
4. Query database (or insert/update/delete)
5. Process the result
6. Close connection to database
1. Instantiate Driver
• Class.forName(“driver class”) - to dynamically load the driver's class file into
memory, which automatically registers it
• Driver class is vendor dependent, e.g.,
– sun.jdbc.odbc.JdbcOdbcDriver
• JDBC-ODBC bridge used to access ODBC Sources
– com.mysql.jdbc.Driver
• driver to access MySQL database
– com.sybase.jdbc2.jdbc.SybDriver
• driver to access Sybase database
2. Open Connection
• DriverManager.getConnection(url) - creates a Connection object, which is used
to create SQL statements, send them to the Informix database, and process the
results.
or
• DriverManager.getConnection(url, user, pwd) return Connection
• jdbc:<subprotocol>://<host>:<port>/<db>
– jdbc:mysql://localhost:3306/testDB
3. Connect to database
• Load JDBC driver
– Class.forName("com.mysql.jdbc.Driver").newInstance();
• Make connection
– Connection conn = DriverManager.getConnection(url);
• URL
– Format: jdbc:<subprotocol>://<host>:<port>/<db>
– jdbc:mysql://localhost:3306/testDB
4. Query database
a. Create statement
– Statement stmt = conn.createStatement();
– stmt object sends SQL commands to database
– Methods
• executeQuery() for SELECT statements
• executeUpdate() for INSERT, UPDATE, DELETE, statements
b. Send SQL statements
– stmt.executeQuery(“SELECT …”);
– stmt.executeUpdate(“INSERT …”);
5. Process results
• Result of a SELECT statement (rows/columns) returned as a ResultSet object
– ResultSet rs = stmt.executeQuery("SELECT * FROM users");
• Step through each row in the result
– rs.next()
• Get column values in a row
– String userid = rs.getString(“userid”);
– int type = rs.getInt(“type”);
users table
userid firstname lastname password type
Bob Bob King cat 0
John John Smith pass 1
Print the users table
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
String userid = rs.getString(1);
String firstname = rs.getString(“firstname”);
String lastname = rs.getString(“lastname”);
String password = rs.getString(4);
int type = rs.getInt(“type”);
System.out.println(userid + ” ” + firstname + ” ” +
lastname + ” ” + password + ” ” + type);
}
users table
userid firstname lastname password type
Bob Bob King cat 0
John John Smith pass 1
Add a row to the users table
String str = "INSERT INTO users VALUES('Bob', 'Bob', 'King',
'cat', 0)”;
//Returns number of rows in table
int rows = stmt.executeUpdate(str);
users table
userid firstname lastname password type
Bob Bob King cat 0
6. Closing connections
• Close the ResultSet object
– rs.close();
• Close the Statement object
– stmt.close();
• Close the connection
– conn.close();
import java.sql.*;
public class Tester {
public static void main(String[] args) {
try {
// Load JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Make connection
String url = “jdbc:mysql://localhost:3306/testDB”;
Connection conn = DriverManager.getConnection(url, ”root”, ”rev”);
// Create statement
Statement stmt = conn.createStatement();
// Print the users table
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString(1)+”t”+rs.getString(2));
...
}
// Cleanup
rs.close(); stmt.close(); conn.close();
}
catch (Exception e) {
System.out.println("exception " + e);
}
}
Transactions
• Currently every executeUpdate() is “finalized” right away
• Sometimes want to a set of updates to all fail or all succeed
– E.g. add to Appointments and Bookings tables
– Treat both inserts as one transaction
• Transaction
– Used to group several SQL statements together
– Either all succeed or all fail
Transactions
• Commit
– Execute all statements as one unit
– “Finalize” updates
• Rollback
– Abort transaction
– All uncommited statements are discarded
– Revert database to original state
Transactions in JDBC
• Disable auto-commit for the connection
– conn.setAutoCommit(false);
• Call necessary executeUpdate() statements
• Commit or rollback
– conn.commit();
– conn.rollback();
JDBC Driver
There are four flavors of JDBC
JDBC-ODBC Bridge (Type 1 driver)
Native-API/partly-Java driver (Type 2 driver)
Net-protocol/all-Java driver (Type 3 driver)
Native-protocol/all-Java driver (Type 4 driver)
JDBC Driver
• We will use the,
Native-protocol/all-Java driver
Java
Application
Native-protocol/all-Java
driver
Database
server
Functionality of Type 4 driver
Example
import java.sql.*;
import java.io.*;
class JDBC
{
public static void main(String[] args)
{
try
{
Connection conn;
Statement stmt;
String Query;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost/game","root","password");
stmt=conn.createStatement();
Query="select * from table1";
rs=stmt.executeQuery(Query);
while(rs.next())
{ String s = rs.getString(1);
System.out.println(s);
}
rs.close();
conn.close();
}
catch(SQLException sqle)
{
System.out.println(sqle);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Loading the Driver
a) Import statements
import java.sql.*;
b) Loading the database driver
Class.forName("com.mysql.jdbc.Driver");
- We load the driver class by calling Class.forName() with the Driver
class name as an argument
- If the class name is jdbc.DriverXYZ , you would load the driver with the
following line of code: Class.forName("jdbc.DriverXYZ");
- Once loaded, the Driver class creates an instance of itself.

More Related Content

Similar to session and cookies.ppt

24 HOP edición Español -Diferentes técnicas de administración de logins y usu...
24 HOP edición Español -Diferentes técnicas de administración de logins y usu...24 HOP edición Español -Diferentes técnicas de administración de logins y usu...
24 HOP edición Español -Diferentes técnicas de administración de logins y usu...
SpanishPASSVC
 
0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf
Zani10
 
CMPE282_009994036_PROJECT_REPORT
CMPE282_009994036_PROJECT_REPORTCMPE282_009994036_PROJECT_REPORT
CMPE282_009994036_PROJECT_REPORT
Sandyarathi Das
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
Gaurav Bhardwaj
 

Similar to session and cookies.ppt (20)

24 HOP edición Español -Diferentes técnicas de administración de logins y usu...
24 HOP edición Español -Diferentes técnicas de administración de logins y usu...24 HOP edición Español -Diferentes técnicas de administración de logins y usu...
24 HOP edición Español -Diferentes técnicas de administración de logins y usu...
 
Session and state management
Session and state managementSession and state management
Session and state management
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6
 
Servers names
Servers namesServers names
Servers names
 
Servers names
Servers namesServers names
Servers names
 
0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Module5SADP.pptx
Module5SADP.pptxModule5SADP.pptx
Module5SADP.pptx
 
Servlet programming
Servlet programmingServlet programming
Servlet programming
 
CS8651 IP Unit 3.pptx
CS8651 IP Unit 3.pptxCS8651 IP Unit 3.pptx
CS8651 IP Unit 3.pptx
 
Research Inventy : International Journal of Engineering and Science
Research Inventy : International Journal of Engineering and ScienceResearch Inventy : International Journal of Engineering and Science
Research Inventy : International Journal of Engineering and Science
 
Enterprice java
Enterprice javaEnterprice java
Enterprice java
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
CMPE282_009994036_PROJECT_REPORT
CMPE282_009994036_PROJECT_REPORTCMPE282_009994036_PROJECT_REPORT
CMPE282_009994036_PROJECT_REPORT
 
It and ej
It and ejIt and ej
It and ej
 
Major project report
Major project reportMajor project report
Major project report
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
 

More from Jayaprasanna4

More from Jayaprasanna4 (20)

Human computer Interaction ch1-the human.pdf
Human computer Interaction ch1-the human.pdfHuman computer Interaction ch1-the human.pdf
Human computer Interaction ch1-the human.pdf
 
computer Networks Error Detection and Correction.ppt
computer Networks Error Detection and Correction.pptcomputer Networks Error Detection and Correction.ppt
computer Networks Error Detection and Correction.ppt
 
HUman computer Interaction Socio-organizational Issues.ppt
HUman computer Interaction Socio-organizational Issues.pptHUman computer Interaction Socio-organizational Issues.ppt
HUman computer Interaction Socio-organizational Issues.ppt
 
human computer Interaction cognitive models.ppt
human computer Interaction cognitive models.ppthuman computer Interaction cognitive models.ppt
human computer Interaction cognitive models.ppt
 
World wide web and Hyper Text Markup Language
World wide web and Hyper Text Markup LanguageWorld wide web and Hyper Text Markup Language
World wide web and Hyper Text Markup Language
 
CI-Monte-Carlo.ppt
CI-Monte-Carlo.pptCI-Monte-Carlo.ppt
CI-Monte-Carlo.ppt
 
Activity planning.ppt
Activity planning.pptActivity planning.ppt
Activity planning.ppt
 
Cost effort.ppt
Cost effort.pptCost effort.ppt
Cost effort.ppt
 
Activity planning.ppt
Activity planning.pptActivity planning.ppt
Activity planning.ppt
 
unit-1.ppt
unit-1.pptunit-1.ppt
unit-1.ppt
 
BGP.ppt
BGP.pptBGP.ppt
BGP.ppt
 
Lecture 19- Multicasting.ppt
Lecture 19- Multicasting.pptLecture 19- Multicasting.ppt
Lecture 19- Multicasting.ppt
 
line coding.ppt
line coding.pptline coding.ppt
line coding.ppt
 
error detection.ppt
error detection.ppterror detection.ppt
error detection.ppt
 
connecting LANs.pptx
connecting LANs.pptxconnecting LANs.pptx
connecting LANs.pptx
 
CS1302 06NOV.pdf
CS1302 06NOV.pdfCS1302 06NOV.pdf
CS1302 06NOV.pdf
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
connecting devices.ppt
connecting devices.pptconnecting devices.ppt
connecting devices.ppt
 
ARP.ppt
ARP.pptARP.ppt
ARP.ppt
 
Transport_layer.ppt
Transport_layer.pptTransport_layer.ppt
Transport_layer.ppt
 

Recently uploaded

Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 

Recently uploaded (20)

Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Signal Processing and Linear System Analysis
Signal Processing and Linear System AnalysisSignal Processing and Linear System Analysis
Signal Processing and Linear System Analysis
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Computer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesComputer Graphics Introduction To Curves
Computer Graphics Introduction To Curves
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 

session and cookies.ppt

  • 1. Session Tracking in Servlets • Session simply means a particular interval of time. • Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet. • Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user. • HTTP is stateless that means each request is considered as the new request. Session Tracking Techniques There are four techniques used in Session tracking: 1. Cookies 2. Hidden Form Field 3. URL Rewriting 4. HttpSession
  • 2. Cookies • small piece of information that is persisted between the multiple client requests • name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. • A web server can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. • used for storing client state
  • 3. Types of Cookie There are 2 types of cookies in servlets. 1. Non-persistent cookie 2. Persistent cookie Non-persistent cookie It is valid for single session only. It is removed each time when user closes the browser. Persistent cookie It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout. Advantage of Cookies 1. Simplest technique of maintaining the state. 2. Cookies are maintained at client side. Disadvantage of Cookies 1. It will not work if cookie is disabled from the browser. 2. Only textual information can be set in Cookie object.
  • 4.
  • 5.
  • 6. create Cookie Cookie ck=new Cookie("user","sony");//creating cookie object response.addCookie(ck);//adding cookie in the response delete Cookie Cookie ck=new Cookie("user","");//deleting value of cookie ck.setMaxAge(0);//changing the maximum age to 0 seconds response.addCookie(ck);//adding cookie in the response
  • 7.
  • 8. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); Cookie ck=new Cookie("uname",n);//creating cookie object response.addCookie(ck);//adding cookie in the response //creating submit button out.print("<form action='servlet2'>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out.println(e);} } }
  • 9. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); Cookie ck[]=request.getCookies(); out.print("Hello "+ck[0].getValue()); out.close(); }catch(Exception e){System.out.println(e);} } }
  • 10. web.xml (web. xml defines mappings between URL paths and the servlets that handle requests with those paths.) <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
  • 11.
  • 12. Hidden Form Fields: • a hidden (invisible) textfield is used for maintaining the state of an user • <input type="hidden" name="sessionid" value="12345"> • we store the information in the hidden field and get it from another servlet • when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers. URL Rewriting append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. http://point.com/file.htm;sessionid=12345
  • 15. Advantage of URL Rewriting • It will always work whether cookie is disabled or not (browser independent). • Extra form submission is not required on each pages. Disadvantage of URL Rewriting • It will work only with links. • It can send Only textual information.
  • 16. • whenever a user starts using our application, we can save a unique identification information about him, in an object which is available throughout the application, until its destroyed. • So wherever the user goes, we will always have his information and we can always manage which user is doing what. Whenever a user wants to exit from your application, destroy the object with his information. HttpSession
  • 17.
  • 18. <form method="post" action="Validate"> User: <input type="text" name="user" /><br/> Password: <input type="text" name="pass" ><br/> <input type="submit" value="submit"> </form> <web-app..> <servlet> <servlet-name>Validate</servlet-name> <servlet-class>Validate</servlet-class> </servlet> <servlet> <servlet-name>Welcome</servlet-name> <servlet-class>Welcome</servlet-class> </servlet> <servlet-mapping> <servlet-name>Validate</servlet-name> <url-pattern>/Validate</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Welcome</servlet-name> <url-pattern>/Welcome</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
  • 19. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Validate extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("user"); String pass = request.getParameter("pass"); if(pass.equals("1234")) { //creating a session HttpSession session = request.getSession(); session.setAttribute("user", name); response.sendRedirect("Welcome"); } } }
  • 20. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Welcome extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); String user = (String)session.getAttribute("user"); out.println("Hello "+user); } }
  • 21.
  • 22. DATABASE CONNECTIVITY – Database connectivity allows the client software to communicate with the database server software. – It is an interface that allows communication between the database and the software application. – Elements of frontend applications/websites like buttons, fonts, or menus need to be connected to the database (back-end) to deliver relevant information to the end-user. – Database connectivity can be done using different programming languages such as Java, C++, and HTML (hypertext markup language). – By using these languages, one can connect a program to a particular database and can query data to access and manipulate them.
  • 23. Querying the database • Organized collection of data in a computer system is a database. • It stores information in the form of structured tables that contain rows and columns to organize the data. • It is controlled by the management system. • DBMS enables creation and maintenance of database.
  • 24. SQL – SQL (Structured Query Language) is used for querying the data stored in a relational database. – MySQL database and SQL select are some modified versions of SQL. – The query is categorized into DDL (Data Definition Language) and DML (Data Manipulation Language).
  • 25. – Data Definition Language (DDL): • The statements used to create the database schema and the tables are referred to as DDL. • They can also be used to modify the structure of the table. For example, CREATE, ALTER and so forth. – Data Manipulation Language (DML): • These statements are used to insert records into the table, update and delete records present in the table. • For example, INSERT, UPDATE, DELETE and so forth.
  • 26. Database Driver • A driver is a computer program that helps applications to establish database connection. • There are two standard protocols for establishing database connectivity name Open Database Connectivity (ODBC) and Java Database Connectivity (JDBC). • These enable applications to access and manipulate database contents by providing a generic interface.
  • 27. Servlet – Database connection • A Servlet can generate dynamic HTML by retrieving data from the database and sending it back to the client as a response. • We can also update the database based on data passed in the client HTTP request. • We will create a simple servlet to fetch/retrieve data from the database based on the client’s request.
  • 28. What is JDBC? • JDBC is: a Sun trademark – is often taken to stand for Java Database Connectivity. – is a Java API for connecting programs written in Java to the data in relational databases. – consists of a set of classes and interfaces written in the Java programming language. – provides a standard API for tool/database developers and makes it possible to write database applications using a pure Java API. – The standard defined by Sun Microsystems, allowing individual providers to implement and extend the standard with their own JDBC drivers.
  • 29. JDBC • Java is very standardized, but there are many versions of SQL • JDBC is a means of accessing SQL databases from Java – JDBC is a standardized API for use by Java programs – JDBC is also a specification for how third-party vendors should write database drivers to access specific SQL versions • JDBC: – establishes a connection with a database – sends SQL statements – processes the results.
  • 30. The need of an application • Databases offer structured storing, easy retrieval and processing of data • The maintenance, however, can be tedious Suppose you manage a database store on an SQL server. Then you need to have a knowledge on SQL in order to retrieve or update data. This will not be that pleasant for you. Will it? • An application in between can do the job for you The application will deal with the database while you interact with the user-friendly GUI
  • 31. JDBC • Java Database Connectivity • Provides a Java API to access SQL databases
  • 32. The JDBC API • The JDBC API contains methods to communicate with DBMS or RDBMS • The JDBC API uses the JDBC driver to carry out it tasks • The JDBC API & Driver enables a Java application to: 1. Establish a connection with a data source 2. Send queries and update statements to the data source 3. Process the results Java Program JDBC API JDBC Driver Database The process of accessing the database
  • 33. JDBC API • The JDBC API supports both two-tier and three-tier models for database access. • Two-tier model -- a Java applet or application interacts directly with the database. • Three-tier model -- introduces a middle-level server for execution of business logic: – the middle tier to maintain control over data access. – the user can employ an easy-to-use higher-level API which is translated by the middle tier into the appropriate low-level calls.
  • 34. The JDBC API • The JDBC API supports both two-tier and three-tier models Java Application DBMS JDBC Client machine DBMS – proprietary protocol Database server Two-tier model Java applet or HTML browser DBMS Application server (Java) JDBC Client machine (GUI) HTTP, RMI, CORBA or other calls Server machine (business logic) DBMS – proprietary protocol Database server Three-tier model
  • 35. JDBC Classes • java.sql. – DriverManager • getConnection – Connection • createStatement – Statement • execute, executeQuery, executeBatch, executeUpdate – ResultSet • next, getString, getInt, getDate, getMetaData – ResultSetMetadata • getColumnCount, getColumnName, getColumnType
  • 36. JDBC Steps 1. Instantiate proper driver 2. Open connection to database 3. Connect to database 4. Query database (or insert/update/delete) 5. Process the result 6. Close connection to database
  • 37. 1. Instantiate Driver • Class.forName(“driver class”) - to dynamically load the driver's class file into memory, which automatically registers it • Driver class is vendor dependent, e.g., – sun.jdbc.odbc.JdbcOdbcDriver • JDBC-ODBC bridge used to access ODBC Sources – com.mysql.jdbc.Driver • driver to access MySQL database – com.sybase.jdbc2.jdbc.SybDriver • driver to access Sybase database
  • 38. 2. Open Connection • DriverManager.getConnection(url) - creates a Connection object, which is used to create SQL statements, send them to the Informix database, and process the results. or • DriverManager.getConnection(url, user, pwd) return Connection • jdbc:<subprotocol>://<host>:<port>/<db> – jdbc:mysql://localhost:3306/testDB
  • 39. 3. Connect to database • Load JDBC driver – Class.forName("com.mysql.jdbc.Driver").newInstance(); • Make connection – Connection conn = DriverManager.getConnection(url); • URL – Format: jdbc:<subprotocol>://<host>:<port>/<db> – jdbc:mysql://localhost:3306/testDB
  • 40. 4. Query database a. Create statement – Statement stmt = conn.createStatement(); – stmt object sends SQL commands to database – Methods • executeQuery() for SELECT statements • executeUpdate() for INSERT, UPDATE, DELETE, statements b. Send SQL statements – stmt.executeQuery(“SELECT …”); – stmt.executeUpdate(“INSERT …”);
  • 41. 5. Process results • Result of a SELECT statement (rows/columns) returned as a ResultSet object – ResultSet rs = stmt.executeQuery("SELECT * FROM users"); • Step through each row in the result – rs.next() • Get column values in a row – String userid = rs.getString(“userid”); – int type = rs.getInt(“type”); users table userid firstname lastname password type Bob Bob King cat 0 John John Smith pass 1
  • 42. Print the users table ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { String userid = rs.getString(1); String firstname = rs.getString(“firstname”); String lastname = rs.getString(“lastname”); String password = rs.getString(4); int type = rs.getInt(“type”); System.out.println(userid + ” ” + firstname + ” ” + lastname + ” ” + password + ” ” + type); } users table userid firstname lastname password type Bob Bob King cat 0 John John Smith pass 1
  • 43. Add a row to the users table String str = "INSERT INTO users VALUES('Bob', 'Bob', 'King', 'cat', 0)”; //Returns number of rows in table int rows = stmt.executeUpdate(str); users table userid firstname lastname password type Bob Bob King cat 0
  • 44. 6. Closing connections • Close the ResultSet object – rs.close(); • Close the Statement object – stmt.close(); • Close the connection – conn.close();
  • 45. import java.sql.*; public class Tester { public static void main(String[] args) { try { // Load JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Make connection String url = “jdbc:mysql://localhost:3306/testDB”; Connection conn = DriverManager.getConnection(url, ”root”, ”rev”); // Create statement Statement stmt = conn.createStatement(); // Print the users table ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { System.out.println(rs.getString(1)+”t”+rs.getString(2)); ... } // Cleanup rs.close(); stmt.close(); conn.close(); } catch (Exception e) { System.out.println("exception " + e); } }
  • 46. Transactions • Currently every executeUpdate() is “finalized” right away • Sometimes want to a set of updates to all fail or all succeed – E.g. add to Appointments and Bookings tables – Treat both inserts as one transaction • Transaction – Used to group several SQL statements together – Either all succeed or all fail
  • 47. Transactions • Commit – Execute all statements as one unit – “Finalize” updates • Rollback – Abort transaction – All uncommited statements are discarded – Revert database to original state
  • 48. Transactions in JDBC • Disable auto-commit for the connection – conn.setAutoCommit(false); • Call necessary executeUpdate() statements • Commit or rollback – conn.commit(); – conn.rollback();
  • 49. JDBC Driver There are four flavors of JDBC JDBC-ODBC Bridge (Type 1 driver) Native-API/partly-Java driver (Type 2 driver) Net-protocol/all-Java driver (Type 3 driver) Native-protocol/all-Java driver (Type 4 driver)
  • 50. JDBC Driver • We will use the, Native-protocol/all-Java driver Java Application Native-protocol/all-Java driver Database server Functionality of Type 4 driver
  • 51. Example import java.sql.*; import java.io.*; class JDBC { public static void main(String[] args) { try { Connection conn; Statement stmt; String Query; ResultSet rs; Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost/game","root","password"); stmt=conn.createStatement();
  • 52. Query="select * from table1"; rs=stmt.executeQuery(Query); while(rs.next()) { String s = rs.getString(1); System.out.println(s); } rs.close(); conn.close(); } catch(SQLException sqle) { System.out.println(sqle); } catch(Exception e) { System.out.println(e); } } }
  • 53. Loading the Driver a) Import statements import java.sql.*; b) Loading the database driver Class.forName("com.mysql.jdbc.Driver"); - We load the driver class by calling Class.forName() with the Driver class name as an argument - If the class name is jdbc.DriverXYZ , you would load the driver with the following line of code: Class.forName("jdbc.DriverXYZ"); - Once loaded, the Driver class creates an instance of itself.