You are on page 1of 73

UNIT 5

SERVLETS AND DATABASE CONNECTIVITY

Servlets: Java Servlet Architecture –


Servlet Life cycle- Form GET and POST
actions -Sessions – Cookies – Database
connectivity - JDBC Creation of simple
interactive applications - Simple
database applications
Servlets
Java Servlet Architecture
 Servlet Life Cycle
Form GET and POST actions
Session Handling
Understanding Cookies
Installing and Configuring Apache Tomcat Web
Server
DATABASE CONNECTIVITY:
 JDBC perspectives, JDBC program example
Servers
• A server is a computer that responds to requests from
a client
– Typical requests: provide a web page, upload or download a file,
send email
• A server is also the software that responds to these
requests; a client could be the browser or other
software making these requests.
• Computer is the client(Browser), and someone else’s big
computer is the server
– However, any computer can be a server
– It is not unusual to have server software and client software
running on the same computer
Apache
• Apache is a very popular server
– 66% of the web sites on the Internet use Apache
• Features:
– Full-featured and extensible
– Efficient
– Robust
– Secure (at least, more secure than other servers)
– Up to date with current standards
– Open source
Ports
• A port is a connection between a server and a client
– Ports are identified by positive integers
– A port is a software notion, not a hardware notion, so there may
be various uses.
• A service is associated with a specific port
– Typical port numbers:
• 21—FTP, File Transfer Protocol
• 22—SSH, Secure Shell
• 25—SMTP, Simple Mail Transfer Protocol
• 53—DNS, Domain Name Service
• 80—HTTP, Hypertext Transfer Protocol
• 8080—HTTP (used for testing HTTP)
• 7648, 7649—TCP/UDP - CU-SeeMe (Cornell University - video
conferencing)
• 27960—Quake III(video game)
CGI Scripts
“Common Gateway Interface”
Client sends a request to server
Server starts a CGI script client server
Script computes a result for server
client
and quits script
Server returns response to client
Another client sends a request
client server
Server starts the CGI script again
client
servlet
Servlets vs. CGI scripts
• Advantages:
– Running a servlet doesn’t require creating a
separate process each time
– A servlet stays in memory, so it doesn’t have to be
reloaded each time
– There is only one instance handling multiple
requests, not a separate instance for every request
– Untrusted servlets can be run in a “sandbox”
• Disadvantage:
– Less choice of languages (CGI scripts can be in any
language)
Perl 1
DB
Browser 1

Browser 2 Web Perl 2


Server DB
Browser N

Perl N
DB

DB
Browser 1

Browser 2 Web Servlet


Server DB
Browser N

DB
1. Java Servlet Architecture
Request – Response Process
Servlet container (servlet engine)
– Server that executes a servlet

HTTP Request Servlet


Servlet
Browser HTTP Container
HTTP Response Server
Static
Content
Benefits:
• Performance
– no process creation for each client request.
– Each request is handled by the servlet container process.
– After a servlet has completed processing a request, it stays resident in
memory, waiting for another request.
• Portability
• Rapid development cycle
– Servlets have access to the rich Java library - speed up the
development process.
• Robustness
– Managed by the Java Virtual Machine - no memory leakage or garbage
collection, which helps you write robust applications.
• Widespread acceptance - widely accepted technology.
2. Servlet Life Cycle

Initialization
init()

Service
service()

doGet() Concurrent
doPost() threads
doDelete() of Execution
doHead()
doTrace()
doOptions()

Destruction
destroy()
Packages
 javax.servlet

 javax.servlet.http

 javax.servlet.jsp
• A servlet is any class that implements the
javax.servlet.Servlet interface
– In practice, most servlets extend the
javax.servlet.http.HttpServlet class
– Some servlets extend
javax.servlet.GenericServlet instead
• Servlets, like applets, usually lack a main
method, but must implement or override
certain other methods
Generic Servlet & HTTP Servlet

GenericServlet
Client
request

Server service ( )
response

HTTPServlet
Browser

request doGet ( )
HTTP service ( )
Server
response doPost ( )
GenericServlet - Methods
• void init(ServletConfig config)
– Initializes the servlet.

• void service(ServletRequest req, ServletResponse res)


– Carries out a single request from the client.

• void destroy()
– Cleans up whatever resources are being held (e.g., memory, file
handlers, threads) and makes sure that any persistent state is
synchronized with the servlet's current in-memory state.

• ServletConfig getServletConfig()
– Returns a servlet config object, which contains any initialization
parameters and startup configuration for this servlet.

• String getServletInfo()
– Returns a string containing information about the servlet, such as
its author, version, and copyright.
Servlet Request Objects
• provides client request information to a servlet.
• the servlet container creates a servlet request object and
passes it as an argument to the servlet's service method.
• the ServletRequest interface define methods to retrieve
data sent as client request:
–parameter name and values
– attributes
– input stream
• HTTPServletRequest extends the ServletRequest
interface to provide request information for HTTP
servlets.
HttpServlet - Methods
void doGet (HttpServletRequest request,
HttpServletResponse response)
handles GET requests
void doPost (HttpServletRequest request,
HttpServletResponse response)
handles POST requests
void doPut (HttpServletRequest request,
HttpServletResponse response)
handles PUT requests
void doDelete (HttpServletRequest request,
HttpServletResponse response)
handles DELETE requests
HttpServletRequest - Methods

Enumeration getParameterNames()
an Enumeration of String objects, each String
containing the name of a request parameter; or an
empty Enumeration if the request has no
parameters
java.lang.String[] getParameterValues (java.lang.String name)
Returns an array of String objects containing all of
the values the given request parameter has, or null if
the parameter does not exist.
java.lang.String getParameter (java.lang.String name)
Returns the value of a request parameter as a String,
or null if the parameter does not exist.
HttpServletRequest - Methods

Cookie[] getCookies()
Returns an array containing all of the Cookie objects
the client sent with this request.
java.lang.String getMethod()
Returns the name of the HTTP method with which the
request was made, for example, GET, POST, or PUT.

java.lang.String getQueryString()
Returns the query string that is contained in the
request URL after the path.
HttpSession getSession()
Returns the current session associated with this
request, or if the request does not have a session,
creates one.
Servlet Response Objects
• Defines an object to assist a servlet in
sending a response to the client.

• The servlet container creates a


ServletResponse object and passes it as an
argument to the servlet's service method.
HttpServletResponse - Methods

java.io.PrintWriter getWriter()
Returns a PrintWriter object that can send
character text to the client

void setContentType (java.lang.String type)


Sets the content type of the response being sent
to the client. The content type may include the type
of character encoding used, for example, text/html;
charset=ISO-8859-4
int getBufferSize()
Returns the actual buffer size used for the
response
Servlet Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println( "<HTML><HEAD><TITLE> Hello You!” +“</Title></HEAD>” +
“<Body> Welcome to Kingston </BODY></HTML>“ );
out.close();
}
}
3.Understanding Cookies
Cookies features
• Cookies are stored in the client browser as pairs (string-
key, string-value). Each pair is associated to a URL domain

• Cookies have an expiration date. After that date, the client


state will be lost.

• Cookies are not a universal way to store the client state


(e.g., the client may disable cookies)

• Cookies are usually used in two situations:


 Remember client preferences (e.g., client language)
 Support to session management.
Program:
// RepeatVisitor.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class RepeatVisitor extends HttpServlet
{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{ boolean visit = true;
Cookie[] cookies = request.getCookies();
if (cookies != null)
{for(int i=0; i<cookies.length;i++)
Cookie c = cookies[i]; String s=c.getName();
if ((s.equals("repeat")) && (c.getValue().equals("yes")))
{ visit = false; break; }}}
String title;
if (visit)
{ Cookie returnVisitorCookie = new Cookie("repeat", "yes");
returnVisitorCookie.setMaxAge(60*60*24*365); // 1 year
response.addCookie(returnVisitorCookie); title = "Welcome User"; }
else { title = "Welcome Back"; }
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =“<DOCTYPE html>”;
out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"</BODY></HTML>"); }}
Understanding Cookies
Understanding Cookies
//web.xml
<servlet>
<init-param>
<param-name>username</param-name>
<param-value>admin1,admin2,admin3</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>admin1,admin2,admin3</param-value>
</init-param>
<init-param>
<param-name>cardno</param-name>
<param-value>123,234,345</param-value>
</init-param>
<servlet-name>Tom</servlet-name>
<servlet-class>DynamicServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Tom</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Correct</servlet-name>
<servlet-class>LoginSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Correct</servlet-name>
<url-pattern>/Success</url-pattern>
</servlet-mapping>
4. Session Handling

Keeping client information between pages

In a web application we may maintain the client state by


means of different techniques:
• Hidden fields
• URL rewriting
• Cookies
• Servlet and JSP API
Process of session handling:
1. The client sends a request to the server
2. The server creates a session which will encompass all the
interactions with that client in the next few minutes. This
session is identified with a session identifier
3. The server manages the client request and elaborates a
response to its request.
4. This management may remember some objects which
will be retrieved by later requests of the same session.
These remembered objects:
• are called attributes
• are associated to the session
• can be retrieved using a key (string)
5. When the server has finished managing the request, the
server sends to the client:
• its response (html/xml code)
• a cookie with the session identifier (sid)

6. When the client sends another request to the same


server, it includes the cookie (with the identifier sid) that
received from it. In this way the server can identify the
session.

7. The server manages the new request. In particular, it may


retrieve the session attributes which were set in the last
session access.
Session tracking in servlets:
1. Accessing the session object associated with the
current request.
Call request.getSession - to get an HttpSession object, which
is a simple hash table for storing user-specific data.
Ex:
HttpSession session = request.getSession(false);
if (session == null) {
printMessageSayingCartIsEmpty();
}
else {
extractCartAndPrintContents(session);
}
2. Looking up information associated with a session.
Call getAttribute on the HttpSession object - cast the
return value to the appropriate type, and check whether the
result is null.
Ex:
SomeClass value =
(SomeClass)session.getAttribute("someIdentifier");

3. Storing information in a session.


Use setAttribute with a key and a value.
Ex:
HttpSession session = request.getSession();
session.setAttribute("someIdentifier", value);
4. Discarding session data
1. Remove only the data your servlet created:
Call removeAttribute - to discard a specific value. Call
invalidate to discard an entire session.

2. Delete the whole session (in the current Web


application)
Call invalidate() - user’s session data to be lost

3. Log the user out and delete all sessions belonging to


user
Call logout - to log the client out of the Web server and
invalidate all sessions associated with that user.
The Session-Tracking API
 public Object getAttribute(String name)
 public Enumeration getAttributeNames()
 public void setAttribute(String name, Object value)
 public void removeAttribute(String name)
 public void invalidate()
 public void logout()
 public String getId()
 public boolean isNew()
 public long getCreationTime()
 public long getLastAccessedTime()
 public int getMaxInactiveInterval()
 public void setMaxInactiveInterval(int seconds)
Program1:
import java.io.*;
import javax.servlet.*; import javax.servlet.http.*;
import java.util.*;
public class ShowSession extends HttpServlet
{ public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
HttpSession session = request.getSession();
String heading;
Integer accessCount =(Integer)session.getAttribute("accessCount");
if (accessCount == null)
{ accessCount = new Integer(0);
heading = "Welcome, NewUser";
}
else
{ heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
session.setAttribute("accessCount", accessCount);
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+"Transitional//EN\">\n";
out.println(docType +"<HTML>\n" +"<HEAD><TITLE>" + title +
"</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +"<CENTER>\n" +
"<H1>" + heading + "</H1>\n" +"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1>\n" +"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +"<TR>\n" +
" <TD>ID\n" +" <TD>" + session.getId() + "\n" +
"<TR>\n" +
" <TD>Creation Time\n" +" <TD>" +new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +" <TD>Time of Last Access\n" +" <TD>" +new
Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +" <TD>Number of Previous Accesses\n" +
" <TD>" + accessCount + "\n" +"</TABLE>\n" +
"</CENTER></BODY></HTML>"); }}
Session tracking using hidden form fields
//test.html
<html><head>
<title>Hidden Form Demo</title></head>
<body>
<form method="post" action="FormA">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form></body></html>
//FormA.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FormA extends HttpServlet
{ protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
out.println("<form action='Second'>");
out.println("<input type='hidden' name='user' value='"+user+"'>");
out.println("<input type='submit' value='submit' >");
out.println("</form>");
}}
//FormB.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FormB extends HttpServlet
{ protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//getting parameter from the hidden field
String user = request.getParameter("user");
out.println("Welcome "+user);
}}
//web.xml
<welcome-file-list>
<welcome-file>test.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>FormA</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/FormA</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Second</servlet-name>
<servlet-class>FormB</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Second</servlet-name>
<url-pattern>/FormB</url-pattern>
</servlet-mapping>
5. DATABASE CONNECTIVITY

• JDBC provides a standard library for accessing relational


databases.

• By using the JDBC API, you can access a wide variety of


SQL databases with exactly the same Java syntax.

• It is important to note that although the JDBC API


standardizes the approach for connecting to databases, the
syntax for sending queries and committing transactions,
and the data structure representing the result, JDBC does
not attempt to standardize the SQL syntax.
JDBC Process
JDBC – Basics (Servlet database connectivity)

7 standard steps for querying databases:

1. Load the JDBC driver

Class.forName method - create a driver instance and register


it with the JDBC driver manager.

Ex:
//Type I
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
2. Define the connection URL – specifies the server host,
port, and database name.
3. Establish the connection - a network connection to the
database can be established.

Syntax:
String url = "jdbc:odbc:" + dbName;

Ex:
Connection conn = DriverManager.getConnection ("jdbc:odbc:tour");
or
Connection conn = DriverManager.getConnection (“url");
4. Create a Statement object - to send queries and
commands to the database.
Ex:
Statement stmt = conn.createStatement ();

• prepareStatement - Creates precompiled queries for


submission to the database.
• prepareCall - Accesses stored procedures in the database.
• rollback/commit - Controls transaction management.
• close - Terminates the open connection.
• isClosed - Determines whether the connection timed out or
was explicitly closed.
5. Execute a query or update – use execute, executeQuery,
executeUpdate or executeBatch methods on statement
objects.
Ex:

ResultSet rs1=stmt.executeQuery("select * from details");


Statement class – Methods:
• executeQuery - Executes an SQL query and returns the data in a
ResultSet. The ResultSet may be empty, but never null.

• executeUpdate - Used for UPDATE, INSERT, or DELETE commands.


returns the number of rows affected, which could be zero. Also provides
support for Data Definition Language (DDL) commands, for example,
CREATE TABLE, DROP TABLE, and ALTER TABLE.

• executeBatch - Executes a group of commands as a unit, returning an


array with the update counts for each command. Use addBatch to add a
command to the batch group. Note that vendors are not required to
implement this method in their driver to be JDBC compliant.

• setQueryTimeout - Specifies the amount of time a driver waits for


the result before throwing an SQLException.

• getMaxRows/setMaxRows - Determines the number of rows a


ResultSet may contain. Excess rows are silently dropped. The default is
zero for no limit.
ResultSet methods:
 next/previous
 relative/absolute
 getXxx
 wasNull
 findColumn
 getRow
 getMetaData
ResultSetMetaData methods:
 getColumnCount
 getColumnName
 getColumnType
 isReadOnly
 isSearchable
 isNullable
6. Process the results - ResultSet is returned. (set of rows
and columns that can be processed by calls to next and
various getXxx methods.)
• while(rs1.next())
• {
• out.println("<tr> ");
• out.print("<td>"+rs1.getString(1)+"</td>");
• out.print("<td> "+rs1.getInt(2)+"</td>");
• out.print("<td> "+rs1.getInt(3)+"</td>");
• out.print("<td> "+rs1.getInt(4)+"</td>");
• out.print("<td> "+rs1.getInt(5)+"</td>");

7. Close the connection – releasing resources to the database.


Ex:
• stmt.close();
• conn.close();
JDBC Driver Types:
 Type 1 driver: JDBC-ODBC bridge
Used to test JDBC applications against ODBC data source.
Slower than other driver types.

 Type 2 driver: Partial Java driver


Use native database API for data access. Support for wrapper
classes.

 Type 3 driver: Pure Java driver for accessing


middleware server. (written in java language)

 Type 4 driver: Pure Java driver for direct access to


database.
Most efficient and commonly used. Written in java language.
Servlet – Database connectivity
1. Create a database in MS-Access(tour.accdb)
2. Create the fields and insert values for the table(Table1)
3. Control Panel  System and Security  Administrative
Tools  select ODBC data Sources
4. Select the table and appropriate drivers for the
database connection
a. Set User DSN to MS Access Database
b. System DSN  Select “Add”  Select driver  click Finish
b. System DSN  Select “Add”  Select driver  click Finish
A new window opens: Give Data Source Name  click “Select”  choose
“tour.accdb”
Program: // demoser.java
import java.io.*; import java.util.*; import javax.servlet.*;
import javax.servlet.http.*; import java.sql.*;
public class demoser extends HttpServlet
{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{ PrintWriter out=res.getWriter();
try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:tour");
Statement stmt = conn.createStatement ();
ResultSet rs1=stmt.executeQuery("select * from Table1");
out.println("<html><body bgcolor=\"aqua\" color=\"red\"><br><br><center><h1>Student
Details</h1><br><br><table border=1><tr><th>Name</th><th>RollNo</th><th>"+
"Mark1</th><th>Mark2</th><th>Average</th><th>total</th></tr>");
while(rs1.next())
{ out.println("<tr> ");
out.print("<td>"+rs1.getString(1)+"</td>"); out.print("<td> "+rs1.getInt(2)+"</td>");
out.print("<td> "+rs1.getInt(3)+"</td>"); out.print("<td> "+rs1.getInt(4)+"</td>");
out.print("<td> "+rs1.getInt(5)+"</td>"); out.print("<td> "+rs1.getInt(6)+"</td>");
out.println("</tr> "); }
out.println("</table></center></body></html> ");
stmt.close(); conn.close(); }
catch (Exception e)
{ System.out.println("Error : "+e); } }}
//web.xml
<servlet>
<servlet-name>Database</servlet-name>
<servlet-class>demoser</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Database</servlet-name>
<url-pattern>/DBAccess</url-pattern>
</servlet-mapping>
6. Form GET and POST actions
GET vs. POST
• Advantages of POST
– URL is simpler
– Data is hidden from people looking over user data
– Larger amounts of data can be sent
– Can send special characters (e.g., in uploaded files)
– Browsers will not cache results
– Should always be used if the requests changes data on
server
• Advantages of GET
– Can bookmark results page
– Browsers can cache results
– Easier to test interactively
Reading Form Data using Servlet:
• getParameter(): You call request.getParameter() method
to get the value of a form parameter.
• getParameterValues(): Call this method if the parameter
appears more than once and returns multiple values, for
example checkbox.
• getParameterNames(): Call this method if you want a
complete list of all parameters in the current request.
//getmethod.html
<html> <body>
<form action=“Sample" method="GET">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name"/>
<input type="submit" value="Submit" />
</form>
</body> </html>
//Sample.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class Sample extends HttpServlet
{ public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n"; out.println(docType + "<html>\n" +
"<head><title>" +
title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First
Name</b>: " + request.getParameter("first_name") + "\n" + "
<li><b>Last Name</b>: " + request.getParameter("last_name") +
"\n" + "</ul>\n" + "</body></html>");
}}
Program2: (POST method)
//testpost.html
<html> <body>
<form action=“Demo" method="POST">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body> </html>
//Demo.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class Demo extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{response.setContentType("text/html"); PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" +
title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First Name</b>:
" + request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" + "</ul>\n" + "</body></html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}}

You might also like