session and cookies.ppt

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.
session and cookies.ppt
session and cookies.ppt
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
session and cookies.ppt
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>
session and cookies.ppt
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
session and cookies.ppt
<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);
}
}
session and cookies.ppt
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.
1 de 53

Recomendados

IT2255 Web Essentials - Unit V Servlets and Database Connectivity por
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
116 vistas31 diapositivas
Enterprise java unit-2_chapter-3 por
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3sandeep54552
549 vistas21 diapositivas
Server side programming bt0083 por
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
234 vistas10 diapositivas
State Management.pptx por
State Management.pptxState Management.pptx
State Management.pptxDrMonikaPatel2
4 vistas31 diapositivas
BITM3730Week12.pptx por
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptxMattMarino13
7 vistas20 diapositivas
Advanced java+JDBC+Servlet por
Advanced java+JDBC+ServletAdvanced java+JDBC+Servlet
Advanced java+JDBC+ServletAnuj Singh Rajput
96 vistas22 diapositivas

Más contenido relacionado

Similar a session and cookies.ppt

24 HOP edición Español -Diferentes técnicas de administración de logins y usu... por
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
280 vistas26 diapositivas
Session and state management por
Session and state managementSession and state management
Session and state managementPaneliya Prince
172 vistas89 diapositivas
SCWCD : Session management : CHAP : 6 por
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6Ben Abdallah Helmi
418 vistas78 diapositivas
Servers names por
Servers namesServers names
Servers namesSasidhar Kothuru
195 vistas14 diapositivas
Servers names por
Servers namesServers names
Servers namesSasidhar Kothuru
296 vistas14 diapositivas
0_Leksion_Web_Servers (1).pdf por
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdfZani10
13 vistas41 diapositivas

Similar a session and cookies.ppt(20)

24 HOP edición Español -Diferentes técnicas de administración de logins y usu... por SpanishPASSVC
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...
SpanishPASSVC280 vistas
0_Leksion_Web_Servers (1).pdf por Zani10
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf
Zani1013 vistas
Angular - Chapter 7 - HTTP Services por WebStackAcademy
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
WebStackAcademy648 vistas
Research Inventy : International Journal of Engineering and Science por researchinventy
Research Inventy : International Journal of Engineering and ScienceResearch Inventy : International Journal of Engineering and Science
Research Inventy : International Journal of Engineering and Science
researchinventy158 vistas
Generating the Server Response: HTTP Status Codes por DeeptiJava
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
DeeptiJava156 vistas
CMPE282_009994036_PROJECT_REPORT por Sandyarathi Das
CMPE282_009994036_PROJECT_REPORTCMPE282_009994036_PROJECT_REPORT
CMPE282_009994036_PROJECT_REPORT
Sandyarathi Das262 vistas
Ppt for Online music store por ADEEBANADEEM
Ppt for Online music storePpt for Online music store
Ppt for Online music store
ADEEBANADEEM3.7K vistas
Pinterest like site using REST and Bottle por Gaurav Bhardwaj
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
Gaurav Bhardwaj1.4K vistas

Más de Jayaprasanna4

CI-Monte-Carlo.ppt por
CI-Monte-Carlo.pptCI-Monte-Carlo.ppt
CI-Monte-Carlo.pptJayaprasanna4
1 vista10 diapositivas
Activity planning.ppt por
Activity planning.pptActivity planning.ppt
Activity planning.pptJayaprasanna4
2 vistas33 diapositivas
Cost effort.ppt por
Cost effort.pptCost effort.ppt
Cost effort.pptJayaprasanna4
1 vista22 diapositivas
Activity planning.ppt por
Activity planning.pptActivity planning.ppt
Activity planning.pptJayaprasanna4
1 vista33 diapositivas
unit-1.ppt por
unit-1.pptunit-1.ppt
unit-1.pptJayaprasanna4
12 vistas68 diapositivas
BGP.ppt por
BGP.pptBGP.ppt
BGP.pptJayaprasanna4
1 vista19 diapositivas

Más de Jayaprasanna4(20)

IDC lectureA - Network Layer & IP Addressing with Cisco Notes.ppt por Jayaprasanna4
IDC lectureA - Network Layer & IP Addressing with Cisco Notes.pptIDC lectureA - Network Layer & IP Addressing with Cisco Notes.ppt
IDC lectureA - Network Layer & IP Addressing with Cisco Notes.ppt
Jayaprasanna413 vistas
Supply Chain Drivers and Obstacles.ppt por Jayaprasanna4
Supply Chain Drivers and Obstacles.pptSupply Chain Drivers and Obstacles.ppt
Supply Chain Drivers and Obstacles.ppt
Jayaprasanna421 vistas
7 - 11 casestudy-converted.pptx por Jayaprasanna4
7 - 11 casestudy-converted.pptx7 - 11 casestudy-converted.pptx
7 - 11 casestudy-converted.pptx
Jayaprasanna417 vistas

Último

SNMPx por
SNMPxSNMPx
SNMPxAmatullahbutt
17 vistas12 diapositivas
Proposal Presentation.pptx por
Proposal Presentation.pptxProposal Presentation.pptx
Proposal Presentation.pptxkeytonallamon
29 vistas36 diapositivas
Investor Presentation por
Investor PresentationInvestor Presentation
Investor Presentationeser sevinç
25 vistas26 diapositivas
Introduction to CAD-CAM.pptx por
Introduction to CAD-CAM.pptxIntroduction to CAD-CAM.pptx
Introduction to CAD-CAM.pptxsuyogpatil49
5 vistas15 diapositivas
Final Year Presentation por
Final Year PresentationFinal Year Presentation
Final Year PresentationComsat Universal Islamabad Wah Campus
7 vistas29 diapositivas
Digital Watermarking Of Audio Signals.pptx por
Digital Watermarking Of Audio Signals.pptxDigital Watermarking Of Audio Signals.pptx
Digital Watermarking Of Audio Signals.pptxAyushJaiswal781174
12 vistas25 diapositivas

Último(20)

Proposal Presentation.pptx por keytonallamon
Proposal Presentation.pptxProposal Presentation.pptx
Proposal Presentation.pptx
keytonallamon29 vistas
Introduction to CAD-CAM.pptx por suyogpatil49
Introduction to CAD-CAM.pptxIntroduction to CAD-CAM.pptx
Introduction to CAD-CAM.pptx
suyogpatil495 vistas
Generative AI Models & Their Applications por SN
Generative AI Models & Their ApplicationsGenerative AI Models & Their Applications
Generative AI Models & Their Applications
SN8 vistas
MSA Website Slideshow (16).pdf por msaucla
MSA Website Slideshow (16).pdfMSA Website Slideshow (16).pdf
MSA Website Slideshow (16).pdf
msaucla68 vistas
Instrumentation & Control Lab Manual.pdf por NTU Faisalabad
Instrumentation & Control Lab Manual.pdfInstrumentation & Control Lab Manual.pdf
Instrumentation & Control Lab Manual.pdf
NTU Faisalabad 5 vistas
What is Whirling Hygrometer.pdf por IIT KHARAGPUR
What is Whirling Hygrometer.pdfWhat is Whirling Hygrometer.pdf
What is Whirling Hygrometer.pdf
IIT KHARAGPUR 12 vistas
Effect of deep chemical mixing columns on properties of surrounding soft clay... por AltinKaradagli
Effect of deep chemical mixing columns on properties of surrounding soft clay...Effect of deep chemical mixing columns on properties of surrounding soft clay...
Effect of deep chemical mixing columns on properties of surrounding soft clay...
AltinKaradagli6 vistas
zincalume water storage tank design.pdf por 3D LABS
zincalume water storage tank design.pdfzincalume water storage tank design.pdf
zincalume water storage tank design.pdf
3D LABS5 vistas

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.
  • 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
  • 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>
  • 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
  • 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); } }
  • 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.