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