Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Servlet Read text file and Return contents to Client Example :::

Sometimes, the client may ask the Servlet to send the file contents of a
file existing on the server. It is not file download. Here, the Servlet
reads manually line-by-line and send each line separately to client.

Client HTML Program: TextFileReadAndSend.html

<BODY>
<H2> Getting File contents from the Server </H2>
<FORM METHOD="get" ACTION="http://localhost:8888/india/TFRAS">

Enter File Name <INPUT TYPE="text" NAME="filename"><BR>


<INPUT TYPE="submit" VALUE="Send Me">
<INPUT TYPE="reset" VALUE="Clear">

</FORM>
</BODY>
web.xml entry for Servlet TextFileReadAndSend.java

<servlet>
<servlet-name>snrao1</servlet-name>
<servlet-class>TextFileReadAndSend</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>snrao1</servlet-name>
<url-pattern>/TFRAS</url-pattern>
</servlet-mapping>
Servlet Program: TextFileReadAndSend.java

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;

public class TextFileReadAndSend extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();

String name = req.getParameter("filename");

BufferedReader br = new BufferedReader(new FileReader("c:/"+name));

String str;
while( (str = br.readLine()) != null )
{
pw.println(str + "<BR>");
}

br.close();
pw.close();
}
}
BufferedReader br = new BufferedReader(new FileReader("c:/"+name));
The file asked by the user is assumed to exist in C drive. This also can
be taken from client (security may prevent this). Instead, the classpath
of the file can be placed in <context-param> and read into the Servlet.

For performance reasons, BufferedReader readLine() method is used instead


of FileReader read() method.

Reading and sending HTML file contents is very different from text file
and is explained in Read HTML File Contents Example.

Client HTML file with user entry of File name

ima

Output screen with File contents sent by Servlet

ima1

Servlet Read HTML File Contents Example:::

Earlier we did a program where client requested for a text file; but the
case now is with HTML file.

If the user sends a request for HTML file, when it comes to the browser,
it is interpreted and output of the HTML file is obtained and not the
HTML contents as it is. To overcome this, it must be read angle brackets
of the HTML file separately.

In case the file user wanted is a HTML file, the servlet file should be
changed slightly as follows where HTML angle brackets should be read
differently.

Client HTMl File: HTMLFileSend.html

<BODY>
<H2> Getting File contents from the Server </H2>
<FORM METHOD="get" ACTION="http://localhost:8888/india/HFS">

Enter HTML File Name <INPUT TYPE="text" NAME="filename"><BR>


<INPUT TYPE="submit" VALUE="Send Me">
<INPUT TYPE="reset" VALUE="Clear">

</FORM>
</BODY>
web.xml entry for Servlet

<servlet>
<servlet-name>snrao1</servlet-name>
<servlet-class>HTMLFileSend</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>snrao1</servlet-name>
<url-pattern>/HFS</url-pattern>
</servlet-mapping>
Servlet File: HTMLFileSend.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HTMLFileSend extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();

String name = req.getParameter("filename");

FileReader fr = new FileReader("C:/" + name);

int k;
char ch;

while( (k = fr.read()) != -1 )
{
ch = (char) k;
if(k == 13) // 13 is ASCII value of new line character
pw.print("<BR>");
else if(ch == '<')
pw.print("&lt;");
else if(ch == '>')
pw.print("&gt;");
else
pw.print(ch);
}

fr.close();
pw.close();
}
}
In the earlier text file reading, We used BufferedReader to read a line
at a time. Now, here FileReader is used to read character by character.

FileReader fr = new FileReader("C:/" + name);

It is assumed that the file wanted by the client is existing in C drive.

if(k == 13)

If the character read from the file is 13, send a <BR> to client browser.
13 is the ASCII value of new line (obtained with enter key).

If the character read is < angle bracket, send lt; prefixed by & and
similarly with > also.

Finally if not all, send the character itself to client (else condition
is executed).

There is another way of reading HTML file contents and sent to client
which is very easier than this and is explained in
response.getOutputStream() Example.

Output screens with client request and server response

ima

ima1

Java Made Clear: What is Status code in HTTP Servlets? :::

1. What is Status code in HTTP?


2. Why status codes?

This gives introduction to status code.

Here, I talk in my own style for a better understanding for a very


beginner. Suppose, I develop a software product like School product and
supplied to a School. Well, the software is working nice to the
satisfaction of the client. One day, a call is received by my supporting
team about malfunction of the product. The support team member asked the
client to read of the error message or explain about the error. The
School Teacher is unable to explain properly (or team member is unable to
extract the information he required) and thereby the support team member,
finally, is unable to rectify the problem. It leads to customer
dissatisfaction.
Then what best I can do as an Architect of the product. For every
possible problem, the client may get with my School product, I give a
number (followed by some extra notes). Now the School Teacher reads the
number to the support team. By listening the number, the team understands
the problem and fix it over phone itself.

This number, I designed, is known as "status code". As the name implies,


it gives the status of the request of the client by the server. Do not
think status code is meant for only errors always. See, it is after all
the status of the request, sometimes even the request honoured by Web
server without any problem and Okayed, it can also be given a status
code. That is, even for accepted or not accepted requests, the requests
processed successfully or not processed, sometimes the client is
forbidden to access the information, all these are given status codes in
HTTP protocol.

3. Who can use these Status codes?


4. Who developed these Status codes?

W3C (World Wide Consortium) developed these status codes along with the
development of HTTP protocol (originally developed by Web’s inventor, Tim
Berners-Lee in 1992 while developing FTP). A list of status codes is
maintained by The Internet Assigned Numbers Authority (IANA). It is
treated as the official registry of HTTP status codes. Because these are
not proprietary, any Web technology using HTTP protocol can make use of
them like ASP, Servlets/JSP, PHP etc.

5. Can you explain one Status code example clearly?


6. What is Status code 404 carries the message to client by Web server?
7. How to fix 404 error message?

404 is a very commonly occurring status code number even to a Programmer


while the software is being integrated. 404 means, what the client
requested is not available with the server (resource not found). That is,
client has requested a Servlet on the server by quoting some alias name
and clicking over Submit button, the server did not find a Servlet
matching to that in the URL.

The possible mistakes, the Programmer can commit are:

Alias name written in the URL (in <form action="xxx"> may not be the same
(for misspelling) as given in web.xml file.
The Servlet may not be placed in the correct directory like "classes"
folder.
The source file of .java extension must have been placed in "classes"
folder instead of its .class file.
If the Programmer can fix anyone of the above mistakes, most probably, he
may come out of the 404 error.

Java Made Clear: Classification of Status Codes in HTTP :::

After knowing clearly in a simple way "what a status code is?" and "why
it is needed?", let us dig further in the subject.

A status code is a numeric value with 3 digits. W3C divided all the
status codes broadly into 5 categories starting with digit 1 (of type
1xx), with digit 2 (of type 2xx), with digit 3 (of type 3xx), with digit
4 (of type 4xx) and with digit 5 (of type 5xx).
I. Status codes with Prefix 1 (of type 1xx) : Meant for just Information

This is not generally used but only for in experimental, testing,


integration, deployment states. Here, the Testing engineer can send a
message of information that the Servlet may be/may not be working with
some extra information for team members.

Some examples:

"100" means "Continue" : Client can continue with his request. It is a


message to client that the initial part of the request is honoured and
second part of the request may be sent.

"101" means "Switching Protocols" : Information to the client that on the


protocol the request is sent may be outdated version, the server is
shifting the protocol a newer version for more advantages.

II. Status codes with Prefix 2 (of type 2xx) : Means that Web Server
accepted the request successfully

It is not much used (because meant for positive response) and sometimes
not visible to client.

Some examples:

"200" means "OK" : Request is successfully honoured.

"202" means "Accepted" : The request is accepted for processing but the
processing has not been completed and may be disallowed.

III. Status codes with Prefix 3 (of type 3xx) : Meant for Redirection
(Used when Server redirects the request)

The client requested the Web sever with some URL, but the server may
shift to another URL to fulfil the request.

Some examples:

"301" means "Moved Permanently" : The client requested resource is


permanently shifted to another new URL and future requests may be
contacted on this new URL. The new URL is passed to client with Location
header. The browser, if supports, can keep the new URL in cache.

"302" means "Found" or Moved temporarily : The requested resource is


temporarily moved to some other location.

IV. Status codes with Prefix 4 (of type 4xx) : Client does some errors in
requesting

Some examples:

"400" means "Bad Request" : Request is not honoured by the server due to
malformed URL syntax. The client can repeat the request with some
modifications.

"401" means "Unauthorized" : Client is unauthorized for the request.


"404" means "Not Found" : Server is unable to find the resource to
execute to fulfil the client request as client’s request does not match
any suitable resource like Servlet/JSP.

V. Status codes with Prefix 5 (of type 5xx) : Resource is available on


the server and server is able to locate it but still unable to exeucte
it.

"500" means "Internal Server Error" : The server encountered a situation


which prevented it from execution. For example, the client sends value
ten in string form instead of numeric value 10. The server is unable to
execute ten.

"505" means "HTTP Version Not Supported" : The HTTP version, client used
to send the request, is not supported by the server.

Java Made Clear: List of Status codes – Commonly occurring ::

Before going through, it is advised to read What is Status code in HTTP


Servlets? and Classification of Status Codes in HTTP.

Following table gives you the list of status codes. Only commonly
occurring are given.

503 Service Unavailable

Status code Value Description


100 Continue
101 Switching Protocols
102 Processing
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
208 Already Reported
301 Moved Permanently
302 Found
304 Not Modified
305 Use Proxy
307 Temporary Redirect
308 Permanent Redirect
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
410 Gone
412 Precondition Failed
413 Payload Too Large
414 URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
422 Unprocessable Entity
423 Locked
424 Failed Dependency
425 Unassigned
426 Upgrade Required
428 Precondition Required
429 Too Many Requests
430 Unassigned
431 Request Header Fields Too Large
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
504 Gateway Timeout
505 HTTP Version Not Supported
511 Network Authentication Required

What is 404 Not Found Error in Servlets? How to Fix it?


User clicks over a hyperlink, some Servlet is called, executed and the
response is sent to the user. Sometimes, the mouse click on the hyperlink
calls such an attribute of <ACTION> tag which does not exist on the Web
server. That is, the source corresponding to the hyperlink does not exist
on the Server. Then what server should do to reply to the user?

Server delivers a message to the client, "404 Not Found". 404 indicates
status code of the response. It is a very commonly occurring status code.

404 indicates:

The source (which can generate the response like a Servlet) requested by
the client does not exist on the Server; that is, server is unable to
locate the source. Here, client is authorized to access.

Causes of 404 Error and Fixing it?

The hyperlink (URL) may be broken with some extra spaces not required
while it is being typed by the user.
The hyperlink may be a dead hyperlink (which existed earlier but not
now).
The source (URL) must have moved to another server temporarily or
permanently and server is unable to redirect to the new location.
The extension for an HTML file may be .htm or .html. Should be checked
how the server accepts.
For student learning Servlets
Check the spelling of <url-pattern> alias name of Servlet you have typed
in the URL (of <ACTION> attrubute of <FORM> tag).
Check you have placed .java file of .class file of the Servlet in the
Server.
Check where you have placed .class file and it must be classes folder of
Tomcat.
When you correct all, restart the Tomcat and check again.

Servlet WAR File in Tomcat with Creation, Deployment, Execution :::


We have seen earlier what a JAR file is, its options, creation and
advantages in JAR (Java ARchive) Files.

Now let us study what a WAR file is and its creation etc. WAR stands for
Web ARchive. A WAR file is a JAR file, but contains Web components only.
What does it mean? A JAR can contains any files compressed like text
files, doc files, gif files and excel sheets etc. A WAR file is also a
compressed file like JAR but contains only the Web components like
Servlets, JSPs, web.xml, JavaBeans, Struts and HTML pages etc.

The command to create a WAR file is JAR only (executed from command-
prompt) but extension is .war.

Follow the same 7 Steps – Servlets Tomcat Execution, anyhow a few steps
required are added to the existing and reproduced here.

Install Tomcat server of your choice version by downloading from Apache


site. Many versions of Tomcat can be found in the following link.

http://tomcat.apache.org/download-60.cgi
Check with the documentation of what JDK or JRE version is compatible to
the specific Tomcat version. For example I have loaded Tomcat 5.0 and got
compatible JDK 6.0.

While installation, it asks the port number and I have entered 8888
(default is displayed as 8080. I have not preferred 8080 for the reason
on many systems Oracle server will be working on 8080. For this reason
better choose a different port number). Later, give your own password.

Step 1:When installed, Tomcat gives many folders of which a few are given
hereunder used for execution. See the following one.

C:\Program Files\Apache Software Foundation\Tomcat


5.0\common\lib\servlet-api.jar;

Keep the above JAR file in the classpath of Windows Environment


Variables, else the servlet program will not be compiled.

Note: Now, a fresher should be careful here in the following steps. Steps
are very simple but should be followed carefully. Any small mistake
committed, Tomcat simply refuses to execute your Servlet.

Step 2: Creating your own (base)directory structure.

You also get the following folders.

C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps

In the above webapps folder create your own new folder. I created and
named it as "india".

Step 3: Observe the following directory structure.

C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\ROOT\WEB-


INF

Just copy the above WEB-INF folder (ofcourse, along with its
subdirectories) into india folder.

When you did, now you get the following structure. Check it.
C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\india\WEB-
INF

Note 1: Do not confuse now with the WEB-INF folder as WEB-INF exists in
two places – one in ROOT and one in india.

Note 2: Tomcat is case-sensitive. Do not write web-inf instead of WEB-INF


etc.

Remember, now onwards when I talk about WEB-INF folder, I mean the WEB-
INF available in india and not in ROOT. This is very important.

In \webapps\india\WEB-INF folder you get automatically one "classes"


folder and one "web.xml" file.

Now what is to be done?

Step 4: Deployment of Servlet

Write a servlet program, say Validation.java in your current directoty


and compile it as usual with javac command and obtain Validation.class.
Copy the Validation.class file from your current directory to classes
folder available in the following classpath.

C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\india\WEB-


INF\clssses

Copying the .class file of servlet to classes folder is known as


deployment.

Step 5: Giving the alias name to the servlet with Deployment Descriptor.

Open the web.xml file available in the following folder.

C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\india\WEB-


INF

In the web.xml file add the following code just before </web-app> tag.

<servlet>
<servlet-name>abcd</servlet-name>
<servlet-class>Validation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>abcd</servlet-name>
<url-pattern>/roses</url-pattern>
</servlet-mapping>
Now the alias name of Validation servlet is roses. Client should call the
Validation servlet with the name roses. Observe, this roses you used in
HTML file.

The web.xml file is known as deployment descriptor as it describes the


deployment information of a servlet. Learn more at Deployment Descriptor
– web.xml in Servlets.

Creating WAR File


From here starts creating WAR file. Now you are ready with india folder.

Come to DOS prompt as follows where india folder exists.

C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\india>jar


-cvf hyderabad.war .

Note: Do not forget to place dot after hyderabad.war which indicates to


include the files of india and also subdirectories of india.

Now in india folder, a WAR file by name hyderabad.war is created. This


hyderabad.war file contains all the Web components to execute a Servlet.

Deployment of WAR file

Copy this hyderabad.war file to webapps folder. Remember, webapps is


available in the following path.

C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps

Now creation and deployment of WAR file is over. Next step is execution.
Include the WAR file name in the client request as follows.

Earlier remember, in place of hyderabad it is written india.

Following is the modified client HTML file:

<body>

<h2 align="center">Login Validation</h2>

<form method="get" action="http://localhost:8888/hyderabad/roses">

Enter User Name <input type="text" name="t1"> <br>


Enter Password <input type="text" name="t2"> <br>
<input type="submit" value="SEND">
<input type="reset" value="CLEAR">

</form>
</body>
Observe, hyderabad in the action is the WAR file name.

The same Validate servlet of Login Screen Validation is used without any
modification.

Step 6: Run the Tomcat server.

Step 7: Open a browser. Open the UserPass.html file from File Menu of the
browser, enter the user name and password and click Send button. Now you
get VALID or INVALID.

A similar program is available but creating WAR file in Weblogic server


WAR File in Weblogic Creation and Deployment.

Servlet WAR File in Weblogic Creation and Deployment -


With the release of the Java Servlet Specification 2.2, the concept of a
Web application was introduced. According to this specification, a "Web
Application is a collection of servlets, html pages, classes, and other
resources that can be bundled and run on multiple containers from
multiple vendors". That is, a Web application is anything that resides in
the Web layer of an application.

One of the main characteristics of a Web application is its relationship


to the ServletContext. Each Web application has one and only one
ServletContext. This relationship is controlled by the Servlet container
and guarantees that web applications will not clash when storing objects
in the ServletContext.

The following items can exist in a web application:

Servlets
JavaServer Pages
Utility Classes
Static Documents including, XHTML, images, etc.
Client side classes
Meta information that describes the web application
The standard method for packaging Web applications is to use a Web
ARchive file (WAR). You can create a WAR file by using Java’s archiving
tool jar (jar command). The extension must be .war

Creating a WAR file

Suppose your current directory is greetings as: c:\snr\greetings>

greetings is a folder that contains all the files required for a WAR
file. A WAR file should contain all the files to make it to work
independently as one unit.

Place all HTML and JSP files in it (in greeting directory).


Create a WEB-INF directory under greetings directory and place web.xml
file in it. You can copy the weblogic web.xml into it and remove the
unwanted tags and keep only the tags required for your application.
Create classes directory under WEB-INF directory and copy all the
servlet’s .class files, your application needs.
Now create the WAR file as follows:
c:\snr\greetings> jar -cvf wishes.war *

Asterisk, * indicates to include all the files and subdirectories of


greetings folder.

Now by name a file wishes.war file is created.

Copy wishes.war into Weblogic’s (of Weblogic 8.1 version) applications


directory available as follows:
C:\bea\weblogic81\samples\domains\examples\applications

Now run the weblogic server and type from the browser prompt as follows:
http://localhost:7001/wishes/myData

where myData is the url-pattern name of the servlet written in your


web.xml file. Remember this servlet file is in the classes directly of
your Web application. 7001 is the port number on which Weblogic server is
running.

A similar program is available but creating WAR file in Tomcat server WAR
File in Tomcat with Creation, Deployment, Execution.
Java PrintWriter Vs ServletOutputStream:::

We know when the user clicks a submit button or hyper link, a request
goes to a Servlet. The Servlet container loads the Servlet, calls
implicitly the service(HttpServletRequest request, HttpServletResponse
response) method. The parameter objects request and response has a
gigantic responsibilities. The request object is meant to receive the
data from client and response object is meant to send data to client. If
the Programmer can take care of these two objects, the functionality
(purpose) of Servlet is over.

Earlier we have seen the ways of receiving data from client. Now let us
do with response. The response object functionality is to send data to
client of what client is interested. For this, response uses IO Streams.
There are two streams involved depending on the nature of data like text
data or binary data. For text data, the response uses PrintWriter and for
binary data it uses ServletOutputStream. Two methods exist in
ServletResponse interface (inherited by HttpServletResponse) to return
the objects of PrintWriter and ServletOutputStream – getWriter() and
getOuptputStream(). That is, there are two styles exist.

First let us see what Servlet API says about these methods defined in
javax.servlet.ServletResponse interface.

PrintWriter getWriter()throws IOException: Returns a PrintWriter object


that can send character text to the client. The PrintWriter uses the
character encoding returned by getCharacterEncoding(). If the response’s
character encoding has not been specified as described in
getCharacterEncoding (i.e., the method just returns the default value
ISO-8859-1), getWriter updates it to ISO-8859-1.
ServletOutputStream getOutputStream() throws java.io.IOException: Returns
a ServletOutputStream suitable for writing binary data in the response.
The servlet container does not encode the binary data.
PrintWriter object to send textual data to client:

getWriter() method of ServletResponse (inherited by HttpServletResponse)


returns an object of PrintWriter. This is the general way of sending data
to client as most response represents text or HTML only.

PrintWriter out = response.getWriter();


out.println("VALID"); // sending text data
out.println("<B>INVALID</B>"); // sending HTML data
This is shown in the first Servlet program Login Screen Validation.

ServletOutputStream object to send binary data to client:

Sometimes, the Servlet may need to send images and JAR files etc. to the
client. They do not include text data. To send them to client, the
Programmer should convert this data into binary format and to send this
binary data to client, the ServletOutputStream is used.

It is an abstract class (the abstract methods are overridden by Servlet


container). Methods available in this class are overloaded print() and
println().

Following is the hierarchy


java.lang.Object –> java.io.OutputStream –>
javax.servlet.ServletOutputStream

ServletOutputStream object is obtained with getOutputStream() method of


ServletResponse (inherited by HttpServlerResponse) as follows.

ServletOutputStream sos = resonse.getOutputStream();


sos.write(barray);
barray is a byte array into which binary data is read. This style is used
in four examples – Sending Image to Client, Read HTML File Contents,
response.getOutputStream() and Multiple Submit Buttons in a single HTML
Form.

Small Table showing the big difference.

Property PrintWriter ServletOutputStream


class nature Concrete class Abstract class
Method that returns getWriter() getOutputStream()
Nature of data To send character-based information like textual/HTML
data Mostly used to send binary data and less times to send primitive
values and character-based information
Character encoding Does character encoding for ASCII/Unicode
characters (as per the getCharacterEncoding() method) Does not perform
any character conversion as it is meant for binary data (container does
not encode binary data).
Performance Very expensive for character conversion Faster as no character
conversion exists and particularly the entire data is sent as a byte
array at a time
Type of stream Character stream Byte stream
Usage Mostly used Limited usage

Java Made Clear: Difference Servlet, GenericServlet, HttpServlet ::

Servlets are platform-independent server-side components, being written


in Java. First let us see how the three Servlet, GenericServlet,
HttpServlet are related.

See how to write a Servlet.

public class Validation extends HttpServlet

To write a servlet, everyone goes to extend the abstract class


HttpServlet, like Frame is required to extend to create a frame.

Following figure shows the hierarchy to know from where HttpServlet


comes.

image

Observe the hierarchy and understand the relationship between the three
(involved in multilevel inheritance). With the observation, a conclusion
can be arrived, to write a Servlet three ways exist.

a) by implementing Servlet ( it is interface)


b) by extending GenericServlet ( it is abstract class)
c) by extending HttpServlet ( it is abstract class)
The minus point of the first way is, all the 5 abstract methods of the
interface Servlet should be overridden eventhough Programmer is not
interested in all (like the interface WindowListener to close the frame).
A smart approach is inheriting GenericServlet (like using WindowAdapter)
and overriding its only one abstract method service(). It is enough to
the programmer to override only this method. It is a callback method
(called implicitly). Still better way is extending HttpServlet and need
not to override any methods as HttpServlet contains no abstract methods.
Eventhough the HttpServlet does not contain any abstract methods, it is
declared as abstract class by the Designers to not to allow the
Programmer to create an object directly because a Servlet object is
created by the system (here system is Servlet Container).

1. Servlet interface

It is the super interface for the remaining two – GenericServlet and


HttpServlet. It contains 5 abstract methods and all inherited by
GenericServlet and HttpServlet. Programmers implement Servlet interface
who would like to develop their own container.

2. GenericServlet

It is the immediate subclass of Servlet interface. In this class, only


one abstract method service() exist. Other 4 abstract methods of Servlet
interface are given implementation (given body). Anyone who extends this
GenericServlet should override service() method. It was used by the
Programmers when the Web was not standardized to HTTP protocol. It is
protocol independent; it can be used with any protocol, say, SMTP, FTP,
CGI including HTTP etc.

Signature:

public abstract class GenericServlet extends java.lang.Object implements


Servlet, ServletConfig, java.io.Serializable

3. HttpServlet

When HTTP protocol was developed by W3C people to suit more Web
requirements, the Servlet designers introduced HttpServlet to suit more
for HTTP protocol. HttpServlet is protocol dependent and used specific to
HTTP protocol only.

The immediate super class of HttpServlet is GenericServlet. HttpServlet


overrides the service() method of GenericServlet. HttpServlet is abstract
class but without any abstract methods.

With HttpServlet extension, service() method can be replaced by doGet()


or doPost() with the same parameters of service() method.

Signature:

public abstract class HttpServlet extends GenericServlet implements


java.io.Serializable

Being subclass of GenericServlet, the HttpServlet inherits all the


properties (methods) of GenericServlet. So, if you extend HttpServlet,
you can get the functionality of both.

Let us tabulate the differences for easy understanding and remembering.


GenericServlet HttpServlet
Can be used with any protocol (means, can handle any protocol). Protocol
independent. Should be used with HTTP protocol only (can handle HTTP
specific protocols) . Protocol dependent.
All methods are concrete except service() method. service() method is
abstract method. All methods are concrete (non-abstract). service() is
non-abstract method.
service() should be overridden being abstract in super interface.
service() method need not be overridden.
It is a must to use service() method as it is a callback method. Being
service() is non-abstract, it can be replaced by doGet() or doPost()
methods.
Extends Object and implements interfaces Servlet, ServletConfig and
Serializable. Extends GenericServlet and implements interface
Serializable
Direct subclass of Servet interface. Direct subclass of
GenericServlet.
Defined javax.servlet package. Defined javax.servlet.http package.
All the classes and interfaces belonging to javax.servlet package are
protocol independent. All the classes and interfaces present in
javax.servlet.http package are protocol dependent (specific to HTTP).
Not used now-a-days. Used always.
Similarities :

1. One common feature is both the classes are abstract classes.


2. Used with servlets only.

Java Made Clear: Difference ServletRequest, HttpServletRequest :::

When the client clicks the submit button and sends a request to the
server to invoke some Servlet (by giving the alias name of Servlet), the
Servlet container loads the servlet and calls the service() method. The
container also creates objects of ServeltRequest and ServletResponse and
passes them to service() method. The ServletRequest receives the data
sent by the client (which the Programmer can extract in the program) and
ServletResponse is responsible to send the data required by the client.
This we studied in First Example – Login Screen Validation.

Following table gives the differences between ServletRequest and


HttpServletRequest.

ServletRequest HttpServletRequest
Belongs to javax.servlet package Belongs to javax.servlet.http package
— sub interface of ServletRequest
Comes with many methods like getParameter() etc. It inherits all the
methods of ServletRequest and apart adds its own like getQueryString()
etc.
Used in combination with GenericServlet Used in combination with
HttpServlet
Protocol independent Protocol dependent and specific for HTTP protocol
When HTTP was not used, in earlier days, when a request came from client,
Web container used to create an object of ServletRequest and passed to
service() method. When a request comes from client using HTTP
protocol, Web container creates an object of HttpServletRequest and
passes to service() method
Something more to know:
1. With HTTP protocol also, GenericServlet and ServletRequest can be
used. The container creates an object of HttpServletRequest (because
request is coming from client using HTTP) and passes to ServletRequest,
if ServletRequest is required by the container. The actual implementation
is left to the Web server designers.

2. ServletRequest and HttpServletRequest are interfaces with all abstract


methods. The implementation part of abstract methods in the subclasses is
written by the Web server designers. The implementation is completely
dependent on the Web server. For example, the Weblogic server designer
may write his own subclass of ServletRequest as WeblogicServletRequest
and can pass to service() method. The extra behaviour and properties are
server dependent.

Java Made Clear: Difference ServletResponse, HttpServletResponse -


When the client sends a request to the Web server, the server loads the
concerned Servlet and executes the service() method. In the process of
execution, the container creates objects of ServletRequest and
ServletResponse and passes them to the service() method. This is
discussed in First Example – Login Screen Validation.

Following table gives the differences between ServletResponse and


HttpServletResponse.

ServletResponse HttpServletResponse
Belongs to javax.servlet package Belongs to javax.servlet.http package
— sub interface of ServletResponse
Comes with many methods like getWriter() etc. It inherits all the
methods of ServletResponse and apart adds its own like encodeURL() and
sendRedirect() etc.
Used in combination with GenericServlet Used in combination with
HttpServlet
Protocol independent Protocol dependent and specific for HTTP protocol
When HTTP was not used, in earlier days, when a request came from client,
Web container used to create an object of ServletResponse and passed to
service() method. When a request comes from client using HTTP
protocol, Web container creates an object of HttpServletResponse and
passes to service() method
Something more to know:

1. With HTTP protocol also, GenericServlet and ServletResponse can be


used. The container creates an object of HttpServletResponse (because
request is coming from client using HTTP) and passes to ServletResponse,
if ServletResponse is required by the container. The actual
implementation is left to the Web server designers.

2. ServletResponse and HttpServletResponse are interfaces with all


abstract methods. The implementation part of abstract methods in the
subclasses is written by the Web server designers. The implementation is
completely dependent on the Web server. For example, the Weblogic server
designer may write his own subclass of ServletResponse as
WeblogicServletResponse and can pass to service() method. The extra
behaviour and properties are server dependent.

Java Made Clear: What is HttpServletRequest and HttpServletResponse? -

Both are interfaces from javax.servlet.http package.


They are derived from ServletRequest and ServletResponse interfaces.
Both objects are created and implicitly passed to the service() method of
Servlet by container.
The job of HttpServletRequest is to receive data sent by Web client, like
user name and password.
Also comes with many getXXX() methods to retrieve other client
information like client’s IP address, what protocol client used etc. and
also include methods to know about the client’s browser like what is the
name of the browser, its version etc.
The job of HttpServletResponse is to send data to Web client.
Also comes with many setXXX() methods to set properties to a Servlet.
These being interfaces, the implementation of the abstract methods is to
be developed by the Web server (like Tomcat or Jetty) developers. Even
the servlet container is to be developed by the Web server developers.

You might also like