Wednesday, July 27, 2016

javax.servlet.http Package

javax.servlet.http Package:

The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet developers. We will see that its functionality makes it easy to build servlets that work with HTTP requests and responses.

The following  summarizes the core interfaces that are provided in this package:

                     Interface                                                                          Description

HttpServletRequest                                            Enables servlets to read data from an HTTP request.

HttpServletResponse                                          Enables servlets to write data to an HTTP response.

HttpSession                                                         Allows session data to be read and written.

HttpSessionBindingListener                             Informs an object that it is bound to or unbound
                                                                            from a session.

The following summarizes the core classes that are provided in this package. The most important of these is HttpServlet. Servlet developers typically extend this class in order to process HTTP requests.

Class                                                                  Description
Cookie                                                                   Allows state information to be stored on a client
                                                                               machine.

HttpServlet                                                           Provides methods to handle HTTP requests and
                                                                               responses.

HttpSessionEvent                                                Encapsulates a session-changed event.

HttpSessionBindingEvent                                  Indicates when a listener is bound to or unbound
                                                                              from a session value, or that a session attribute
                                                                              changed


HttpServletRequest Interface:

The HttpServletRequest interface is implemented by the server. It enables a servlet to obtain information about a client request. Several of its methods are shown below

Method                                                         Description

String getAuthType( )                                             Returns authentication scheme.

Cookie[ ] getCookies( )                                            Returns an array of the cookies in this  request.

long getDateHeader(String field)                          Returns the value of the date header field named
                                                                                  field.

String getHeader(String field)                              Returns the value of the header field named field.

Enumeration getHeaderNames( )                         Returns an enumeration of the header names.

int getIntHeader(String field)                                Returns the int equivalent of the header field                                                                                            named field.

String getMethod( )                                                 Returns the HTTP method for this request.

String getPathInfo( )                                               Returns any path information that is located after
                                                                             the servlet path and before a query string of the URL.

String getPathTranslated( )                                   Returns any path information that is located after                                                                                     the servlet path and before a query string of the                                                                                       URL after translating it to a real path.

String getQueryString( )                                        Returns any query string in the URL.

String getRemoteUser( )                                         Returns the name of the user who issued request.

String getRequestedSessionId( )                            Returns the ID of the session.

String getRequestURI( )                                        Returns the URI.

StringBuffer getRequestURL( )                            Returns the URL.

String getServletPath( )                                         Returns that part of the URL identifies the servlet.

HttpSession getSession( )                                       Returns the session for this request.If a session                                                                                         does not exist, one is created and then returned.

HttpSession getSession(boolean new)                  If new is true and no session exists, creates and                                                                                        returns a session for this request. Otherwise,                                                                                            returns the existing session for this request.

boolean isRequestedSessionIdFromCookie( )     Returns true if a cookie contains the session ID.
                                                                                 Otherwise, returns false.

boolean isRequestedSessionIdFromURL( )        Returns true if the URL contains the session ID.
                                                                                 Otherwise, returns false.

boolean isRequestedSessionIdValid( )                Returns true if the requested session ID
                                                                               is valid in the current session context.

HttpServletResponse Interface:

The HttpServletResponse interface is implemented by the server. It enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response. For example, SC_OK indicates that the HTTP request succeeded and SC_NOT_FOUND indicates that the requested resource is not available. Several methods of this interface are summarized below

Method                                                                     Description

void addCookie(Cookie cookie)                                      Adds cookie to the HTTP response.

boolean containsHeader(String field)                             Returns true if the HTTP response
                                                                                           header contains a field named field.

String encodeURL(String url)                                        Determines if the session ID must
                                                                                           be encoded in the URL identified
                                                                                           as url. If so, returns the modified
                                                                                           version of url. Otherwise, returns
                                                                                           url. All URLs generated by a
                                                                                           servlet should be processed by
                                                                                           this method.

String encodeRedirectURL(String url)                         Determines if the session ID
                                                                                           must be encoded in the URL
                                                                                           identified as url. If so, returns
                                                                                           the modified version of url.
                                                                                           Otherwise, returns url. All URLs
                                                                                            passed to sendRedirect( ) should
                                                                                            be processed by this method.


void sendError(int c)
throws IOException                                                         Sends the error code c to the client.

void sendError(int c, String s)
throws IOException                                                         Sends the error code c and messages to the                                                                                               client.
void sendRedirect(String url)
throws IOException                                                         Redirects the client to url.


HttpSession Interface:

The HttpSession interface is implemented by the server. It enables a servlet to read and write the state information that is associated with an HTTP session. Several of its methods are summarized below.  All of these methods throw an IllegalStateException if the session has already been invalidated.


Method                                                               Description

Object getAttribute(String attr)                      Returns the value associated with the                                                                                                       name passed in attr. Returns null if
                                                                            attr is not found.

Enumeration getAttributeNames( )                Returns an enumeration of the attribute
                                                                            names associated with the session.

long getCreationTime( )                                   Returns the time (in milliseconds since
                                                                            midnight, January 1, 1970, GMT) when
                                                                           this session was created.

String getId( )                                                    Returns the session ID.

long getLastAccessedTime( )                           Returns the time (in milliseconds since
                                                                            midnight, January 1, 1970, GMT) when
                                                                            the client last made a request for this session
.
void invalidate( )                                               Invalidates this session and removes it
                                                                            from the context.

boolean isNew( )                                                Returns true if the server created the
                                                                            session and it has not yet been accessed by the client.

void removeAttribute(String attr)                  Removes the attribute specified by attr from the                                                                                       session.
void setAttribute(String attr, Object val)     Associates the value passed in val with
                                                                          the attribute name passed in attr.

HttpSessionBindingListener Interface:

The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. The methods that are invoked when an object is bound or unbound are

               void valueBound(HttpSessionBindingEvent e)

               void valueUnbound(HttpSessionBindingEvent e)

Here, e is the event object that describes the binding.

Cookie Class:

The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. For example, assume that a user visits an online store. A cookie can save the user’s name, address, and other information. The user does not need to enter this data each time he or she visits the store.
A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP response that is sent to the browser.

The names and values of cookies are stored on the user’s machine. Some of the information that is saved for each cookie includes the following:

■ The name of the cookie
■ The value of the cookie
■ The expiration date of the cookie
■ The domain and path of the cookie
The expiration date determines when this cookie is deleted from the user’s machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the user’s machine. The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it is not.
There is one constructor for Cookie. It has the signature shown here:

                     Cookie(String name, String value)

Here, the name and value of the cookie are supplied as arguments to the constructor. The methods of the Cookie class are summarized below

Method                                                           Description

Object clone( )                                                                 Returns a copy of this object.

String getComment( )                                                     Returns the comment.

String getDomain( )                                                         Returns the domain.

int getMaxAge( )                                                              Returns the age (in seconds).

String getName( )                                                             Returns the name.

String getPath( )                                                               Returns the path.

boolean getSecure( )                                                         Returns true if the cookie must be sent using
                                                                                      only a secure protocol. Otherwise, returns false.
String getValue( )                                                             Returns the value.

int getVersion( )                                                               Returns the cookie protocol version. (Will be
                                                                                           0 or 1.)

void setComment(String c)                                            Sets the comment to c.

void setDomain(String d)                                               Sets the domain to d.

void setMaxAge(int secs)                                               Sets the maximum age of the cookie to secs.
                                                                                        This is the number of seconds after which the
                                                                                        cookie is deleted. Passing –1 causes the cookie
                                                                                        to be removed when the browser is terminated.

void setPath(String p)                                                   Sets the path to p.

void setSecure(boolean secure)                                     Sets the security flag to secure, which means
                                                                                          that cookies will be sent only when a secure
                                                                                          protocol is being used.

void setValue(String v)                                                   Sets the value to v.

void setVersion(int v)                                                 Sets the cookie protocol version to v, which will
                                                                                             be 0 or 1.



HttpServlet Class:

The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and process HTTP requests. The methods of the HttpServlet class are summarized below

Method                                                                       Description


void doDelete(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException                                   Performs an HTTP DELETE.

void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException                                   Performs an HTTP GET.

void doHead(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException                                   Performs an HTTP HEAD.

void doOptions(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException                                   Performs an HTTP OPTIONS.

void doPost(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException                                   Performs an HTTP POST.

void doPut(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException                                   Performs an HTTP PUT.

void doTrace(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException                                  Performs an HTTP TRACE.

long getLastModified(HttpServletRequest req)                   Returns the time (in milliseconds since                                                                                                     midnight,January 1, 1970, GMT) when                                                                                                     the requested resource waslast modified.

void service(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException                                 Called by the server when an HTTP                                                                                                           request arrives for this servlet. The                                                                                                           arguments provide access to the HTTP                                                                                                      request and response, respectively.



HttpSessionEvent Class:

HttpSessionEvent encapsulates session events. It extents EventObject and is generated
when a change occurs to the session. It defines this constructor:

                HttpSessionEvent(HttpSession session)

Here, session is the source of the event.

HttpSessionEvent defines one method, getSession( ), which is shown here:

                    HttpSession getSession( )

It returns the session in which the event occurred.


HttpSessionBindingEvent Class:

The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is bound to or unbound from a value in an HttpSession object. It is also generated when an attribute is bound or unbound. Here are its constructors:

         HttpSessionBindingEvent(HttpSession session, String name)

         HttpSessionBindingEvent(HttpSession session, String name, Object val)

Here, session is the source of the event and name is the name associated with the object that is being bound or unbound. If an attribute is being bound or unbound, its value is passed in val.
The getName( ) method obtains the name that is being bound or unbound. Its is shown here:

                     String getName( )

The getSession( ) method, shown next, obtains the session to which the listener is
being bound or unbound:

                     HttpSession getSession( )

The getValue( ) method obtains the value of the attribute that is being bound or
unbound. It is shown here:

                     Object getValue( )


Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home