Unit 4 We
Unit 4 We
Unit 4 We
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
A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
• The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method
to handle requests coming from the client( browsers) and to write
the formatted response back to the client.
• Each time the server receives a request for a servlet, the server
spawns a new thread and calls service.
• The service() method checks the HTTP request type (GET, POST,
PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.
• Here is the signature of this method −
A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
// Servlet code
}
A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
// Servlet code
}
The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to disk,
and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy method definition looks like this −
public void destroy()
{
// Finalization code...
}
Architecture Diagram
5.3.1GET Method
The GET method sends the encoded user information appended to the page
request. The page and the encoded information are separated by the ?
(question mark) symbol as follows −
Servlets handles form data parsing automatically using the following methods
depending on the situation −
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.
$ javac HelloForm.java
web.xml
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Output
Using GET Method to Read Form Data
First Name: ZARA
Last Name: ALI
Here is a simple example which passes two values using HTML FORM and submit button.
We are going to use same Servlet HelloForm to handle this input.
<html>
<body>
<form action = "HelloForm" 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>
Now compile and deploy the above Servlet and test it using Hello.htm with the POST
method as follows −
<html>
<body>
<form action = "HelloForm" 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>
Two common methods for the request-response between a server and client are:
The query string (name/value pairs) is sent inside the URL of a GET request:
GET/RegisterDao.jsp?name1=value1&name2=value2
The query string (name/value pairs) is sent in HTTP message body for a POST
request:
1. Cookies
• This may not be an effective way because many time browser does
not support a cookie, so I would not recommend to use this
procedure to maintain the sessions.
• A web server can send a hidden HTML form field along with a
unique session ID as fol- lows −
• This entry means that, when the form is submitted, the specified
name and value are auto- matically 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.
3. URL Rewriting
• You can 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.
session.setAttribute(visitCountKey, visitCount);
When you are done with a user's session data, you have several options
• Delete the whole session − You can call public void invalidate()
method to discard an en- tire session.
• Log the user out − The servers that support servlets 2.4, you can
call logout to log the client out of the Web server and invalidate all
sessions belonging to all the users.
• web.xml Configuration − If you are using Tomcat, apart from the
above mentioned meth- ods, you can configure session time out in
web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
5.6 COOKIES
Cookies are text files stored on the client computer and they are kept for
various information tracking purpose. Java Servlets transparently supports HTTP
cookies.
Creating a Cookie object − You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.
web.xml
<!-- Cookie Example -->
<web-app>
<servlet>
<servlet-name>cookie</servlet-name>
<servlet-class>AddCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookie</servlet-name>
<url-pattern>/addc</url-pattern>
</servlet-mapping>
</web-app>
Open addcookie.html in a browser and enter cookie data in the textbox and submit
the data.
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a wide
range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & modifying the resulting records.
All of these different executables are able to use a JDBC driver to access a database,
and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers −
JDBC API − This provides the application-to-JDBC Manager connection.
JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager
with respect to the JDBC drivers and the Java application –
Common JDBC Components
Database connectivity
To connect Java application with the MySQL database, we need to follow 5 following
steps.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP
address, 3306 is the port number and sonoo is the database name. We may use
any database, in such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to
create database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Write a servlet program to create and insert records for employee details using JDBC
EmployeeData.java
-----------------
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//displaying records
Response.setContentType(“text/html”);
out.println(“<html>”);
out.println(“<body>”);
out.println(“<h1>Employee Details <h1>”);
while(rs.next())
{
out.print(rs.getInt(1) + “ “ + rs.getString(2) + “ “ + rs.getString(3));
}
out.print(“</body></html>);
}
catch(SQLException e) { }
rs.close();
stmt.close();
con.close();
out.close();
}
}
OUTPUT
Employee Details
100, 'Zara', 'Ali'