dineshonjava

ServletContext Interface

An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.

If any information is shared to many servlet, it is better to provide it from the web.xml file using the element.

Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet. Thus it removes maintenance problem.

Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:

  • The object of ServletContext provides an interface between the container and servlet.
  • The ServletContext object can be used to get configuration information from the web.xml file.
  • The ServletContext object can be used to set, get or remove attribute from the web.xml file.
  • The ServletContext object can be used to provide inter-application communication.


MethodsDescription
Object getAttribute(String name)returns the container attribute with the given name, or null if there is no attribute by that name.
String getInitParameter(String name)returns parameter value for the specified parameter name, or null if the parameter does not exist
Enumeration getInitParameterNames()returns the names of the context's initialization parameters as an Enumeration of String objects
void setAttribute(String name,Object obj)set an object with the given attribute name in the application scope
void removeAttribute(String name)removes the attribute with the specified name from the application context


ServletContext Interface

How to get the object of ServletContext
ServletContext app = getServletContext();
ServletContext app = getServletConfig().getServletContext(); 


How to get the object of ServletContext interface
getServletContext() method of ServletConfig interface returns the object of ServletContext.
    getServletContext() method of GenericServlet class returns the object of ServletContext.
Syntax of getServletContext() method
public ServletContext getServletContext()  
Example of getServletContext() method
//We can get the ServletContext object from ServletConfig object  
    ServletContext application=getServletConfig().getServletContext();  
      
    //Another convenient way to get the ServletContext object  
    ServletContext application=getServletContext();  

Example of ServletContext to get the initialization parameter
In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don't need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element. Let's see the simple example:
HelloServlet.java
import java.io.*;  
    import javax.servlet.*;  
    import javax.servlet.http.*;  
      
      
    public class HelloServlet extends HttpServlet{  
    public void doGet(HttpServletRequest req,HttpServletResponse res)  
    throws ServletException,IOException  
    {  
    res.setContentType("text/html");  
    PrintWriter pw=res.getWriter();  
      
    //creating ServletContext object  
    ServletContext context=getServletContext();  
      
    //Getting the value of the initialization parameter and printing it  
    String driverName=context.getInitParameter("driverName");  
    pw.println("driver name is="+driverName);  
      
    pw.close();  
      
    }
}  

web.xml

<web-app>  
      
    <servlet>  
    <servlet-name>HelloServlet</servlet-name>  
    <servlet-class>HelloServlet</servlet-class>  
    </servlet>  
      
    <context-param>  
    <param-name>driverName</param-name>  
    <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
    </context-param>  
      
    <servlet-mapping>  
    <servlet-name>HelloServlet</servlet-name>  
    <url-pattern>/context</url-pattern>  
    </servlet-mapping>  
      
    </web-app> 

Example of ServletContext to get all the initialization parameters
In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the getInitParameterNames() method in the servlet class.

HelloServlet.java
import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class DemoServlet extends HttpServlet{  
public void doGet(HttpServletRequest req,HttpServletResponse res)  
throws ServletException,IOException  
{  
res.setContentType("text/html");  
PrintWriter out=res.getWriter();  
  
ServletContext context=getServletContext();  
Enumeration<string> e=context.getInitParameterNames();  
      
String str="";  
while(e.hasMoreElements()){  
    str=e.nextElement();  
    out.print("<br> "+context.getInitParameter(str));  
}  
}
}  

web.xml
<web-app>  
      
    <servlet>  
    <servlet-name>HelloServlet</servlet-name>  
    <servlet-class>HelloServlet</servlet-class>  
    </servlet>  
      
    <context-param>  
    <param-name>driverName</param-name>  
    <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
    </context-param>  
      
    <context-param>  
    <param-name>name</param-name>  
    <param-value>dinesh</param-value>  
    </context-param>  
      
    <context-param>  
    <param-name>email</param-name>  
    <param-value>admin@dineshonjava.com</param-value>  
    </context-param>  
      
    <servlet-mapping>  
    <servlet-name>HelloServlet</servlet-name>  
    <url-pattern>/context</url-pattern>  
    </servlet-mapping>  
      
    </web-app>  



<<Previous <<   || Index ||   >>Next >>



ServletConfig Interface

ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.

An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file.

If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.

Advantage of ServletConfig

The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the web.xml file.

Methods of ServletConfig interface
  • public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  • public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.
  • public String getServletName():Returns the name of the servlet.
  • public ServletContext getServletContext():Returns an object of ServletContext.


How to initialize a servlet inside web.xml
ServletConfig Interface
Inside servlet class:
ServletConfig config=getServletConfig();  
String email=config.getInitParameter("email"); 
Example of ServletConfig to get initialization parameter

In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the servlet.

HelloServlet.java
import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class HelloServlet extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
      
    ServletConfig config=getServletConfig();  
    String email=config.getInitParameter("email");  
    out.print("Email is: "+eamil);  
          
    out.close();  
    }  
  
}  

web.xml
<web-app>  
  
<servlet>  
<servlet-name>HelloServlet</servlet-name>  
<servlet-class>HelloServlet</servlet-class>  
  
<init-param>  
<param-name>email</param-name>  
<param-value>admin@dineshonjava.com</param-value>  
</init-param>  
  
</servlet>  
  
<servlet-mapping>  
<servlet-name>HelloServlet</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>  
  
</web-app>  

Example of ServletConfig to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet.

HelloServlet.java
import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.Enumeration;  
  
import javax.servlet.ServletConfig;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
  
public class HelloServlet extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
      
    ServletConfig config=getServletConfig();  
    Enumeration<String> e=config.getInitParameterNames();  
          
    String str="";  
    while(e.hasMoreElements()){  
    str=e.nextElement();  
    out.print("<br>Name: "+str);  
    out.print(" value: "+config.getInitParameter(str));  
    }  
          
    out.close();  
}  
  
}  
  
web.xml
<web-app>  
  
<servlet>  
<servlet-name>HelloServlet</servlet-name>  
<servlet-class>HelloServlet</servlet-class>  
  
<init-param>  
<param-name>name</param-name>  
<param-value>dinesh</param-value>  
</init-param>  
  
<init-param>  
<param-name>email</param-name>  
<param-value>admin@dineshonjava.com</param-value>  
</init-param>  
  
</servlet>  
  
<servlet-mapping>  
<servlet-name>HelloServlet</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>  
  
</web-app>  


<<Previous <<   || Index ||   >>Next >>



Send Redirect in Servlet

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server.

In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not. If not then the servlet decides that the request can be handle by other servlet or jsp. Then the servlet calls the sendRedirect() method of the response object and sends back the response to the browser along with the status code. Then the browser sees the status code and look for that servlet which can now handle the request. Again the browser makes a new request, but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser. In all this process the client is unaware of the processing.

The output of the program is given below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Redirecting the page</title>
</head>
<body>
 <form action = "/ServletProject/SendRedirect" method = "post">
 <tr>
  <td>Enter your name :</td>
  <td><input type = "text" name = "username"></td>
 </tr><br>
 <tr>
  <td>Enter your password :</td>
  <td><input type = "password" name = "password"></td>
 </tr><br>
 <tr>
  <td><input type = "submit" name = "submit"></td>
 </tr>
 </form>
</body>
</html>


import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendRedirect extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public SendRedirect() {
super();
} 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
if(name.equals("dinesh")&& password.equals("swwety"))
{
response.sendRedirect("/ServletProject/ValidUser");
}
else
{
pw.println("u r not a valid user");
}
} 
}
Difference between forward() and sendRedirect() method

There are many differences between the forward() method of RequestDispatcher and sendRedirect() method of HttpServletResponse interface. They are given below:


forward() methodsendRedirect() method
The forward() method works at server side.The sendRedirect() method works at client side.
It sends the same request and response objects to another servlet.It always sends a new request.
It can work within the server only.It can be used within and outside the server.
Example: request.getRequestDispacher("servlet2").forward(request,response);Example: response.sendRedirect("servlet2");

MySearcher.java
import java.io.IOException;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
public class MySearcher extends HttpServlet {  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
  
        String name=request.getParameter("name");  
        response.sendRedirect("https://www.google.co.in/#q="+name);  
    }  
}  
index.html
<!DOCTYPE html>  
<html>  
<head>  
<meta charset="ISO-8859-1">  
<title>sendRedirect example</title>  
</head>  
<body>  
  
  
<form action="MySearcher">  
<input type="text" name="name">  
<input type="submit" value="Google Search">  
</form>  
  
</body>  
</html>  






<<Previous <<   || Index ||   >>Next >>







HttpSession interface

The HttpSession object represents a user session. A user session contains information about the user across multiple HTTP requests.

When a user enters your site for the first time, the user is given a unique ID to identify his session by. This ID is typically stored in a cookie or in a request parameter.

Here is how you access the session object:
  • public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.
  • public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.

protected void doPost(HttpServletRequest request,
    HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
}
You can store values in the session object, and retrieve them later. First, let's see how you can store values in the session object:
session.setAttribute("userName", "theUserName");


To read the value again, you do this:
String userName = (String) session.getAttribute("userName");
Values stored in the session object are stored in the memory of the servlet container.

An object of HttpSession can be used to perform two tasks:
  1. bind objects
  2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
HttpSession interface

Commonly used methods of HttpSession interface
  1. public String getId(): Returns a string containing the unique identifier value.
  2. public long getCreationTime(): Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  3. public long getLastAccessedTime(): Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
  4. public void invalidate(): Invalidates this session then unbinds any objects bound to it.

Sessions and Clusters

If you have an architecture with 2 web servers in a cluster, keep in mind that values stored in the session object of one server, may not be available in the session object on the other server. So, if a user's requests are divided evenly between the two servers, sometimes session values may be missing.

The solution to this problem would be one of:
  1. Do not use session attributes.
  2. Use a session database, into which session attributes are written, and from which it is read.
  3. Use sticky session, where a user is always sent to the same server, throughout the whole session.




<<Previous <<   || Index ||   >>Next >>


RequestDispatcher Interface

In this tutorial you will learn how to use forward() method of RequestDispatcher in Servlet

forward() method of RequestDispatcher forwards the request made by the client by the the resource (any of them servlet , jsp, html, etc.) on the server without including the content of the requested resource.

syntax :
void forward(request, response) throws ServletException, IOException
The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.
Methods of RequestDispatcher interface
The RequestDispatcher interface provides two methods. They are:
  1. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.


    HttpSession interface
    RequestDispatcher Interface
    As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.
  2. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
    As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client.
Getting the object of RequestDispatcher
The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher

Syntax of getRequestDispatcher method:

public RequestDispatcher getRequestDispatcher(String resource);  
Example of using getRequestDispatcher method
RequestDispatcher rd=request.getRequestDispatcher("/welcomeServlet");  
  //welcomeServlet is the url-pattern of the second servlet  
  rd.forward(request, response);//method may be include or forward  

Example of RequestDispatcher interface

In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are checking for hard coded information. But you can check it to the database also that we will see in the development chapter.

1. :login.html file for getting input from the user.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form method="get" action="loginServlet">
<p>Enter your info in the following text boxes</p>
Enter your name <input type="text" name="text1"/><br>
Enter your password <input type="password" name="text2"/><br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
2. LoginServlet.java file: a servlet class for processing the response. If password is servlet, it will forward the request to the welcome servlet.
import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class LoginSevlet extends HttpServlet {  
  
public void doPost(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String userName=request.getParameter("userName");  
    String userPass=request.getParameter("userPass");  
          
    if(userPass.equals("sweety")){  
        RequestDispatcher rd=request.getRequestDispatcher("welcomeServlet");  
        rd.forward(request, response);  
    }  
    else{  
        out.print("Sorry User Name or Password Error!");  
        RequestDispatcher rd=request.getRequestDispatcher("/login.html");  
        rd.include(request, response);  
                      
        }  
    }  
  
}  
3. WelcomeServlet.java file: a servlet class for displaying the welcome message.
import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class WelcomeServlet extends HttpServlet {  
  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String userName=request.getParameter("userName");  
    out.print("Welcome "+userName);  
    }  
  
}  
4. web.xml file: a deployment descriptor file that contains the information about the servlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>servletRequestDispatcher</display-name>
<servlet>  
    <servlet-name>loginServlet</servlet-name>  
    <servlet-class>LoginServlet</servlet-class>  
  </servlet>  
  <servlet>  
    <servlet-name>welcomeServlet</servlet-name>  
    <servlet-class>WelcomeServlet</servlet-class>  
  </servlet>  
  
  
  <servlet-mapping>  
    <servlet-name>loginServlet</servlet-name>  
    <url-pattern>/loginServlet</url-pattern>  
  </servlet-mapping>  
  <servlet-mapping>  
    <servlet-name>welcomeServlet</servlet-name>  
    <url-pattern>/welcomeServlet</url-pattern>  
  </servlet-mapping>  
  
  <welcome-file-list>  
   <welcome-file>login.html</welcome-file>  
  </welcome-file-list>  

</web-app>
RequestDispatcher

Now let us start tomcat server using C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\bin\startup.bat (on windows) or /bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/login.html in browser's address box. If everything goes fine, you would get following result:

RequestDispatcher

With wrong password it request dispatched to again login form.

RequestDispatcher

With right user name and password.

RequestDispatcher




<<Previous <<   || Index ||   >>Next >>


HttpResponse Servlet

The HttpServlet class request processing methods take two parameters.
  1. javax.servlet.http.HttpRequest
  2. javax.servlet.http.HttpResponse
The HttpServletResponse object generates a response to return to the requesting client. Its methods allow you to set the response header and the response body.

The first line of the Response header (response.setContentType("text/html");) identifies the MIME type of the response. The following three lines are often placed in servlet code to prevent Web browsers and proxy servers from caching dynamically-generated Web pages. If you want your dynamic Web page to be cached, remove these three lines of code.

The response object also has the getWriter() method to return a PrintWriter object. The print() and println() methods of the PrintWriter object write the servlet response back to the client.

For instance, here is the signature of the HttpServlet.doGet() method:
protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
      throws ServletException, IOException {

}


In this text I will look at the HttpResponse object.

The purpose of the HttpResponse object is to represent the HTTP response your web application sends back to the browser, in response to the HTTP request the browser send to your web application.

Methods to Set HTTP Response Header:

There are following methods which can be used to set HTTP response header in your servlet program. These methods are available with HttpServletResponse object.

1 String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
2 String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
3 boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.
4 boolean isCommitted()
Returns a boolean indicating if the response has been committed.
5 void addCookie(Cookie cookie)
Adds the specified cookie to the response.
6 void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.
7 void addHeader(String name, String value)
Adds a response header with the given name and value.
8 void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
9 void flushBuffer()
Forces any content in the buffer to be written to the client.
10 void reset()
Clears any data that exists in the buffer as well as the status code and headers.
11 void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code.
12 void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
13 void sendError(int sc, String msg)
Sends an error response to the client using the specified status.
14 void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL.
15 void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
16 void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.
17 void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.
18 void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet.
19 void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.
20 void setHeader(String name, String value)
Sets a response header with the given name and value.
21 void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
22 void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet.
23 void setStatus(int sc)
Sets the status code for this response.

The HttpResponse object has a lot of methods, so I will just cover the most commonly used here. The rest you can read about in the JavaDoc, if you are interested. The parts I will cover are:
  1. Writing HTML
  2. Headers
  3. Content-Type
  4. Writing Text
  5. Content-Length
  6. Writing Binary Data
  7. Redirecting to a Different URL
  8. Writing HTML

To send HTML back to the browser, you have to obtain the a PrintWriter from the HttpResponse object. Here is how:
PrintWriter writer = response.getWriter();
writer.write("<html><body>GET/POST response</body></html>"); 

Headers

Just like the request object, the HttpRequest can contain HTTP headers. Headers must be set before any data is written to the response. You set a header on the response object like this:
response.setHeader("Header-Name", "Header Value");
As you can see, a response header is a name, value pair.

Content-Type

The Content-Type header is a response header that tells the browser the type of the content you are sending back to it. For instance, the content type for HTML is text/html. Similarly, if what you send back to the browser is plain text, you use the content type text/plain.

Here is how you set the Content-Type header on the HttpResponse object:
response.setHeader("Content-Type", "text/html");

Writing Text

You can write text back to the browser instead of HTML, like this:
response.setHeader("Content-Type", "text/plain");

PrintWriter writer = response.getWriter();
writer.write("This is just plain text");
First the Content-Type header is set to text/plain. Then a plain text string is written to the writer obtained from the response object.

Content-Length

The Content-Length header tells the browser how many bytes your servlet is sending back. If you are sending binary data back you need to set the content length header. Here is how:
response.setHeader("Content-Length", "31642");

Writing Binary Data

You can also write binary data back to the browser instead of text. For instance, you can send an image back, a PDF file or a Flash file or something like that.

Again, you will first have to set the Content-Type header to the type matching the data you are sending back. For instance, the content type for a PNG image is image/png.

You can search for "mime types" in your favourite search engine to find a list of mime types (content types), so you can find the mime type for the content you are sending back.

In order to write binary data back to the browser you cannot use the Writer obtained from response.getWriter(). Afterall, Writer's are intended for text.

Instead you have to use the OutputStream obtained from the response.getOutputStream() method. Here is how:
OutputStream outputStream = response.getOutputStream();
outputStream.write(...);
Redirecting to a Different URL

You can redirect the browser to a different URL from your servlet. You cannot send any data back to the browser when redirecting. Here is how you redirect:
response.sendRedirect("http://www.dineshonjava.com");
Create the HTTP response

After the servlet request code, add the response code:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletSample extends HttpServlet
{

   public void doGet (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
   {

      Enumeration keys;
      String key;
      String myName = "";
      keys = request.getParameterNames();
      while (keys.hasMoreElements())
      {
         key = (String) keys.nextElement();
         if (key.equalsIgnoreCase("myName")) myName = request.getParameter(key);
      }
      System.out.println("Name = ");
      if (myName == "") myName = "Hello";

      response.setContentType("text/html"); 
      response.setHeader("Pragma", "No-cache");
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache");
   
      PrintWriter out = response.getWriter(); 
      out.println("<html>");  
      out.println("<head><title>Just a basic servlet</title></head>");
      out.println("<body>");
      out.println("<h1>Just a basic servlet</h1>");
      out.println ("<p>" + myName +  ", this is a very basic servlet.");
      out.println("</body></html>");    
      out.flush();

   }
}

<<Previous <<   || Index ||   >>Next >>


HttpRequest

The HttpServlet class request processing methods take two parameters.
  1. javax.servlet.http.HttpRequest
  2. javax.servlet.http.HttpResponse
For instance, here is the signature of the HttpServlet.doGet() method:
protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
      throws ServletException, IOException {

}
The purpose of the HttpRequest object is to represent the HTTP request a browser sends to your web application. Thus, anything the browser may send, is accessible via the HttpRequest.

The HttpRequest object has a lot of methods, so I will just cover the most commonly used here.
  1. Parameters
  2. Headers
  3. InputStream
  4. Session
  5. ServletContext


Parameters
The request parameters are parameters that are sent from the browser along with the request. Request parameters are typically sent as part of the URL (in the "query string"), or as part of the body of an HTTP request. For instance:
http://www.dineshonjava.com/somePage.html?param1=hello&m2=world

Notice the "query string" part of the URL: ?param1=hello&m2=world This part contains two parameters with parameter values:

param1=hello
param2=world

You can access these parameters from the HttpRequest object like this:
protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
      throws ServletException, IOException {

    String param1 = request.getParameter("param1");
    String param2 = request.getParameter("param2");

}
You would use the same code, if the request parameters were sent in the body part of the HTTP request. If no parameter exists with the given name, null is returned.

In general, if the browser sends an HTTP GET request, the parameters are included in the query string in the URL. If the browser sends an HTTP POST request, the parameters are included in the body part of the HTTP request.

Headers
The request headers are name, value pairs sent by the browser along with the HTTP request. The request headers contain information about e.g. what browser software is being used, what file types the browser is capable of receiving etc. In short, at lot of meta data around the HTTP request.

You can access the request headers from the HttpRequest object like this:
String contentLength = request.getHeader("Content-Length");    
This example reads the Content-Length header sent by the browser.

The Content-Length header contains the number of bytes sent in the HTTP request body, in case the browser sends an HTTP POST request. If the browser sends an HTTP GET request, the Content-Length header is not used, and the above code will return null.

In general, If no header exists with the name passed to getHeader(), null is returned.
InputStream
If the browser sends an HTTP POST request, request parameters and other potential data is sent to the server in the HTTP request body. It doesn't have to be request parameters that is sent in the HTTP request body. It could be pretty much any data, like a file or a SOAP request (web service request).

To give you access to the request body of an HTTP POST request, you can obtain an InputStream pointing to the HTTP request body. Here is how it is done:
InputStream requestBodyInput = request.getInputStream();    
NOTE: You will have to call this method before calling any getParameter() method, because calling the getParameter() method on an HTTP POST request will cause the servlet engine to parse the HTTP request body for parameters. Once parsed, you cannot access the body as a raw stream of bytes anymore.

What you do with the data read from the InputStream is up to you. The servlet engine does not help you parse or interprete that data. You just get it raw.
Session

It is possible to obtain the session object from the HttpRequest object too.

The session object can hold information about a given user, between requests. So, if you set an object into the session object during one request, it will be available for you to read during any subsequent requests within the same session time scope.

Here is how you access the session object from the HttpRequest object:
HttpSession session = request.getSession();

ServletContext
You can access the ServletContext object from the HttpRequest object too. The ServletContext contains meta information about the web application. For instance, you can access context parameters set in the web.xml file, you can forward the request to other servlets, and you can store application wide parameters in the ServletContext too.

Here is how you access the ServletContext object from the HttpRequest object:
ServletContext context = request.getSession().getServletContext();            
As you can see, you have to first get the session object, to get access to the ServletContext object.


<<Previous <<   || Index ||   >>Next >>



Class HttpServlet

The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc. The javax.servlet.http.HttpServlet class is a slightly more advanced base class than the GenericServlet.

The HttpServlet class reads the HTTP request, and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method.

Similar to the GenericServlet class this class is also abstract and we extend it make the SubClass work like a servlet. The SubClass must override one of the following methods:-
  • doGet() - for HTTP GET requests
  • doPost() - for HTTP POST requests
  • doDelete() - for HTTP DELETE requests
  • doPut() - for HTTP PUT requests
  • init()/destroy() - for managing the resources during the life of the servlet
  • getServletInfo() - this method is used by the servlet to provide information about itself



service() method of HTTPServlet class is not abstract as was the case in the GenericServlet class and there is hardly any need to override that method as by default it contains the capability of deciding the type of the HTTP request it receives and based on that it calls the specific method to do the needful. For example, if an HTTP GET request calls the servlet then the service nethod of the HTTPServlet class determines the request type (it'll find it to be GET) and subsequently calls doGet() method to serve the request.



Methods of HttpServlet class


  • public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.
  • protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.
  • protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container.
  • protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container.
  • protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container.
  • protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container.
  • protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by the web container.
  • protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is invoked by the web container.
  • protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is invoked by the web container.
  • protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was last modified since midnight January 1, 1970 GMT.

To respond to e.g. HTTP GET requests only, you will extend the HttpServlet class, and override the doGet() method only. Here is an example:
public class SimpleHttpServlet extends HttpServlet {

  protected void doGet( HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException {

      response.getWriter().write("<html><body>GET response</body></html>");
  }
}
If you want to handle both GET and POST request from a given servlet, you can override both methods, and have one call the other. Here is how:
public class SimpleHttpServlet extends HttpServlet {

  protected void doGet( HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException {

      doPost(request, response);
  }

  protected void doPost( HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException {

      response.getWriter().write("GET/POST response");
    }
}

I would recommend you to use the HttpServlet instead of the GenericServlet whenever possible. HttpServlet is easier to work with, and has more convenience methods than GenericServlet.

<<Previous <<   || Index ||   >>Next >>