Reading:  

Introduction to Servlet technology


Client requests

When web page is requested from browser, webserver sends information back as part of HTTP request header. 

Some of the header information which comes from browser side are: 

Header

Description

Accept

The header specifies MIME types that browser or other clients can handle.

Accept-Charset

The header specifies character sets browser can use to display information.

Accept-Encoding

The header specifies types of encodings that browser knows how to handle.

Accept-Language

The header specifies client's preferred languages in case servlet can produce results in more than one language.

Authorization

The header is used by client to identify themselves when accessing password-protected Web pages.

Connection

The header indicates the client can handle persistent HTTP connections.

Content-Length

The header is applicable only to POST requests and gives the size of POST data in bytes.

Cookie

The header returns cookies to servers that previously sent them to browser.

Host

The header specifies host and port given in original URL.

If-Modified-Since

The header indicates that client wants page only if it has been changed after specified date.

If-Unmodified-Since

The header is reverse of If-Modified-Since

User-Agent

The header identifies browser or other client making request from different content to different types of browsers.

 

Methods to read HTTP Header

Some of the following method of HTTP header are:

Method & Description

Cookie[] getCookies()


Returns an array containing all of Cookie objects client sent request.

Enumeration getAttributeNames()


Returns an Enumeration containing names of attributes request.

Enumeration getHeaderNames()


Returns an enumeration of all header names request contains.

Enumeration getParameterNames()


Returns an Enumeration of String objects containing names of parameters contained in request.

HttpSession getSession()


Returns current session associated with request

HttpSession getSession(boolean create)


Returns current HttpSession associated with request

Locale getLocale()


Returns preferred Locale that  client will accept content in.

Object getAttribute(String name)


Returns value of named attribute as an Object

ServletInputStream getInputStream()


Retrieves body of request as binary data using a ServletInputStream.

String getAuthType()


Returns name of authentication scheme used to protect servlet

String getCharacterEncoding()


Returns name of character encoding used in body of request.

String getContentType()


Returns MIME type of body of request

String getContextPath()


Returns portion of request URI .

String getHeader(String name)


Returns value of specified request header as a String.

String getMethod()


Returns name of HTTP method 

String getParameter(String name)


Returns value of a request parameter as a String

String getPathInfo()


Returns any extra path information associated with URL

String getProtocol()


Returns name and version of protocol request.

String getQueryString()


Returns query string that is contained in request URL

String getRemoteAddr()


Returns Internet Protocol (IP) address of client which sent request.

String getRemoteHost()


Returns fully qualified name of client which sent request.

String getRemoteUser()


Returns login of user making this request

String getRequestURI()


Returns part of this request's URL

String getRequestedSessionId()


Returns session ID specified by client.

String getServletPath()


Returns part of this request's URL

String[] getParameterValues(String name)


Returns an array of String objects containing all values given request parameter

boolean isSecure()


Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

int getContentLength()


Returns length in bytes

int getIntHeader(String name)


Returns value of specified request header as an int.

int getServerPort()


Returns port number on which this request was received.

 

HTTP Header Request Example 

Below example use getHeaderNames() method of HttpServletRequest to read HTTP header information. The method returns an Enumeration which contains header information associated with current HTTP request.

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import util.CookieFilter;
import util.HTMLFilter;

public class RequestHeaderExample extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final ResourceBundle RB = ResourceBundle.getBundle("LocalStrings");

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html><html>");
        out.println("<head>");
        out.println("<meta charset=\"UTF-8\" />");

        String title = RB.getString("requestheader.title");
        out.println("<title>" + title + "</title>");
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");

        out.println("<a href=\"../reqheaders.html\">");
        out.println("<img src=\"../images/code.gif\" height=24 " +
                    "width=24 align=right border=0 alt=\"view code\"></a>");
        out.println("<a href=\"../index.html\">");
        out.println("<img src=\"../images/return.gif\" height=24 " +
                    "width=24 align=right border=0 alt=\"return\"></a>");

        out.println("<h3>" + title + "</h3>");
        out.println("<table border=0>");
        Enumeration<String> e = request.getHeaderNames();
        while (e.hasMoreElements()) {
            String headerName = e.nextElement();
            String headerValue = request.getHeader(headerName);
            out.println("<tr><td bgcolor=\"#CCCCCC\">");
            out.println(HTMLFilter.filter(headerName));
            out.println("</td><td>");
            if (headerName.toLowerCase(Locale.ENGLISH).contains("cookie")) {
                HttpSession session = request.getSession(false);
                String sessionId = null;
                if (session != null) {
                    sessionId = session.getId();
                }
                out.println(HTMLFilter.filter(CookieFilter.filter(headerValue, sessionId)));
            } else {
                out.println(HTMLFilter.filter(headerValue));
            }
            out.println("</td></tr>");
        }
        out.println("</table>");
    }

    @Override
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        doGet(request, response);
    }

}
 

When you request this resource from URL http://localhost:8080/examples/servlets, below is what header information you will get

HTTP Headers servlet requests

 

Description

This guide introduces Servlet technology and we will cover below topics

  1. What is a Servlet?
  2. Initial Setup
  3. Life Cycle
  4. Various Examples
  5. Client Request
  6. Server Response
  7. Http Status Codes
  8. Writing Filters
  9. Exception Handling
  10. Cookies Handling
  11. Session Tracking
  12. Database Access
  13. Packaging
  14. Internationalization

This is to the point introduction to the topic to get you started

 



Prerequisites

Working knowledge of Core Java is essential

Audience

Beginner to Java Servlet technology or students looking to brush up their skills quickly

Learning Objectives

Learn Java Servlets

Author: Subject Coach
Added on: 2nd May 2015

You must be logged in as Student to ask a Question.

None just yet!