SlideShare a Scribd company logo

session and cookies.ppt

session

session and cookies.ppt

1 of 53
Download to read offline
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

Recommended

IT2255 Web Essentials - Unit V Servlets and Database Connectivity
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
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3sandeep54552
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptxMattMarino13
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 

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
 
Session and state management
Session and state managementSession and state management
Session and state managementPaneliya Prince
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6Ben Abdallah Helmi
 
0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdfZani10
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
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 Scienceresearchinventy
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 
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 CodesDeeptiJava
 
CMPE282_009994036_PROJECT_REPORT
CMPE282_009994036_PROJECT_REPORTCMPE282_009994036_PROJECT_REPORT
CMPE282_009994036_PROJECT_REPORTSandyarathi Das
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music storeADEEBANADEEM
 
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

Activity planning.ppt
Activity planning.pptActivity planning.ppt
Activity planning.pptJayaprasanna4
 
Activity planning.ppt
Activity planning.pptActivity planning.ppt
Activity planning.pptJayaprasanna4
 
Lecture 19- Multicasting.ppt
Lecture 19- Multicasting.pptLecture 19- Multicasting.ppt
Lecture 19- Multicasting.pptJayaprasanna4
 
connecting LANs.pptx
connecting LANs.pptxconnecting LANs.pptx
connecting LANs.pptxJayaprasanna4
 
connecting devices.ppt
connecting devices.pptconnecting devices.ppt
connecting devices.pptJayaprasanna4
 
IDC lectureA - Network Layer & IP Addressing with Cisco Notes.ppt
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.pptJayaprasanna4
 
Supply Chain Drivers and Obstacles.ppt
Supply Chain Drivers and Obstacles.pptSupply Chain Drivers and Obstacles.ppt
Supply Chain Drivers and Obstacles.pptJayaprasanna4
 
7 - 11 casestudy-converted.pptx
7 - 11 casestudy-converted.pptx7 - 11 casestudy-converted.pptx
7 - 11 casestudy-converted.pptxJayaprasanna4
 

More from Jayaprasanna4 (20)

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
 
IDC lectureA - Network Layer & IP Addressing with Cisco Notes.ppt
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
 
MultipleAccess.ppt
MultipleAccess.pptMultipleAccess.ppt
MultipleAccess.ppt
 
Supply Chain Drivers and Obstacles.ppt
Supply Chain Drivers and Obstacles.pptSupply Chain Drivers and Obstacles.ppt
Supply Chain Drivers and Obstacles.ppt
 
7 - 11 casestudy-converted.pptx
7 - 11 casestudy-converted.pptx7 - 11 casestudy-converted.pptx
7 - 11 casestudy-converted.pptx
 
syseng.ppt
syseng.pptsyseng.ppt
syseng.ppt
 

Recently uploaded

Bresenham line-drawing-algorithm By S L Sonawane.pdf
Bresenham line-drawing-algorithm By S L Sonawane.pdfBresenham line-drawing-algorithm By S L Sonawane.pdf
Bresenham line-drawing-algorithm By S L Sonawane.pdfSujataSonawane11
 
my goal is place in mnc's companies and got good salary
my goal is place in mnc's companies and got good salarymy goal is place in mnc's companies and got good salary
my goal is place in mnc's companies and got good salarymonoarul2004
 
Hydraulics Introduction& Hydrostatics.pdf
Hydraulics  Introduction&   Hydrostatics.pdfHydraulics  Introduction&   Hydrostatics.pdf
Hydraulics Introduction& Hydrostatics.pdfGetacher Teshome
 
Petrogulf Misr I PICO International Training Certificate I 2016
Petrogulf Misr I PICO International Training Certificate I 2016Petrogulf Misr I PICO International Training Certificate I 2016
Petrogulf Misr I PICO International Training Certificate I 2016Abdelrahman Al-Gammal
 
Ai Catalyst 2024 ggggggggggggggggggggggggggggggggggggg
Ai Catalyst 2024 gggggggggggggggggggggggggggggggggggggAi Catalyst 2024 ggggggggggggggggggggggggggggggggggggg
Ai Catalyst 2024 gggggggggggggggggggggggggggggggggggggGoogleDSCDibrugarhUn
 
Thailand 2023Q3 CCTV Seasonal Spotlight Product - DGF.PDF
Thailand 2023Q3 CCTV Seasonal Spotlight Product - DGF.PDFThailand 2023Q3 CCTV Seasonal Spotlight Product - DGF.PDF
Thailand 2023Q3 CCTV Seasonal Spotlight Product - DGF.PDFPawachMetharattanara
 
Into the World of AI GDSC YCCE PPTX.pptx
Into the World of AI GDSC YCCE PPTX.pptxInto the World of AI GDSC YCCE PPTX.pptx
Into the World of AI GDSC YCCE PPTX.pptxGDSCYCCE
 
Fundamentals of Data Structure_Unit I.pptx
Fundamentals of Data Structure_Unit I.pptxFundamentals of Data Structure_Unit I.pptx
Fundamentals of Data Structure_Unit I.pptxDr. Madhuri Jawale
 
Eversendai - HSE Performance Management Systems-R1.pptx
Eversendai - HSE Performance Management Systems-R1.pptxEversendai - HSE Performance Management Systems-R1.pptx
Eversendai - HSE Performance Management Systems-R1.pptxADILRASHID54
 
20CE501PE – INDUSTRIAL WASTE MANAGEMENT.ppt
20CE501PE – INDUSTRIAL WASTE MANAGEMENT.ppt20CE501PE – INDUSTRIAL WASTE MANAGEMENT.ppt
20CE501PE – INDUSTRIAL WASTE MANAGEMENT.pptMohanumar S
 
Python Workshop Day - 03.pptx
Python Workshop Day - 03.pptxPython Workshop Day - 03.pptx
Python Workshop Day - 03.pptxShivanshSeth6
 
STATE EXAMS 4000 ONE LINERS TOTHEPOINTBYDHYANPAL.pdf
STATE EXAMS 4000 ONE LINERS TOTHEPOINTBYDHYANPAL.pdfSTATE EXAMS 4000 ONE LINERS TOTHEPOINTBYDHYANPAL.pdf
STATE EXAMS 4000 ONE LINERS TOTHEPOINTBYDHYANPAL.pdfpraveenkumar620098
 
Searching and Sorting Unit II Part I.pptx
Searching and Sorting Unit II Part I.pptxSearching and Sorting Unit II Part I.pptx
Searching and Sorting Unit II Part I.pptxDr. Madhuri Jawale
 
PetroDara I TransGlobe Energy Training Certificate I 2017
PetroDara I TransGlobe Energy Training Certificate I 2017PetroDara I TransGlobe Energy Training Certificate I 2017
PetroDara I TransGlobe Energy Training Certificate I 2017Abdelrahman Al-Gammal
 
WEPCO Summer Training Certificate I 2017
WEPCO Summer Training Certificate I 2017WEPCO Summer Training Certificate I 2017
WEPCO Summer Training Certificate I 2017Abdelrahman Al-Gammal
 
Better Builder Magazine, Issue 48 / Winter 2023
Better Builder Magazine, Issue 48 / Winter 2023Better Builder Magazine, Issue 48 / Winter 2023
Better Builder Magazine, Issue 48 / Winter 2023Better Builder Magazine
 
Eshpetco I LUKOIL Training Certificate I 2017
Eshpetco I LUKOIL Training Certificate I 2017Eshpetco I LUKOIL Training Certificate I 2017
Eshpetco I LUKOIL Training Certificate I 2017Abdelrahman Al-Gammal
 

Recently uploaded (20)

Bresenham line-drawing-algorithm By S L Sonawane.pdf
Bresenham line-drawing-algorithm By S L Sonawane.pdfBresenham line-drawing-algorithm By S L Sonawane.pdf
Bresenham line-drawing-algorithm By S L Sonawane.pdf
 
Mobile Hacking Unit 1
Mobile Hacking Unit 1Mobile Hacking Unit 1
Mobile Hacking Unit 1
 
my goal is place in mnc's companies and got good salary
my goal is place in mnc's companies and got good salarymy goal is place in mnc's companies and got good salary
my goal is place in mnc's companies and got good salary
 
Hydraulics Introduction& Hydrostatics.pdf
Hydraulics  Introduction&   Hydrostatics.pdfHydraulics  Introduction&   Hydrostatics.pdf
Hydraulics Introduction& Hydrostatics.pdf
 
Petrogulf Misr I PICO International Training Certificate I 2016
Petrogulf Misr I PICO International Training Certificate I 2016Petrogulf Misr I PICO International Training Certificate I 2016
Petrogulf Misr I PICO International Training Certificate I 2016
 
Ai Catalyst 2024 ggggggggggggggggggggggggggggggggggggg
Ai Catalyst 2024 gggggggggggggggggggggggggggggggggggggAi Catalyst 2024 ggggggggggggggggggggggggggggggggggggg
Ai Catalyst 2024 ggggggggggggggggggggggggggggggggggggg
 
Thailand 2023Q3 CCTV Seasonal Spotlight Product - DGF.PDF
Thailand 2023Q3 CCTV Seasonal Spotlight Product - DGF.PDFThailand 2023Q3 CCTV Seasonal Spotlight Product - DGF.PDF
Thailand 2023Q3 CCTV Seasonal Spotlight Product - DGF.PDF
 
Into the World of AI GDSC YCCE PPTX.pptx
Into the World of AI GDSC YCCE PPTX.pptxInto the World of AI GDSC YCCE PPTX.pptx
Into the World of AI GDSC YCCE PPTX.pptx
 
Fundamentals of Data Structure_Unit I.pptx
Fundamentals of Data Structure_Unit I.pptxFundamentals of Data Structure_Unit I.pptx
Fundamentals of Data Structure_Unit I.pptx
 
Eversendai - HSE Performance Management Systems-R1.pptx
Eversendai - HSE Performance Management Systems-R1.pptxEversendai - HSE Performance Management Systems-R1.pptx
Eversendai - HSE Performance Management Systems-R1.pptx
 
20CE501PE – INDUSTRIAL WASTE MANAGEMENT.ppt
20CE501PE – INDUSTRIAL WASTE MANAGEMENT.ppt20CE501PE – INDUSTRIAL WASTE MANAGEMENT.ppt
20CE501PE – INDUSTRIAL WASTE MANAGEMENT.ppt
 
Python Workshop Day - 03.pptx
Python Workshop Day - 03.pptxPython Workshop Day - 03.pptx
Python Workshop Day - 03.pptx
 
STATE EXAMS 4000 ONE LINERS TOTHEPOINTBYDHYANPAL.pdf
STATE EXAMS 4000 ONE LINERS TOTHEPOINTBYDHYANPAL.pdfSTATE EXAMS 4000 ONE LINERS TOTHEPOINTBYDHYANPAL.pdf
STATE EXAMS 4000 ONE LINERS TOTHEPOINTBYDHYANPAL.pdf
 
Searching and Sorting Unit II Part I.pptx
Searching and Sorting Unit II Part I.pptxSearching and Sorting Unit II Part I.pptx
Searching and Sorting Unit II Part I.pptx
 
Solar PPT.pdf
Solar PPT.pdfSolar PPT.pdf
Solar PPT.pdf
 
PetroDara I TransGlobe Energy Training Certificate I 2017
PetroDara I TransGlobe Energy Training Certificate I 2017PetroDara I TransGlobe Energy Training Certificate I 2017
PetroDara I TransGlobe Energy Training Certificate I 2017
 
WEPCO Summer Training Certificate I 2017
WEPCO Summer Training Certificate I 2017WEPCO Summer Training Certificate I 2017
WEPCO Summer Training Certificate I 2017
 
Better Builder Magazine, Issue 48 / Winter 2023
Better Builder Magazine, Issue 48 / Winter 2023Better Builder Magazine, Issue 48 / Winter 2023
Better Builder Magazine, Issue 48 / Winter 2023
 
IGBT.ppt
IGBT.pptIGBT.ppt
IGBT.ppt
 
Eshpetco I LUKOIL Training Certificate I 2017
Eshpetco I LUKOIL Training Certificate I 2017Eshpetco I LUKOIL Training Certificate I 2017
Eshpetco I LUKOIL Training Certificate I 2017
 

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.