Servlets

You might also like

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

Servlets Introduction, Tutorial and Architecture::

For easy understanding, the introduction is given in Question/Answer


format.

1. What is Component?

A Component is a reusable software unit.

2. What is server-side component?

In client/server communication, a server-side component is that one which


is automatically invoked against client request, executed and responses
to client fulfilling the requirement.

3. What is Web component?

A Web component on the server-side is the one invoked by the client using
Web (Internet) as medium (interface) of communication.

4. What is Servlet?

A Servlet is server-side Java Web component written as per Servlet API


specifications.

5. What is Container and Servlet container?

Container is a general computer term which looks after the execution of a


program. Following are the responsibilities of a container.

Renders services to execute a program (application).


Responsible to call the callback methods whenever required for the smooth
execution of the program.
Responsible to maintain the life cycle of the program (application).
Callback methods are those which are called automatically by the system.
For example, main(String args[]) method in Java is a callback method
called by JVM at the start of the execution. Here, I can name JVM is a
container. Similarly, a browser is a container for an applet. Browser
calls the callback methods of the applet like init(), start() etc. at
appropriate times and also looks over the life cycle of applet.

Servlet container is responsible to execute the servlet. The callback


methods called by the servlet container are init(), service() and
destroy() (also known as life cycle methods). In our subsequent programs,
we load Tomcat server which gets us the servlet container.

6. What is Servlet Architecture?

The architecture, here, discusses the communication interface, protocol


used, requirements of client and server, the programming with the
languages and software involved.

image

In Web communication, the client and server uses Web (Internet) as an


interface (medium) of communication. That is, both client and server
should connect to Web (though an Internet Service Provider) to
communicate, else, impossible to communicate. When connected, the simple
client system can be called as "Web client" and the server can be called
as "Web server". Other way to say simply, any client and server connected
to Web are known as "Web client" and "Web server".
The standard protocol used in the Web, now-a-days, is HTTP (HyperText
Transfer Protocol) protocol. For this reason, the cleint and server are
also can be called as "HTTP client" and "HTTP server" .
When connected, the client sends a request and server responses. In Web
terminology, use only the words of request and response (do not use like
client sends and server replies) only. It is known as request/response
paradigm (style).
To send a request, the software to be loaded on the Web cleint is
"Browser" (the same browser you use to connect to Internet). Similarly,
the software required on the Web server is "Web server software". To get
the Web server software (or servlet container), most commonly used server
is Tomcat (of Apache), Weblogic (of BEA, now acquired by Oracle) and
WebSphere (of IBM) etc.
Responsibilities of Web client
Should be able to take request from the client by displaying some GUI
environment (like user name and passowrd as in Login screen).
To extract the data entered by the user and send it to the Web server as
request.
Should be able to receive what the server responses and display to the
user.
Now choose such a software on the client which can fulfill the above
requirements. Obviously, it is browser. Browser represents the client
system. When I say the client, it means I am talking about the browser on
the client. Client sends request means, the browser on the client sends.
Write a program which can take care of the above requirements in such a
language understood by the browser. The easiet language programmer
prefers is HTML. For GUI, HTML comes with <FORM> tag. So, the client
program is written in HTML (alternatively, you can use an Java Applet
also).
Responsibilities of Web server
Should be able to receive the request send by the Web client.
As per the request, load an appropriate servlet, execute it and send the
output of execution as response to client.
When response is delivered close the connection.
On the Web server-side, I prefer to use popular Tomcat. Tomcat
understands Servlets and JSP apart other frameworks like Struts. Servlets
are written in Java as per Servlet API specifications (rules) stipulated
by Sun Microsystems.

Now with this knowledge, let us write a small program of Login


validations where client sends (as request) user name and password,
server validates and responses valid or invalid.

First Servlet Example Program – Login Screen Validation

After going through the introduction and architecture of servlets, let us


write a simple Login Validation program. As you have seen in the
architecture, there will be two programs – one running on client machine
and the other on server. First let us write the client-side program.

I. Client Program – UserPass.html

<body>

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

<form method="get" action="http://localhost:8888/india/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>
<form method="get" action="http://localhost:8888/india/roses">

localhost: It is the system where Tomcat server is running. Here,


localhost is treated as the server. In realtime, actual name of server
comes.
8888: It is the port number on which Tomcat is running.
india: It is the name of the folder you created and placed in web-app
folder.
roses: It is the alias name of the Validation servlet given web.xml file.
Above steps are clearly explained in Step-by-Step Execution of Servlet in
Tomcat.

II. Servlet program – Validation.java

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

public class Validation extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// extract the user name and
password from req object sent by client
String str1 = req.getParameter("t1");
String str2 = req.getParameter("t2");
// some validation code
if(str1.equals("snrao") && str2.equals("java"))
{
out.println("VALID");
}
else
{
out.println("<b>INVALID</b>");
}

out.close();
}
}

Being the first program, let us have a detailed discussion on each line.

1. import javax.servlet.*;

The above package is imported for the sake of class ServletException.

2. import javax.servlet.http.*;
The above package is imported for the abstract class
HttpServlet and interfaces HttpServletRequest and HttpServletResponse.

3. import java.io.*;

java.io package is needed for PrintWriter and IOException.

4. public class Validation extends HttpServlet

To write a servlet, it is required to extend the abstract class


HttpServlet, like Applet is required to extend to write an applet.

Let us see the hierarchy of HttpServlet.

image

From the above hierarchy, it can be understood that to develop a servlet


there are three styles.

a) by implementing Servlet interface


b) by extending GenericServlet
c) by extending HttpServlet

The disadvantage of first style is, it is required to override all the


abstract methods of the interface Servlet eventhough we are not
interested (like the interface WindowListener to close a frame) in a few.
The better approach is extending GenericServlet (like WindowAdapter to
close the frame) which contains only one abstract method service(). It is
enough to the programmer to override only this method. It is a callback
method. GenericServlet was used by the programmers when HTTP protocol was
not standardized for the Web. When the HTTP became a defacto standard for
Web, HttpServlet was designed to suit more for HTTP protocol. HttpServlet
is an abstact class but without any abstract methods (all are non-
abstract methods). Even the service() method is non-abstract and infact
with HttpServlet, the service() method can be replaced by the methods
doGet() or doPost(). This we will see later.

The above code works fine even if GenericServlet is extended instead of


HttpServlet.

5. public void service(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException

service() method is a callback method called automatically when the


container loads the servlet for execution when the client request comes.
The method takes two parameters – an object of interface
HttpServletRequest and an object of interface HttpServletResponse and let
us see what these interfaces meant to servlet.

a) HttpServletRequest interface

Following is the hierarchy.

image

The first parameter can be either of ServletRequest or its sub-interface


HttpServletRequest. We use ServletRequest as parameter when we extend
GenericServlet and HttpServletRequest when HttpServlet is extended. The
data send by the client (through HTML) finally reaches HttpServletRequest
object after travelling intermittent stages. That is, req object of
HttpServletRequest receives data sent by client. From this object, the
servlet programmer can extract the data and can use for validation or
other purposes as hereunder.

b) HttpServletResponse interface

image

The second parameter can be either of ServletResponse or its sub-


interface HttpServletResponse. We use ServletResponse as parameter when
we extend GenericServlet and HttpServletResponse when HttpServlet is
extended. The responsibility of the data to be sent (like valid or
invalid etc.) to the client is taken care by HttpServletResponse. The
programmer job is simply to pass the response messages (to be reached to
client) to HttpServletResponse and actual sending is taken care by the
container.

c) The service() method throws two checked exceptions of


javax.servlet.ServletException and java.io.IOException.

6. res.setContentType("text/html");

setContentType(String) is a method of ServletResponse inherited by


HttpServletResponse and its job is sending the information to client’s
browser of how the response sent by the servlet is to be formatted. It is
here is text or HTML. That is, the data sent to the client is either in
text format (as in ("VALID")) or HTML format (as in (<b>INVALID</b>)).
The difference is HTML <b> tag. This is more called as setting the MIME
(Multipurpose Internet Mail Extension) type. The other types can be of
image/gif etc. which we use later.

7. PrintWriter out = res.getWriter();


8. out.println("VALID");

We know earlier the HttpServletResponse is meant to send data (known as


response) to client. Being an interface, it cannot be used directly. As a
convenience, the getWriter() method of ServletResponse (inherited by
HttpServletResponse) returns an object of PrintWriter. println() is a
method of PrintWriter used to attach a message, here, as a string
parameter. This string message (here, VALID OR INVALID) is ultimately
sent to client by the HttpServletResponse.

9. String str1 = req.getParameter("t1");

We know the data sent by client (known as request) finally reaches


HttpServletRequest. getParameter(String) method of ServletRequest
(inherited by HttpServletRequest) takes a string parameter and returns a
string. The parameter is nothing but the <FORM> field name (here, t1) and
the returned string value is what user entered in field t1. Using
getParameter() method, the programmer extracts all the data sent by the
client. The other way is getParameterNames() where all the data is
extracted in a single stretch in a for loop.

10. out.close();

When the job is over, it is customary to close the streams as you have
done in file copying.

7 Steps – Servlets Tomcat Execution::


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 is
compatible with 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 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.
3. Now what is to be done?

Following next steps for deployment and execution.

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.

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.

For all servlet programs, the same procedure is followed.

Note: Whenever the servlet file is copied (even the same one), it is
required to restart the Tomcat every time.

Note: For the installation of Tomcat and running first program, it is


advised to take the help of a friend knowing Servlets, else it takes a
hell of time to execute the first program requiring lot of Google search.
Deployment Descriptor – web.xml in Servlets:::

1. What is Deployment?

Copying the .class file of the servlet from the current directory to the
classes folder of Tomcat (or any Web server) is known as deployment. When
deployed, Tomcat is ready to load and execute the servlet, at anytime, at
the client request.

2. What is Deployment Descriptor?

As the name indicates, the deployment descriptor describes the deployment


information (or Web Information) of a Servlet. The deployment descriptor
is an XML file known as web.xml. XML is the easiest way to give the
information to a server, just writing in between the tags, instead of
writing in a text file or RDBMS file. The name and tags of web.xml are
Servlet API specifications.

3. What information can be stored with deployment descriptor?

The following activities can be done by the programmer in web.xml file.


a) Mapping alias name with the actual servlet name

First and foremost is the alias name to the servlet. Never a client is
given the actual name of the servlet. Always an alias name is given just
for security (avoid hacking). The alias name is given in the following
XML tags.

image

The servlet comes with two alias names, internal and external. The
internal name is used by the Tomcat and the external name is given (to be
written in <FORM> tag of HTML file) to the client to invoke the servlet
on the server. That is, there exists alias to alias. All this is for
security. Observe, the names are given in two different XML tags, in the
web.xml file, to make it difficult for hacking (for more security in EJB,
two alias are given in two different XML files).

To invoke the Validation servlet, the client calls the server with the
name roses. When roses call reaches the server, the Tomcat server opens
the web.xml file to check the deployment particulars. Searches such a
<servlet-mapping> tag that matches roses. roses is exchanged with abcd.
Then, searches such a <servlet> tag that matches abcd and exchanges with
Validation. Now the server, loads Validation servlet, executes and sends
the output of execution as response to client.

b) To write Initialization Parameters

Intialization parameteres are read by the servlet from web.xml file.


Programmer can write code to be used for initialization. An example code
is given below

<init-param>
<param-name>trainer</param-name>
<param-value>S. Nageswara Rao</param-value>
</init-param>
This can be read by the servlet using ServletConfig interface. It is more
discussed in init param Example with ServletConfig.
c) To write tag libraries (this is mostly used in frameworks like Struts
etc)

An example code is given used in Struts. This we will cover later.

<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
Following are a few important XML elements in web.xml.

<context-param>, <filter-mapping>, <taglib> and <mime-mapping> etc.

Note 1: When a servlet code is modified and copied to classes folder,


each time it is required to restart the Tomcat server.

Note 2: For every servlet, there must be an entry in web.xml file with an
alias name.

Creating dynamically filled HTML form to client in Servlets

This is the modified code of the Login Screen Validation. In the first
program, the user name and password are read by the servlet, validated
and sent back the result of validation (valid or invalid) as response.

The modification is, whichever field is wrong, that field is sent empty
and which field is correct, that is filled and sent. That is both user
name and password are to be validated separately and as per the
validation, a HTML form is generated dynamically (on the fly) and sent to
the client. This is like creating a new email account.

We know earlier in the first program, whatever is placed in out.println()


method goes to client. Now in out.println(), the whole HTML file is
placed and sent to the client. The browser on the client takes HTML and
displays the form.

<body>

<h3> Login Validation </h3>

<form method="get"
action="http://localhost:8888/india/dynamicgeneration">
Enter User Name <input type="text" name="t1"> <br>
Enter Password <input type="password" name="t2"> <br>
<input type="submit" value="Send">

</form> </body>
In the HTML, there is nothing new. Following is the web.xml entry for the
servlet.

<servlet>
<servlet-name>dhfg</servlet-name>
<servlet-class>DynamicHTMLFormGeneration</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>dhfg</servlet-name>
<url-pattern>/dynamicgeneration</url-pattern>
</servlet-mapping>
Following is the servlet program.

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

public class DynamicHTMLFormGeneration extends HttpServlet


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

String str1 = req.getParameter("t1");


String str2 = req.getParameter("t2");

if( str1.equals("snrao") && str2.equals("java") )


{
out.println("<body bgcolor = green text = white>");
out.println("<h2> VALID </h2>");
}
else // here comes separate validatoin
{
out.println("<body> <h3> Login Validation </h3>");
out.println("<form method=get action =
http://localhost:8888/india/dynamicgeneration>");

if( str1.equals("snrao") )
{
out.println("Enter User Name <input type=text name=t1 value=" +
str1 + "> <br>");
}
else
{
out.println("Enter User Name <input type=text name=t1> <br>");
}

if( str2.equals("java") )
{
out.println("Enter Password <input type=password name=t2 value="
+ str2 + "> <br>");
}
else
{
out.println("Enter Password <input type=password name=t2>
<br>");
}

out.println("<input type=submit value=Send>");


out.println("</form> </body>");

}
out.close();
}
}
When both fields are given correct values as follows
ima

the response screen is

ima

When password is given wrong as follows

ima

the response screen is

ima

Observe, the password field is empty (not filled).


If you give both fields wrong, both fields will be empty; try.

Sending static HTML form to Client (sendRedirect) in Servlets ::::

It is the modification of the first program Login Validation. The


modification is instead of sending INVALID message, a new HTML form is
sent to the user wherein the user can fill up again and send. This HTML
form is existing already on the server. It is not created on the fly.
That is why, I called it as a static form.

Client Program: File Name: UserPass.html

<body>

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

<form method="get" action="http://localhost:8888/india/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>
Servlet Program: File Name: Validation.java

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

public class Validation extends HttpServlet


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

String str1 = req.getParameter("t1");


String str2 = req.getParameter("t2");
if(str1.equals("snrao") && str2.equals("java"))
{
out.println("VALID");
}
else
{
res.sendRedirect("UserPass.html");
}
out.close();
}
}
res.sendRedirect("UserPass.html");

sendRedirect(String) is a method of HttpServletResponse which is capable


of sending a file to the client passed as a string parameter.

Following is the method signature as defined HttpServletResponse


interface.

public abstract void sendRedirect(java.lang.String) throws


java.io.IOException;

When user name and password are given correct

ima

the response screen is

ima

When the password is given wrong as hereunder,

ima

the following fresh (new) form is sent.

ima

Servlet getParameterNames() Example::::

One of the aspects of Servlets is reading the HTML/Applet data sent by


the client like login data etc. For this, three methods exist in
ServletRequest interface – getParameter(String), getParameterNames() and
getParameterValues(String). These methods are inherited by
HttpServletRequest interface.

Following are the method signatures as defined in


javax.servlet.ServletRequest interface.

public 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. Request parameters are extra information sent with the
request. For HTTP servlets, parameters are contained in the query string
or posted form data.
public java.util.Enumeration getParameterNames():
Returns an Enumeration of String objects containing the names of the
parameters contained in this request. If the request has no parameters,
the method returns an empty Enumeration.
public 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. If the
parameter has a single value, the array has a length of 1.
The first method getParameter(String) is explained in Login Screen
Validation and the third in Servlets getParameterValues() Example. Now
let us see the second one, getParameterNames().

getParameter(String) is used to read only one form field.


getParameterNames() is used to read all form field data at a time. Let us
explain further with an example.

Client Program: StudentAddress.html

<body>
<form method="get" action="http://localhost:8888/india/readall">

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


Enter Student ID <input type="text" name="t2"> <br>
Enter Student Marks <input type="text" name="t3"> <br>
Enter Student Branch <input type="text" name="t4"> <br>
Enter Student College <input type="text" name="t5"> <br>
Enter Student Residence <input type="text" name="t6"> <br>
<input type="submit" value="PRINT ALL"> <br>

</form>
</body>
Observe, there are 6 form fields from t1 to t6. The aim of this servlet
is to read all at a time.

web.xml entry for GetPNames servlet:

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>GetPNames</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/readall</url-pattern>
</servlet-mapping>
Servlet: GetPNames.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Enumeration;

public class GetPNames extends HttpServlet


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

Enumeration e = req.getParameterNames();

while(e.hasMoreElements())
{
Object obj = e.nextElement();
String fieldName = (String) obj;
String fieldValue = req.getParameter(fieldName);
out.println(fieldName + " : " + fieldValue + "<br>");
}

out.close();
}
}
Enumeration e = req.getParameterNames();

The getParameterNames() of ServletRequest (inherited by


HttpServletRequest) returns an object of java.util.Enumeration.

Object obj = e.nextElement( );


String fieldName = (String) obj;
String fieldValue = req.getParameter(fieldName);

The e object of Enumeration contains all the names of fields like t1, t2,
t3 etc. but not their values entered by the user. The nextElement()
returns one field name for each iteration. The field name is passed to
getParameter(fieldName) method to retrieve the value entered by the user.

HTML file when all the fields are filled up:

ima

Output screen when submit button clicked:

ima1

Note: Observe, the output is not in correct order (infact, it is in


reverse order). It is the problem with Enumeration; anyhow, here order is
not important.

Get all parameters of HTML form with getParameterNames() ::

In the first simple program Login Screen Validation, the data sent by the
client is extracted from HttpServletRequest object req, using
getParameter(String) method. The getParameter(String) method works to
read a single text box (or any FORM field) only. The HttpServletRequest
interface comes with another method getParameterNames() (inherited from
ServletRequest interface) to read all the FORM fields’ values at a time.
Following is the method signature.

public abstract java.util.Enumeration getParameterNames();

The above signature indicates, the return value is an object of


Enumeration interface. This method is used in this program.

As usual there exists minimum two programs running one on client-side and
the other on server-side.

1st Program (running on client): AllFields.html

<body>
<H3> Reading all Text box values at a time </H3>
<form method="get" action="http://localhost:8888/india/tiger">

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


Enter Middle Name <input type="text" name="t2"> <br>
Enter Last Name <input type="text" name="t3"> <br>
Enter Experience <input type="text" name="t4"> <br>
Enter Hobby <input type="text" name="t5"> <br>

<input type="submit" value="Print All">

</form> </body>
Observe, the above HTML file comes with five text boxes from t1 to t5.
The following servlet, reads all at a time.

2nd Program (running on server): ReadAll.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Enumeration;
import java.io.*;

public class ReadAll extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter( );
// to retrieve one text box value
String str1=req.getParameter ("t3");
out.println("Reading only one t3 field value : " + str1 +
"<br><br>");
// to retrieve all fields values at a time
out.println("Reading all text boxes values at a time:<br>");
Enumeration e = req.getParameterNames();
out.println("<body bgcolor=pink>");

while(e.hasMoreElements())
{
String name=(String) e.nextElement();
out.println( name +" : ");
String value=req.getParameter(name);
out.println(value.toUpperCase() +"<br>");
}

out.println("</body>");
out.close();
}
}
web.xml entry for the above servlet:

<servlet>
<servlet-name>animal</servlet-name>
<servlet-class>ReadAll</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>animal</servlet-name>
<url-pattern>/tiger</url-pattern>
</servlet-mapping>
String str1 = req.getParameter ("t3");

The above method is known earlier in the first program and with this
method, we learnt how to read a single text box value. The same is
repeated with t3 text box to know the value entered by the user in t3
box. But the aim of this code is different – to read all boxes’ values at
a time.

Enumeration e = req.getParameterNames();

The getParameterNames() method returns an object of Enumeration


interface. This Enumeration object e contains all the names of text boxes
like t1, t2, t3 etc., but not their values. It is the same Enumeration
interface we learnt in Collections framework. The object e contains all
the text boxes names (t1 to t5) but not their values. It is extra
following code to extract the values entered by the user in these form
fields.

String name=(String) e.nextElement();


out.println(name + " : ");
String value=req.getParameter(name);
out.println(value.toUpperCase() + "<br>");

The Enumeration interface comes with two methods – hasMoreElements()


returning a boolean value used to iterate the loop and the nextElement()
returning an object of Object class used to retrieve the form field name.

The name variable contains the name of the FORM field (like t1 or t2
etc.). The getParameter(name) returns the value entered by the user in
the FORM field name. The value variable contains the actual data entered
by the user in the field name.

Using Enumeration object, all the values entered by the user in the FORM
fields are extracted.

Following are output screens.

ima

ima

Observe the response screen. The values are not in the other of t1 to t5.
It is the problem with Enumeration iteration and not with servlet.
Anyhow, the order is not important here.

A similar program is available using Enumeration to read all the


initialization parameters of web.xml file by a Servlet: Servlet web xml
init param Example using ServletConfig.

Servlets getParametehttp://way2java.com/jsp/first-jsp-example-user-name-
and-password-login-validationrValues() Example -:::::

One of the aspects of Servlets is reading the HTML/Applet data sent by


the client like login data etc. For this, three methods exist in
ServletRequest interface – getParameter(String), getParameterNames() and
getParameterValues(String). These methods are inherited by
HttpServletRequest interface.

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

public 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. Request parameters are extra information sent with the
request. For HTTP servlets, parameters are contained in the query string
or posted form data.
public java.util.Enumeration getParameterNames():
Returns an Enumeration of String objects containing the names of the
parameters contained in this request. If the request has no parameters,
the method returns an empty Enumeration.
public 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. If the
parameter has a single value, the array has a length of 1.
The first method getParameter(String) is explained in Login Screen
Validation. The second method is discussed in Servlet getParameterNames()
Example. Now let us see the third one, getParameterValues(String).

getParameter(String) is used to read only one form field.


getParameterNames() is used to read all form field data at a time.

When to use getParameterValues() to read form data?

Observe the following client HTML file, StudentAddress.html

<body>
<form method="get" action="http://localhost:8888/india/readall">

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


Enter ID <input type="text" name="t2"> <br>
Enter H.No. <input type="text" name="t3"> <br>
Enter Street <input type="text" name="t3"> <br>
Enter Area <input type="text" name="t3"> <br>
Enter City <input type="text" name="t3"> <br>
Enter PIN <input type="text" name="t3"> <br>
<input type="submit" value="PRINT ALL"> <br>

</form>
</body>
Observe, there are total 7 form fields of which five fields are having a
common name of t3. All the five form fields with t3 name comprises of a
student address. The job of the servlet may be to extract all the 7 form
fields data and enter into a database table. Imagine, the database have
only 3 columns like stdname, stdid and stdaddress. The value of t1 goes
into the stdname column, t2 goes into stdid and all the remaining five
fields with name t3 goes into stdaddress.

How to do this job easily in a servlet?

Read t1 and t2 separately with getParameter(String) method as usual as


you did in Login Screen Validation. Now comes our
getParameterValues(String) method to read all the t3 values at a time.
This method returns a string array containing all the values entered by
the user in t3 fields. Take this array and enter into the database
column. Ofcourse, the aim of this servlet is reading only but does not do
any database operation.

web.xml entry for GetPNames servlet:

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>GetPNames</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/readall</url-pattern>
</servlet-mapping>
Servlet: GetPNames.java

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

public class GetPNames extends HttpServlet


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

String address[] = req.getParameterValues("t3");

StringBuffer temp = new StringBuffer();


for(String str : address)
{
temp.append(str + ", ");
}

out.println(temp);
out.close();
}
}
getParameterValues(String) avoids reading separately. But the condition
is all the fields should have the common name. The StringBuffer object
temp can be taken and inserted into a database column.

Client-side HTML screen when values are entered.

ima

Output screen when the submit button is clicked.

ima1

Handling the client request – HTML form data – 3 Styles ::

One of the activites of a Servlet developer is to read the data sent by


the client through a HTML form. The data sent by the client lands finally
in ServletRequest/HttpServletRequest object passed as parameter to
service() method. To retrieve the data from ServletRequest object, the
ServletRequest interface comes with three methods mostly used.
They are getParameter(String), getParameterNames() and
getParameterValues(String).

Let us see what Java API says about these methods as defined in
javax.servlet.ServletRequest interface and inherited by
HttpServletRequest interface.

public 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. Request parameters are extra information sent with the
request. For HTTP servlets, parameters are contained in the query string
or posted form data.
public java.util.Enumeration getParameterNames():
Returns an Enumeration of String objects containing the names of the
parameters contained in this request. If the request has no parameters,
the method returns an empty Enumeration.
public 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. If the
parameter has a single value, the array has a length of 1.
getParameter(String) is used to read only one form field data as a
string. Example is available at Login Screen Validation.
getParameterNames() is used to read all form fields data at a time as an
Enumeration object. Example is available at Servlet getParameterNames()
Example.
getParameterValues(String) is used to read multiple form field data as a
string array where fields have some common name. Example is available at
Servlets getParameterValues() Example.

Difference between GET and POST Methods:::

The developer should specifiy to the browser in what style the data is to
be sent to the server. The most commonly used styles are GET and POST.
These styles are to be written in METHOD attribute of <FORM> tag as
follows.

<form method="GET" action="http://localhost:8888/india/roses">

In GET style, the data is appended to the URL (written in action


attribute in the above statement) and sent to the server and in POST
style, the client data is sent separately as message body.

Remember the Login Screen Validation Servlet. The screens are displayed
here in relevance to GET style.

Observe the client HTML program when the fields (text boxes) t1 (for user
name) and t2 (for password) are filled up.

ima

Observe the URL in browser prompt.

Output screen when submit button is clicked.


ima

Now again, observe the URL in browser prompt. It is as follows.

http://localhost:8888/india/roses?t1=S+N+Rao&t2=java

What we understand by the above URL?

The data of user name (S N Rao) and the password (java) are appended to
the URL with a delimiter (separator) of ?, that is, the actual URL
separated from the client data with a question mark, ?. Still observe,
the spaces in between S N Rao are indicated with + symbol and delimiter &
is used to separate two fields of t1 and t2.

Following table gives a glance of the differences.

Feature GET POST


Sending of data Client data is appended to URL and sent Client data is
sent separately
Storing in Browser History As data is appended, the client data is
stored in browser history As data is sent seaprately, the client data
is not stored in browser history
Bookmark The URL with client data can be bookmarked. Thereby, later
without filling the HTML form, the same data can be sent to server Not
possible to bookmark
Encoding or enctype application/x-www-form-urlencoded application/x-
www-form-urlencoded or multipart/form-data. For binary data, multipart
enctype to be used
Limitation of data sent Limited to 2048 characters (browser
dependent) Unlimited data
Hacking easiness Easy to hack the data as data is stored in browser
history Difficult to hack
Type of data sent Only ASCII data can be sent Any type of data can
be sent including binary data
Data secrecy Data is not secret as other people can see the data in
browser history Data is secret as not stored in history
When to be used Prefer when data sent is not secret. Do not use for
passwords etc. Prefer for critical and sensitive data like passwords
etc.
Cache Can be caught Cannot be caught
Default If not mentioned, GET is assumed as default Should be
mentioned explicitly
Performance Relatively faster as data is appeneded to URL A separate
message body is to be created
Which is to be preferred – GET or POST?

It depends on your application need. If client data includes only ASCII


characters, no secrecy and limited to 2KB length (depends on the
browser), then prefer GET, else POST.

Servlet getHeaderNames() and getHeader() Simple Example :::

When a client clicks a hyper link or a submit button, we know that the
data entered by the user in the Form fields is sent to server and is the
default behaviour of submit button. Ofcourse, right. But along with a lot
of extra information goes to server on the name of headers (attached to
request object) like what browser client is using, its supported
languages etc.
Apart header data, lot of other data of client system also goes like what
client system IP address is, what protocol client is using and on what
port number client browser is sending request etc.

This tutorial illustrates how to extract Header information from request


object. The methods used are getHeaderNames() and getHeader(String)
defined in javax.servlet.http.HttpServletRequest interface.

Let us see first what Servlet API says about these methods:

Enumeration getHeaderNames(): Returns an enumeration of all the header


names this request contains. If the request has no headers, this method
returns an empty enumeration.
Some servlet containers do not allow servlets to access headers using
this method, in which case this method returns null.
String getHeader(String name): Returns the value of the specified request
header as a String. If the request did not include a header of the
specified name, this method returns null. If there are multiple headers
with the same name, this method returns the first head in the request.
The header name is case insensitive. You can use this method with any
request header.
Following code gives a very simple program of extracting header
information from request object.

Client HTML file: Headers.html

<body>

Would you like to see the <a href="http://localhost:8888/india/head">


Headers</a> please?

</body>
web.xml entry for Headers.java servlet

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

<servlet-mapping>
<servlet-name>snrao1</servlet-name>
<url-pattern>/head</url-pattern>
</servlet-mapping>
Server Servlet File: Headers.java

import javax.servlet.*;
import javax.servlet.http.* ;
import java.io.* ;
import java.util.*;
public class Headers extends HttpServlet
{
public void service( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

Enumeration e = req.getHeaderNames();
out.println("<H3>Following are the Headers coming from the
Client<BR></H3>");

out.println("<table border=2 bordercolor=blue>");

out.println("<tr><th>Header Name</th><th>Header Value</th></tr>");

while(e.hasMoreElements())
{
String name = (String) e.nextElement();
String value = req.getHeader(name);
out.println("<tr><th>"+name + "</th><th>" + value + "</th></tr>");
}
out.println("</table>");
out.close();
}
}
Enumeration e = req.getHeaderNames();

The getHeaderNames() method of HttpServletRequest returns an object of


Enumeration. The Enumeration object e contains all the header names but
not their associated values. In the code, value associated with each
header is read and printed.

String name = (String) e.nextElement();


String value = req.getHeader(name);

The getHeaderNames() returns the header names in the form of strings. For
this reason, the object returned by nextElement() is casted to String.
Pass the header name "name" to getHeader() and the method returns the
associated value as a string. In the while loop, with each iteration, one
header name and its value are printed. Observe the output screen.

Client HTML Screen with a Hyperlink.

ima

Output screen with Headers Name Vs Header Value.

ima1

In the above screenshot, the first column of table gives the header names
and the second column gives the values associated with each header.

Following list gives the meaning of each header name.

host: This header gives the host (server) name and port number as written
in the URL (in ACTION attribute).
connection: It specifies whether the client’s browser can handle the
persistent HTTP connections. "keep-alive" indicates that the browser can
handle persistent connections. On a persistent connection, the browser
can retrieve multiple files on a single request (or single connection).
accept: This header informs the Server (or Servlet) what MIME types (like
text/html, image/gif etc.) the browser supports (so that the Servlet can
send response in the supported MIME type only).
user-agent: Returns the name of the browser and its version etc. This
information is used by the Servlet to send data specific to that browser.
Suppose, the Servlet would like to send <MARQUEE> tag and if client is
having Netscape Navigator browser (which does not support MARQUEE tag),
it does not send and instead it may send the same information in <BLINK>
tag supported by Netscape. Or a Servlet sends a response to the browser
that requires an ActiveX control which the browser may not have.
Microsoft IE version 4 does not come with ActiveX controls supported by
version 5. For this reason, the Servlet requires the user-agent
information.
accept-encoding: This header tells the Servlet what type of compression
algorithms are supported by the browser like gzip etc. so that Servlet
sends an appropriate compressed file to the browser.
accept language: This informs the Server that what type of languages the
browser support like English, Spanish or Japanese etc., so that the
Servlet may send response in other languages supported by the browser.
Java and Servlets support Internationalization.

request.getRequestURL() method Example in Servlets:::

What is client data?

When the user clicks the submit button, we think that the data entered by
the user like user name and password are sent to the server. Ofcourse,
right. But along with it, lot of client data goes to the server. The
client data includes the protocol used by the client to access the
server, client IP address and also the name of the browser client is
using, its version (headers) etc.

Is there anyway to retrieve client data from the servlet?

Yes, HttpServletRequest interface comes with many methods to retrieve the


client data.

This program uses getRequestURL() to retrieve the URL used by the client
to call the servlet on the server.

Following is the method signature as defined in HttpServletRequest


interface.

public abstract java.lang.StringBuffer getRequestURL();


Let us go to the coding part.

Client Program: ClientData.html

<body>

<form method="get" action="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</form>

</body>
web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Server Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

StringBuffer sb = req.getRequestURL();
out.println("req.getRequestURL() : " + sb);

out.close();
}
}
Output screen of ClientData.html with text field filled up.

getme

The output screen when submit button is clicked.

ima

Observe, the getRequestURL() prints the complete URL (written in ACTION


attribute of FORM tag) used by the client to call the servlet. This is
where getRequestURL() differs from getRequestURI().

request.getRequestURI() Method Example in Servlets:::

What is client data?

When the user clicks the submit button, we think that the data entered by
the user like user name and password are sent to the server. Ofcourse,
right. But along with it, lot of client data goes to the server. The
client data includes the protocol used by the client to access the
server, client IP address and also the name of the browser client is
using, its version (headers) etc.

Is there anyway to retrieve client data from the servlet?

Yes, HttpServletRequest interface comes with many methods to retrieve the


client data.

This program uses getRequestURI() to retrieve the a part of the URL used
by the client to call the servlet on the server.

Following is the method signature as defined in HttpServletRequest


interface.

public abstract java.lang.String getRequestURI();


Let us go to the coding part.
Client Program: ClientData.html

<body>

<form method="get" action="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</form>

</body>
web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Server Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

String str = req.getRequestURI();


out.println("req.getRequestURI() : " + str);

out.close();
}
}
Following is the method signature as defined in HttpServletRequest
interface.

public abstract java.lang.String getRequestURI();


Output screen of ClientData.html with text field filled up.

getme

The output screen when submit button is clicked.

ima

Observe, the getRequestURI() prints a portion of the URL (written in


ACTION attribute of FORM tag) used by the client to call the servlet.
This is where getRequestURL() differs from getRequestURI().
Difference between getRequestURL() and getRequestURI() :::

getRequestURL() and getRequestURI() methods are defined in


HttpServletRequest interface. These two are used by the servlet to
retrieve the URL information (written in ACTION attribute of FORM tag)
used by the client to call the servlet.

They differ in the length of the URL returned.

Let us see what Java API says about these methods.

public abstract java.lang.StringBuffer getRequestURL(): Reconstructs the


URL the client used to make the request. The returned URL contains a
protocol, server name, port number, and server path, but it does not
include query string parameters.
public abstract java.lang.String getRequestURI(): Returns the part of
this request’s URL from the protocol name up to the query string in the
first line of the HTTP request.
Let us write a servlet that includes both methods and analyze them.

HTML Program: ClientData.html

<body>

<form method="get" action="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</form>

</body>
web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
StringBuffer sb = req.getRequestURL();
out.println("req.getRequestURL() : " + sb);

String str = req.getRequestURI();


out.println("<br><br>req.getRequestURI() : " + str);

out.close();
}
}
Output screen of ClientData.html with text field filled up.

getme

The output screen when submit button is clicked.

ima

By looking at the output screen, it is understood that getRequestURL()


returns complete URL used by the client where as getRequestURI() returns
just the basic folder name (may represent the project name) and the
servlet alias name. Anyhow, both will not return the query string (like
t1=SNRao).

request.getRemoteAddr() Method Example in Servlets:::

This method is defined in ServletRequest interface from javax.servlet


package inherited by HttpServletRequest.

With this method, the servlet programmer can know the IP address of the
client from which the request came.

Let us see what Java API says about this method.

String getRemoteAddr(): Returns the Internet Protocol (IP) address of the


client or last proxy that sent the request. For HTTP servlets, same as
the value of the CGI variable REMOTE_ADDR.
The method getRemoteAddr() returns the IP address of the cleint as a
string.

Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="get" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

String str = req.getRemoteAddr();


out.println("req.getRemoteAddr() : " + str);

out.close();
}
}
Output screen of ClientData.html with text field filled up. Ofcourse,
this does not have any relevance with the method getRemoreAddr() method.

getme

The output screen when submit button is clicked.

ima

Observe, the IP address as 127.0.0.1

To know the name of the client system (not IP address), a separate


program exists: request.getRemoteHost() Method Example.

request.getRemoteHost() Method Example in Servlets:::

This method is defined in ServletRequest interface from javax.servlet


package inherited by HttpServletRequest.

With this method, the servlet programmer can know the name of the client
from which the request came.

Let us see what Java API says about this method.

java.lang.String getRemoteHost():
Returns the fully qualified name of the client or the last proxy that
sent the request. If the engine cannot or chooses not to resolve the
hostname (to improve performance), this method returns the dotted-string
form of the IP address. For HTTP servlets, same as the value of the CGI
variable REMOTE_HOST.
The method getRemoteHost() returns the name of the client system as a
string.
Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="get" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

String str = req.getRemoteHost();


out.println("req.getRemoteHost() : " + str);

out.close();
}
}
Output screen of ClientData.html with text field filled up. Ofcourse,
this does not have any relevance with the method getRemoreAddr() method.

getme

The output screen when submit button is clicked.

ima

Observe, the name is localhost, used in HTML file in ACTION attribute.

To know the IP address of the client (not name), a separate program


exists: request.getRemoteAddr() Method Example.

Difference between getRemoteAddr() and getRemoteHost() :::


Both are defined in ServletRequest interface and serves the servlet
programmer to retrieve the client system particulars from where the
request came. They differ slightly in the output.

getRemoteAddr() returns a string containing the IP address (in format


like IPiv, 127.0.0.1) of the client.

getRemoteHost() returns a string containing the name of the client system


(like localhost or fully qualified name of the client).

Let us see what Java API says about these methods as defined
javax.servlet.ServletRequest interface.

public java.lang.String getRemoteAddr(): Returns the Internet Protocol


(IP) address of the client or last proxy that sent the request. For HTTP
servlets, same as the value of the CGI variable REMOTE_ADDR.
public java.lang.String getRemoteHost(): Returns the fully qualified name
of the client or the last proxy that sent the request. If the engine
cannot or chooses not to resolve the hostname (to improve performance),
this method returns the dotted-string form of the IP address. For HTTP
servlets, same as the value of the CGI variable REMOTE_HOST.
Let us see the difference practically through a program.

HTML Program: ClientData.html

1
2
3
4
5
6
7
8
<body>

<FORM METHOD="get" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ClientInformation extends HttpServlet


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

String str1 = req.getRemoteAddr();


out.println("req.getRemoteAddr() : " + str1);

String str2 = req.getRemoteHost();


out.println("<br><br>req.getRemoteHost() : " + str2);

out.close();
}
}
Output screen of ClientData.html with text field filled up. Ofcourse,
this does not have any relevance with the methods.

getme

The output screen when submit button is clicked.

ima

Observe, the getRemoteAddr() returns the IP address as 127.0.0.1 and


gerRemoteHost() returns localhost, the name given in ACTION attribute of
FORM tag in HTML file.

request.getQueryString() Method Example in Servlets ::

This method is defined in HttpServletRequest interface from


javax.servlet.http package.

With this method, the servlet programmer can know the data (through FORM
fields like user name etc.) sent by the client.

What is query string in servlets?


It is the string containing the name of FORM fields and the data entered
by the user in the fields. Field is separated with the value entered by
the user with = symbol (see the output screen).

Let us see what Java API says about this method.

java.lang.String getQueryString():
Returns the query string that is contained in the request URL after the
path. This method returns null if the URL does not have a query string.
Same as the value of the CGI variable QUERY_STRING.
The method getQueryString() returns a string of data, filled by the user
in FORM fields (of text boxes, check boxes etc.), and sent to server.

Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="GET" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

String str = req.getQueryString();


out.println("req.getQueryString() : " + str);

out.close();
}
}
Output screen of ClientData.html with text field filled up as SNRao.
getme

The output screen when submit button is clicked.

ima

Observe, t1 is the name of text box in the HTML file and SNRao is the
value entered in t1. The field and value are separated by = symbol.

Note: With POST method in HTML, it is observed that the queryString()


returns null.

request.getContentLength() Method Example in Servlets ::

This method is defined in ServletRequest interface from javax.servlet


package and inherited by HttpServletRequest.

With this method, the servlet programmer can know the length of data
(through FORM fields like user name etc.) sent by the client. Or to say,
the length (in bytes) of query string.

What is query string in servlets?

It is the string containing the name of FORM fields and the data entered
by the user in the fields. Field is separated with the value entered by
the user with = symbol (see the output screen).

Let us see what Java API says about this method.

public int getContentLength():


Returns the length, in bytes, of the request body and made available by
the input stream, or -1 if the length is not known. For HTTP servlets,
same as the value of the CGI variable CONTENT_LENGTH.
The method getContentLength() returns the number of bytes as an integer
value, the length of data sent by the client through FORM fields (of text
boxes, check boxes etc.).

Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="POST" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
Observe, the client uses8888 port number in attribute ACTION.

web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

int length = req.getContentLength();


out.println("req.getContentLength() : " + length);

out.close();
}
}
Output screen of ClientData.html with text field filled up as SNRao.

getme

The output screen when submit button is clicked.

ima

Observe, the content length is 8 bytes (of t1=SNRao).

Note: With GET method in HTML, the content returned is -1.

request.getServletPath() Method Example in Servlets :::

Sometimes, it may be required by the programmer to retrieve the alias


name used by the client to access the servlet.

This program uses getServletPath() of HttpServletRequest to retrieve the


alias name (of <servlet-mapping>) tag used by the client to call the
servlet.

Following is the method signature as defined in HttpServletRequest


interface.

public abstract java.lang.String getServletPath();


Let us go to the coding part.

Client Program: ClientData.html

<body>

<form method="get" action="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</form>

</body>
web.xml entry for ClientInformation servlet
<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Let us go to the coding part.

Server Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

String str = req.getServletPath();


out.println("req.getServletPath() : " + str);

out.close();
}
}
Output screen of ClientData.html with text field filled up.

getme

The output screen when submit button is clicked.

ima

Observe, the getServletPath() prints just the alias name and not complete
URL. To retrieve complete URL, use getRequestURL() method of
HttpServletRequest.

request.getMethod() Method Example in Servlets:::

This method is defined in HttpServletRequest interface from


javax.servlet.http package.

With this method, the servlet programmer can know what method (either get
or post) is used by the client from HTML file to call the servlet.

Let us see what Java API says about this method.

java.lang.String getMethod(): Returns the name of the HTTP method with


which this request was made, for example, GET, POST, or PUT. Same as the
value of the CGI variable REQUEST_METHOD.
The method getMethod() returns a string, the attribute of METHOD in FORM
tag used by the client to call the servlet, generally either GET or POST.

Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="GET" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
Observe, the client uses GET value for attribute METHOD.

web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

String str = req.getMethod();


out.println("req.getMethod() : " + str);

out.close();
}
}
Output screen of ClientData.html with text field filled up. Anyhow, the
text field does not have any purpose here.

getme

The output screen when submit button is clicked.

ima

request.getProtocol() Method Example in Servlets:::


This method is defined in ServletRequest interface from javax.servlet
package and inherited by HttpServletRequest.

With this method, the servlet programmer can know what protocol (like
HTTP/1.0 or HTTP/1.1) is used by the client from HTML file to call the
servlet.

Let us see what Java API says about this method.

java.lang.String getProtocol():
Returns the name and version of the protocol the request uses in the form
protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP
servlets, the value returned is the same as the value of the CGI variable
SERVER_PROTOCOL.
The method getProtocol() returns a string, the protocol used in ACTION
attribute of of FORM tag used by the client to call the servlet.

Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="GET" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
Observe, the client uses GET value for attribute METHOD.

web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

String str = req.getProtocol();


out.println("req.getProtocol() : " + str);

out.close();
}
}
Output screen of ClientData.html with text field filled up. Anyhow, the
text field does not have any purpose here.

getme

The output screen when submit button is clicked.

ima

request.getScheme() Method Example in Servlets::::

This method is defined in ServletRequest interface from javax.servlet


package inherited by HttpServletRequest.

With this method, the servlet programmer can know what protocol (like
HTTP) is used by the client from HTML file to call the servlet.

Let us see what Java API says about this method.

public java.lang.String getScheme(): Returns the name of the scheme used


to make this request, for example, http, https, or ftp. Different schemes
have different rules for constructing URLs, as noted in RFC 1738.
The method getScheme() returns a string, the protocol used in ACTION
attribute of of FORM tag used by the client to call the servlet.

Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="GET" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
Observe, the client uses GET value for attribute METHOD.

web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

String str = req.getScheme();


out.println("req.getScheme() : " + str);

out.close();
}
}
Output screen of ClientData.html with text field filled up. Anyhow, the
text field does not have any purpose here.

getme

The output screen when submit button is clicked.

ima

To get the protocol with version, use getProtocol() method.

request.getServerPort() Method Example in Servlets:::

This method is defined in ServletRequest interface from javax.servlet


package and inherited by HttpServletRequest.

With this method, the servlet programmer can know what port number is
used by the client from HTML file to call the servlet.

Let us see what Java API says about this method.

int getServerPort():
Returns the port number to which the request was sent. It is the value of
the part after ":" in the Host header value, if any, or the server port
where the client connection was accepted on.
The method getServerPort() returns an integer value, the port number used
in ACTION attribute of of FORM tag used by the client to call the
servlet.

Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="GET" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
Observe, the client uses8888 port number in attribute ACTION.

web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

int portNumber = req.getServerPort();


out.println("req.getServerPort() : " + portNumber);

out.close();
}
}
Output screen of ClientData.html with text field filled up. Anyhow, the
text field does not have any purpose here.

getme

The output screen when submit button is clicked.

ima

request.isSecure() Method Example in Servlets:::

This method is defined in ServletRequest interface from javax.servlet


package and inherited by HttpServletRequest.

With this method, the servlet programmer can know whether the client is
using a secured protocol (HTTPS) or not while calling the servlet. If
secured protocol is used, this method returns true else false.

Let us see what Java API says about this method.


boolean isSecure(): Returns a boolean indicating whether this request was
made using a secure channel, such as HTTPS.
The method isSecure() returns a boolean value indicating whether the
client uses secured protocol or not to call the servlet.

Let us see the output by writing a program.

HTML Program: ClientData.html

<body>

<FORM METHOD="GET" ACTION="http://localhost:8888/india/jasmine">


Enter Your Name <input type="text" name="t1">
<input type="submit" value="Get Me">
</FORM>

</body>
Observe, the client uses http in attribute ACTION.

web.xml entry for ClientInformation servlet

<servlet>
<servlet-name>efgh</servlet-name>
<servlet-class>ClientInformation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>efgh</servlet-name>
<url-pattern>/jasmine</url-pattern>
</servlet-mapping>
Servelet Program: ClientInformation.java

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

public class ClientInformation extends HttpServlet


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

boolean b1 = req.isSecure();
out.println("req.isSecure() : " + b1);

out.close();
}
}

Output screen of ClientData.html with text field filled up. Anyhow, the
text field does not have any purpose here.

getme

The output screen when submit button is clicked.


ima

Because the client is using http and not https, the output screen above
shows a false value.

Note: Instead of http if https is used in the client program, the browser
tries to establish a secure connection with the server and if unable
throws ERR_SSL_PROTOCOL_ERROR with the message "Unable to make a secure
connection to the server. This may be a problem with the server or it may
be requiring a client authentication certificate that you don’t have."

You might also like