Chapter 8 Servlet-1
Chapter 8 Servlet-1
Introduction to Servlets
What are Servlets?
Java Servlets are programs that run on a Web or Application server and act as a middle layer between
requests coming from a Web browser or other HTTP client and databases or applications on the
HTTP server.
Using Servlets, you can collect input from users through web page forms, present records to a database
or another source, and create web pages dynamically.
Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.
Servlets Tasks:
Servlets perform the following major tasks:
Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an Applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database,
invoking a Web service, or computing the response directly.
1
Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in
a variety of formats, including text (HTML or XML), GIF images, Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.
Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet
specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard
part of the Java's enterprise edition, an expanded version of the Java class library that supports large-
scale development projects.
These classes implement the Java Servlet and JSP specifications. Java servlets have been created and
compiled just like any other Java class. After you install the servlet packages and add them to your
computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current
compiler.
2
The init( ) method :
The init method is designed to be called only once. It is called when the servlet is first created, and not
called again for each user request. So, it is used for one-time initializations, just as with the init method
of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you
can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request
resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply
creates or loads some data that will be used throughout the life of the servlet.
Each time the server receives a request for a servlet, the server spawns/generates 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.
3
The service ( ) method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service ( ) method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods within each service request. Here is the
signature of these two methods.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy
method definition looks like this:
4
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service( ) method.
Then the servlet container handles multiple requests by spawning multiple threads, each thread
executing the service( ) method of a single instance of the servlet.
Servlets - Examples
Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet
interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet,
an abstract class that implements the Servlet interface and is specially designed to handle HTTP
requests.
5
Sample Code for Hello World:
Following is the sample source code structure of a servlet example to write Hello World:
out.println("<a href=\"http://www.google.co.za\">google</a>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
} }
6
Servlets Form Data/query data
Before looking into how a servlet can read data submitted via a form, it is necessary to understand how
data from an HTML form is passed to the web server by the browser.
There are two common ways of passing data from the web browser to the web server. They are called
POST and GET methods. Both of these methods pass the data in a 'key=value' format. The key for each
data field is specified as part of the tag describing the relevant field.
GET method:
The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character as follows:
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web server and it
produces a long string that appears in your browser's Location: box. Never use the GET method if you
have password or other sensitive information to pass to the server. The GET method has size limitation:
only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using doGet()
method.
POST method:
A generally more reliable method of passing information to a backend program is the POST method.
This packages the information in exactly the same way as GET methods, but instead of sending it as a
text string after a ? in the URL it sends it as a separate message. This message comes to the backend
program in the form of the standard input which you can parse and use for your processing. Servlet
handles this type of requests using doPost() method.
7
Reading Form Data using Servlet:
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.
out.println( "<html>");
out.println( "<head><title> Using GET Method to Read Form Data </title></head>");
out.println( "<body bgcolor=pink");
out.println( "<h1 align=center> Using GET Method to Read Form Data </h1>");
out.println( "<ul>");
out.print( " <li><b>First Name</b>: ");
out.println( request.getParameter("first_name"));
out.print( " <li><b>Last Name</b>: ");
out.println( request.getParameter("last_name"));
8
out.println( "</ul>");
out.println( "</body></html>");
} finally {
out.close();
}
}
After running, try to enter First Name and Last Name and then click submit button to see the result on
your local machine where tomcat is running. Based on the input provided, it will generate similar result
as shown below.
If you click submit button you will get the query data at the URL address as follows
http://localhost:8085/Servletexamples12/Formdatausinggetmethod?first_name=Selam&last_name=Taye
If everything goes fine, above compilation would produce Formdatausinggetmethod.class file. Next you
would have to copy this class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes
9
and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name> Formdatausinggetmethod </servlet-name>
<servlet-class> Formdatausinggetmethod </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> Formdatausinggetmethod </servlet-name>
<url-pattern>/ Formdatausinggetmethod </url-pattern>
</servlet-mapping>
10
// TODO output your page here
out.println( "<html>");
out.println("<head><title> Using POST Method to Read Form Data </title></head>");
out.println( "<body bgcolor=pink");
Based on the input provided, it would generate similar result as mentioned in the above examples.
11
Passing Checkbox Data to Servlet Program
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<html>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics” /> Physics
<input type="checkbox" name="chemistry" checked="checked" />
Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
12
Below is CheckBox.java servlet program to handle input given by web browser for checkbox button.
out.println(" </body>");
out.println(" </html>");
} finally {
out.close();
}
}
13
Reading All Form Parameters:
Following is the generic example which uses getParameterValues() method of HttpServletRequest to
read all the available form parameters. This method returns an Enumeration that contains the parameter
names in an unspecified order.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
14
for(int i=0; i<courses.length; i++){
out.println("<li>"+(courses[i]));
}
out.println("</ul>");
}
else
out.println("<p><font color=red>not selected</font></p>");
out.println("</body></html>");
} finally { out.close(); }
}
}
Let we have a database called stud and table dept1 (with fields did and dname)
In this program we are going to fetch the data from the database table to our java servlet pages.
To accomplish our goal we first have to make a class named as dbconnection which must extends the
abstract HttpServlet class, the name of the class should be such that the other person can understand
what this program is going to perform. The logic of the program will be written inside the
processRequest() method which takes two arguments, first is HttpServletRequest interface and the
second one is the HttpServletResponse interface and this method can throw ServletException.
Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the
database only and only if there is a connectivity between our database and the java program. Now use
the static method getConnection() of the DriverManager class. This method takes three arguments and
returns the Connection object. SQL statements are executed and results are returned within the context
of a connection. Now your connection has been established. Now use the method createStatement() of
the Connection object which will return the Statement object. This object is used for executing a static
SQL statement and obtaining the results produced by it. As we need to retrieve the data from the table so
we need to write a query to select all the records from the table. This query will be passed in the
executeQuery() method of Statement object, which returns the ResultSet object. Now the data will be
retrieved by using the getString() method of the ResultSet object.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class dbconnection extends HttpServlet {
Connection con;Statement stmt; ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
15
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stud", "stud");
stmt=con.createStatement();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet dbconnection</title>");
out.println("</head>");
out.println("<body>");
out.println("<table border= 2> ");
out.println("<tr> ");
out.println("<td> did </td> <td> dname </td> ");
out.println("</tr> ");
out.println("<br>");
while(rs.next()){
out.println("<tr> ");
out.println("<td>"+rs.getString(1) + "</td> <td>" +rs.getString(2)+"</td>" );
out.println("<br>");
}
}
catch(Exception e){
System.out.println(e);
}
16
Inserting data from the HTML page to the database
Let we have a database called stud and table dept1 (with fields did and dname)
In this program we are going to make servlet program in which we are going to insert the values in the
database table from the html form.
To make our program working we need to make one html form in which we will have two fields, one is
for the department name and the other one is for entering the department id. And we will have the
submit button, clicking on which the values will be passed to the the database dserver.
The values which we have entered in the Html form will be retrieved by the server side program which
we are going to write. To accomplish our goal we first have to make a class named as
Servletinsertingdatatodb which must extends the abstract HttpServlet class, the name of the class
should be such that the other person can understand what this program is going to perform. The logic of
the program will be written inside the processRequest() method which takes two arguments, first is
HttpServletRequest interface and the second one is the HttpServletResponse interface and this method
can throw ServletException.
We can insert the data in the database only and only if there is a connectivity between our database and
the java program. To establish the connection between our database and the java program the static
method getConnection() of the DriverManager class takes three arguments and returns the Connection
object. SQL statements are executed and results are returned within the context of a connection. Now
your connection has been established. Now use the method prepareStatement() of the Connection
object which will return the PreparedStatement object to submit query to database. The values which we
have got from the html will be set in the database by using the setString() method of the
PreparedStatement object.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
17
throws ServletException, IOException {
response.setContentType("text/html");
out.println(" <html>");
out.println(" <head>");
out.println("<body>");
out.println("</form>");
stmt=con.createStatement();
String id = request.getParameter("did");
pst.setString(1,id);
pst.setString(2,name);
int i = pst.executeUpdate();
if(i!=0){
18
out.println("<br>Record has been inserted");
} else
out.println("</body>");
out.println("</html>");
out.println(e); }
//Home .java
try { out.println("<html>");
out.println("<head>");
out.println("<title>Well Come To DMU Student Registration</title>");
out.println("</head>");
out.println("<body bgcolor=#66CCFF>");
out.println("<center><table>");
out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student
Registration System</h1></th></tr>");
out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home
style=color:white;font-size:20;background-color:#cc6600></a></td>");
out.println("</tr>");
out.println("</table></center>");
out.println("</br></br></br></br></br></br></br>");
out.println("<div style=height:100;width:200;margin-top:8;margin-right:1000");
19
out.println("<tr><td><form method=post action=Validateuser>"
+ "<h1>Login</h1>"
out.println("</div>");
out.println("</body>");
out.println("</html>");
} finally { out.close(); }
//Validateuser.java
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
20
String name = request.getParameter("username");
rd.include(request, response);
rd.forward(request, response);
} else{
rd=request.getRequestDispatcher("/Home");
rd.include(request, response);
} }
//DataAccesspagehome
response.setContentType("text/html;charset=UTF-8");
try { out.println("<html>");
out.println("<head>");
out.println("<title>Well Come To DMU Student Registration</title>");
out.println("</head>");
out.println("<body bgcolor=#66CCFF>");
out.println("<center><table>");
out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student
Registration System</h1></th></tr>");
21
out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home
style=color:white;font-size:20;background-color:#cc6600></a></td>");
out.println("</tr>");
out.println("</table></center>");
out.println("</br></br></br></br></br></br></br>");
out.println("</div>");
out.println("<div style=height:100;width:200;margin-top:-200;margin-left:1100");
out.println("</div>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
} }
22
//StudentManagement.java
response.setContentType("text/html;charset=UTF-8");
try {
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body bgcolor=#66CCFF>");
out.println("<center><table>");
23
out.println("<td><a href=DataAccesshomepage style=color:white;font-size:26><input type=submit
value='Data access home' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("</tr>");
out.println("</table></center>");
out.println("</br></br></br></br></br></br></br>");
out.println("</div>");
out.println("<div style=height:100;width:200;margin-top:-200;margin-left:1100");
out.println("</div>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
//StudentManagement.java
response.setContentType("text/html;charset=UTF-8");
24
out.println("<html>");
out.println("<head>");
out.println("<title>Well Come To DMU Student Registration</title>");
out.println("</head>");
out.println("<body bgcolor=#66CCFF>");
out.println("<center><table>");
out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student
Registration System</h1></th></tr>");
out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home
style=color:white;font-size:20;background-color:#cc6600></a></td>");
out.println("</tr>");
out.println("</table></center>");
out.println("</br></br></br></br></br></br></br>");
out.println("</div>");
out.println("<div style=height:100;width:200;margin-top:-200;margin-left:1100");
out.println(" <a href=Logout ><input type=submit value='Logout' ></a>");
out.println("</div>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
} }
25
//AddNewStudent.java ,let we have studentdb database and student table(sis,sname,dname)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
26
out.println("<tr><th colspan=5><h1 style=color:#cc6600>Debre Markos University<br>Online student
Registration System</h1></th></tr>");
out.println("<tr><td><a href=Home style=color:white;font-size:26><input type=submit value=Home
style=color:white;font-size:20;background-color:#cc6600></a></td>");
out.println("<td><a href=DataAccesshomepage style=color:white;font-size:26><input type=submit
value='Data access home' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("<td><a href=Addnewstudent style=color:white;font-size:26><input type=submit value='Add
new student' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("<td><a href=Updatestudentprofile style=color:white;font-size:26><input type=submit
value='Update student Profile' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("<td><a href=DeleteStudent style=color:white;font-size:26><input type=submit value='Delete
student Profile' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("<td><a href=Searchstudent style=color:white;font-size:26><input type=submit value='Search
student' style=color:white;font-size:20;background-color:#cc6600></a> </td>");
out.println("</tr>");
out.println("</table></center>");
out.println("</br></br></br></br></br></br></br>");
out.println("</div>");
out.println("<div style=height:100;width:200;margin-top:-200;margin-left:1100");
out.println(" <a href=Home ><input type=submit value='Logout' ></a>");
out.println("</div>");
out.println("<center>");
out.println("<table>"); out.println("<tr><th colspan=2>Student Registration Form</th></tr>");
out.println("<tr><td><form method=post action=AddNewStudent>");
out.println("</form>");
out.println("</center>");
{ DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stududentdb",
"stududentdb");
stmt=con.createStatement();
27
String id = request.getParameter("sid");
ps.setString(1,id);
ps.setString(2,name);
ps.setString(3,dept);
int i = ps.executeUpdate();
if(i!=0){
} else
out.println("</body>");
out.println("</html>");
} finally {
out.close();
} }
28