Java-Servlets
Java-Servlets
JAVA SERVLETS
INTRODUCTION
Java servlets are programs that run on web server. Java applets are programs that are
embedded into the web pages. When browser loads the web page the applets byte code is
downloaded and executed by Java Virtual Machine. In order to execute an applet you
should have a java enabled web browser. While the servlet code is executed at the server
side the hence java compatibility web browser problem is solved by servlets.
SERVLETS
Servlets are java programs that run on web or application servers, servlets are also called
server side programs i.e the code of the program executes at server side, acting as a
middle layer between request coming from Web browsers or other HTTP clients and
databases or applications on the HTTP server. A servlet container uses a Java Virtual
Machine to run servlet code as requested by a web server. A servlet dynamically loaded
module that services requests from Web server. It runs entirely inside the Java Virtual
Machine.
Client Request
Servlet
Response
Servlets are not tied to specific client server protocol but they are most commonly used
with HTTP. Since servlets run inside the web server they do not display a graphical user
interface.
Servlets are used for developing on-line shopping store web page. When servlet
receives the posted data, it will process it and fullfils the client request .
Servelets are usefuls for developing distributed applications.
ADVANTAGES OF SERVLETS
EFFICIENT
A Servlet code is loaded into memory once. After the servlet is loaded, handling new
request is only matter of calling a service method. In a CGI, if there are N requests to the
same CGI program, the code for the CGI program is loaded into memory N times. While
in case of servlets there are N thread, but only a single copy the servlet would be loaded.
Loading a new executable for every request is expensive technique. The java servlet
provides an is efficient technique to it.
PORTABLE
Servlets are java program, hence the servlet code is independent of machine architecture.
They can be moved to any machine or any operating system.
ROBUST
Because servlets are developed with access to entire JDK, servlet support several
capabilities they are very powerful. It has garbage collector to prevent problems with
memory leaks. Servlets can also maintain information from request to request,
simplifying techniques like session tracking and caching of previous computations.
EXTENSIBLE
Servlets are developed using java they can be extended into new objects that are better
than the previous one. You can implement a base servlet that builds and initializes the
search tool and then extend it to display transaction – specific response.
SECURE
Since servlets run on server side they are secure. They inherits the security provided by
the Web Server.
The CGI programs are often executed by general – purpose operating shells. So, the CGI
programmer must be careful to filterout characters such as backquotes and semicolons
that are treated specially by the shell.
Product Vendor
Apache Web Server Apache
Java Web Server Sun Microsystem
Enterprise Server Netscape
Internet Connection Server IBM
Sun Web Server Sun Microsystem
Domino Go Web Server Lotus
JRun MacroMedia
SERVLET ARCHITECTURE
Servlet
javax.servlet javax.servlet.http
ServletRequest HttpServletRequest
ServletResponse HttpServletResponse
ServletConfig HttpSession
ServletContext HttpSessionContext
GenericServlet
GenericServlet is the core class in javax.servlet package. Generic servlet may be used to
create servlets by extending it. GenericServlet provides methods init() and destroy() and
the methods in ServletConfig interface.
HttpServlet
HttpServlet inherits basic Servlet functionality by extending GenericServlet.HttpServlet
must override methods such as service(), doGet(), doPost(). Its service method receive
two parameters they are HttpServletRequest and HttpServletResponse. The doGet()
method is called in response to an HTTP GET request, used to send client data. The
doPost() is called in response to an HTTP POST request from HTML form.
}
public void service()
{
/* used to fulfill client request */
import java.io.*;
import javax.servlet.*;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B> Hello World <B>");
pw.close();
}
}
browser, and println method is used to print content to the browser with the help of
handle created with PrintWriter class.
After creating the above program save program with name HelloWorld.java and
move to the MS-DOS prompt.
Move to the foldder where you have java servlet program
At the MS-DOS prompt type the path and classpath of java servlet
path = G:\Program Files\Java\jdk1.6.0_01\bin
set classpath=G:\JSDK2.0\lib\jsdk.jar
compile java program as : javac HelloWorld.java
copy HelloWorld.class file and paste it to the example folder of JSDK2.0
open servlet.properties files in notepad and type mapping to the servlet as:
servlet.code.Hello=HelloWorld
move to the bin folder of JSDK2.0 start servletrunner program by double clicking
it.
Start the web browser by double clicking it, and at its address bar type :
http://localhost:8080/servlet/HelloWorld
In the above URL the 8080 specifies the port number where web service runs.
Compiling and running the same program with the help of Apache Tomcat Web Server
4.x type the above java program with a modification to it. Executing it with the help of
invoker servlet.
import java.io.*;
import javax.servlet.*;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<title> Hello World 1</title>");
pw.println("<B> Hello World, Executed with the Apache Tomcat Web
Server<B>");
pw.close();
}
}
Move to the MS-DOS prompt and set classpath and path of java compiler.
path = \Install_dir\Java\jdk1.6.0_01\bin
set classpath=C:\Program Files\Apache Group\Tomcat 4.1\common\lib\servlet.jar
compile java program as javac HelloWorld1.java
copy class file to the classes folder under web-inf folder
\install_dir\Apache Group\Tomcat 4.1\webapps\ROOT\WEB-INF\classes
open web.xml file from install_dir\conf\web.xml
To enable the invoker servlet remove comments from web.xml file The mapping
for the invoker servlet. Uncomment it and save it
Start tomcat web server
Open web browser and type the url : http://localhost:8080/servlet/HelloWorld1
The above code is run with the help of tomcat web server. The <title> </title> tag is
used to specify title at the top of web browser. The <B> </B> tag is used to print the text
in bold size.
5. Create web.xml file under the WEB-INF folder and add following mapping to it.
web.xml
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
The above created servlet can be invoked more than one url. This can be accomplished by
servlet-mapping tag in web.xml file. After creating more than one mapping the contents
of the file web.xml will be as follows:
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
</web-app>
init()
The init() method is where the servlets life begins. It is called by the server immediately
after the servlet is instantiated. The database connection, opening a file, or a network
connection may be established through it. The init method is not called again for each
request. The servlet is normally created when a user first invokes a URL corresponding to
servlet.
The following are the task performed while implementing init() mehtod
service()
The service method handles all requests sent by a client. Each time the server receive a
request for a servlet, the server spawns a new thread and calls service method. The
service method checks the request type GET, POST, PUT, DELETE etc. For, every
request to the servlet, its service method is called. Two objects ServletRequest and
ServletResponse are passed as argument to it.
destroy()
This method signifies the end of a servlet life. The resources that are previously allocated
are destroyed. The method is invoked by server administrator or programmatically by
servlet itself.
Load
Servlet Code
Server
Request
Client
Request
Client
Server
Response
Unload
Servlet Code
Server
Reading parameter requires a html form with some text fields which are used to input
values. The HTML form reads the values and send it to the servlet by using the action
URL. The input values are read by the java servlet program and send back to browser for
the display.
Two.html
<html>
<head>
<title> Reading Parameters </title>
<body bgcolor="#FDF5E6">
<h1 align ="center"> Reading Parameters </h1>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println(req.getParameter("param1"));
pw.println(req.getParameter("param2"));
}
}
The getParameter method is used to read the HTML form parameters and displayed to the
web browser with the help of PrintWriter stream. The fig 20.7 shows the result after
reading the input parameter.
Res.getWriter() returns a PrintWriter object that can send character text to the client.
threepost.html
<html>
<head>
ThreePost.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
COOKIES
Cookies are small text files that are used to maintain the different session when a user
online for shopping different items from same web store. Cookies are send by the web
server to the client browser. The browser later return unchanged when visit the same web
page again. Once the web server receives cookie information the servlet program
processes the cookie information and recognizes it as a new user or already visited user.
Cookies are therefore, a accepted method used by the web server for session tracking.
Since the enable web servers to store and retrieve data from the client side. Cookies let a
user to log in automatically. Cookies can be used to remember user preferennces.
CONTENTS OF A COOKIE
A cookie contains the following contents
PERMANENT COOKIES
Permanent cookies are stored in client machine, they are not deleted when browsing
session is closed. Permanent cookies can be used to identifify individual users. The
persist after the user restart the computer.
SESSION COOKIE
Session cookies are also called transient cookies. These cookies exists till the browsing
session continues and automatically gets deleted as soon as the user closes the web
browser. These cookies usually store a session ID that is not permanently bound to the
user, allowing the user to move from page to page without login each time.
CREATING COOKIE
Cookies are created by the web server and stored in client computer. A Cookie can be
created with the help of Cookie class which is then placed in HTTP response header with
the help of method addCookie( cookie_name)
Cookie c = new Cookie(“user”, “1234”);
Syntax: public Cookie (String <name>, String <value>);
Creates a new cookie with name and value. The following are some methods used with
Cookie class.
Following program creates a cookie and display its name and maximum life of the
cookie.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Cookie c = new Cookie("DemoCookie","123456");
/* Creates the cookie */
c.setMaxAge(7*24*60*60);
/* set life of cookie to one week */
response.addCookie(c);
/* add cookie to the HTTP response header */
pw.println("<HTML><HEAD><TITLE>");
pw.println("Demo Cookie");
pw.println("</TITLE></HEAD><BODY>");
pw.println("<H3>");
pw.println("The Cookie name is : "+ c.getName());
pw.println("<BR>");
pw.println("The Value of Cookie : " + c.getValue());
pw.println("<BR>");
pw.println("Life of Cookie is : " + c.getMaxAge() + " seconds");
pw.println("<BR>");
pw.println("</H3>");
pw.println("</BODY></HTML>");
pw.close();
SEARCHING COOKIES
Cookies can be used to check whether the user is the first time visitor or he / she visiting
again. To search a specific cookie, all the available cookies need to be checked to find the
particular cookie using the getCookies() method of HttpServletRequest.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String title;
if (find)
{
Cookie ck = new Cookie("DemoCookie", "123456");
ck.setMaxAge(60*60*24*7);
response.addCookie(ck);
title = "The New User ";
}
else
{
title = "The Old User ";
}
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<h1>"+ title + "</h1>");
pw.println("</html>");
}
}
The program 20.5 search for the DemoCookie in the computer hard disk if it does not
find one then it creates a new cookie and displays the message The New User otherwise
if it finds the DemoCookie then it display the message The Old User.
DELETING COOKIE
To delete cookies from local disk start Microsoft Internet Explorer select internet option
from Tools menu and press Delete Cookies button of General Tab. A cookie can also be
deleted with following step.
<html>
<head>
<title> Simple Query Form </title>
</head>
<body>
<h2> Query Input:</h2>
<form action ="http://localhost:8080/servlet/jdbcservpost"
method = post>
<table>
<td> <textarea rows="5" cols ="35" name = "query"></textarea>
<tr><td colspan="2" align = "center"><input type = "submit">
</table>
</form>
</body>
</html>
Program 20.6 The HTML cocde of the above SQL Query form
On clicking the submit button the java servlet produces the following output
jdbcservpost.java
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:TestDb";
try
{
Class.forName(driver);
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
String query = request.getParameter("query");
ResultSet result = stmt.executeQuery(query);
ResultSetMetaData resultSetMetaData= result.getMetaData();
PrintWriter pw = response.getWriter();
int columnCount = resultSetMetaData.getColumnCount();
System.out.println(columnCount);
pw.println("<TABLE BORDER=15>");
pw.print("<TR>");
for(int i=1; i<=columnCount; i++)
{
pw.print("<TH>"+resultSetMetaData.getColumnName(i));
}
pw.println();
while(result.next())
{
pw.println("<TR>");
for(int i=1; i<=columnCount;i++)
{
pw.print("<TD>"+result.getString(i));
}
}
pw.println("</table>");
con.close();
}
catch(ClassNotFoundException e)
{
}
catch(SQLException e1)
{
}
}
}
Explanation
The above java overrides doPost method the Jdbc – Odbc dirver is defined by the string
variable.
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
The data source is define as
String url = "jdbc:odbc:TestDb";
The Jdbc – Odbc driver is loaded by the statement
Class.forName(driver);
The ResultSetMetaData provides some extra information about the ResultSet object.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ApplesWord extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("application/vnd.ms-excel");
PrintWriter out = response.getWriter();
out.println("This header indicates the number of bytes ");
out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)");
out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");
}
}
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
color.html
<html>
<body>
<center>
<form name="Form1"
action = "http://localhost:8080/servlet/ColorGetServlet">
<B>: Color: </B>
<servlet>
<servlet-name>ColorGetServlet</servlet-name>
<servlet-class>ColorGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ColorGetServlet</servlet-name>
<url-pattern>/servlet/ColorGetServlet</url-pattern>
</servlet-mapping>
SERVLET DEBUGGING
Servlet run at the server side hence debugging a servlet is difficult task. The Servlet API
gives you two ways of to deal with errors: you can manually send an error message back
to the client or you can throw a ServletException.
1. Use print statements. Insert a print statement, restart the server, and see if the print
statement is displayed in the standard output window.
2. Use the log file. The log contains the error messages. The HttpServlet class has a
method log that lets you write information into a logging file on the server. The
log file is an option even when running on the remote server in such situation
print statements are rarely useful.
3. Write separate classes. The methods that are frequently used put them in a
separate class. Avoid repetition of a method.
4. Look at the HTML source. If the result you see in the browser look odd, then look
att the the HTML code for possible error.
5. Look at the request data separately. Servlets read data from HTTP request,
construct a response, and send send it back to the client. If something in the
process goes worong, you want to discover if the cause is that the client is sending
the wrong data or that the servlet is processing it in incorrectly. The EchoServer
class let you submit HTML forms and get a result that shows you exactly how the
data arrived at the server.
6. Stop and restart the server. Servers are supposed to keep servlets in memory
between requests, not reload them each time they are executed. Howerver, most
server support a development mode in which servlets are supposed to be
automatically reloaded whenever their associated class file changes.
Imagine if a servlet maintains a bank balance using an integer in memory. If two servlets
try to access the balance at the same time we might get this sequence of events.
HTTP
HTTP stands for Hypertext Transfer Protocol. HTTP is used in internet for accessing the
world wide web. HTTP is used to access image, text or video over the internet A browser
is works as an HTTP client because it sends requests to an HTTP server which is called
Web server. The Web Server then sends responses back to the client. The standard and
default port for HTTP servers to listen on is 80. HTTP uses client server technology.
HTTP is connectionless
HTTP disconnects from the server after it request and wait for the response.
HTTP is Stateless
The server and client forget each other after each request. The does not know
whether the request is coming from the same client or from the different client.
HTTP is used to send any type of data it can be image file, text file, HTML file,
video file or any other type file. The content type is handled by the MIME type.
The most methods of HTTP are GET and POST. The GET method reads information
identified by request URI. The entire form submission can be encapsulated in one URL.
While in POST method there's a block of data sent with the request, in the message body.
The whole file can sent with the help of POST method. There are usually extra headers to
describe this message body, like Content-Type: and Content-Length
HTTP CODES
The response header field must be included in response messages. . The field value
consists of at least one challenge that indicates the authentication scheme(s) and
parameters applicable to the Request-URI.
1xx: Information
Message: Description:
100 Continue Only a part of the request has been received by the
server, but as long as it has not been rejected, the
client should continue with the request
101 Switching Protocols The server switches protocol
2xx: Successful
Message: Description:
200 OK The request is OK
201 Created The request is complete, and a new resource is
created
202 Accepted The request is accepted for processing, but the
processing is not complete
203 Non-authoritative Information
204 No Content
205 Reset Content
206 Partial Content
3xx: Redirection
Message: Description:
300 Multiple Choices A link list. The user can select a link and go to that
a) getCookies
public Cookie[] getCookies();
It returns an array containing all the cookies present in this request. Cookies can be used
to uniquely identify clients to servlet. If there are no cookies in the request, then an empty
array is returned.
b) getQueryString
a) addCookie
public void addCookie(Cookie cookie);
It is used to add the specified cookie to the header of response. This method can be called
multiple times to set more than one cookie. This method must be called before the
response is committed so that the appropriate headers can be set. The cookies maximum
age and whether the client allows Cookies to be saved determine whether or not Cookies
will be stored on the client.
b) sendError
public void sendError(int statusCode) throws IOException;
public void sendError(int statusCode, String message) throws IOException;
It sends an error response to the client using the specified status code. If a message is
provided to this method, it is emitted as the response body, otherwise the server should
return a standard message body for the error code given. This is a convenience method
that immediately commits the response. No further output should be made by the servlet
after calling this method.
c) getWriter
public Printwriter getWriter()
It obtains a character-based output stream that enables text data to be sent to the client.
d) getOutputStream()
REFERENCES
1. Core Servlets and JavaServer Pages, Second Edition, Marty Hall, Larry Brown,
2. The Java Complete Reference 5th Edition, Herbet Schildt, Tata McGraw Hill
3. Java Server Programming for Professionals, 2nd Edition, Ivan Bayross, Sharanam