Thursday, July 28, 2016

Using Cookies


Using Cookies:

Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or program data subfolders. Cookies are created when you use your browser to visit a website that uses cookies to keep track of your movements within the site, help you resume where you left off, remember your registered login, theme selection, preferences, and other customization functions.The website stores a corresponding file(with same ID tag)to the one they set in your browser and in this file they can track and keep information on your movements within the site and any information you may have voluntarily given while visiting the website, such as email address.

There are two types of cookies: session cookies and persistent cookies. Session cookies are created temporarily in your browser's subfolder while you are visiting a website. Once you leave the site, the session cookie is deleted. On the other hand, persistent cookie files remain in your browser's subfolder and are activated again once you visit the website that created that particular cookie. A persistent cookie remains in the browser's subfolder for the duration period set within the cookie's file.

Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a form on a Web page is submitted. The example contains three files as summarized here

                File                                                             Description
AddCookie.html                             Allows a user to specify a value for the cookie named MyCookie.

AddCookieServlet.java                  Processes the submission of AddCookie.html.

GetCookiesServlet.java                 Displays cookie values.

The HTML source code for AddCookie.html is shown in the following listing. This page contains a text field in which a value can be entered. There is also a submit button on the page. When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST request.

AddCookie.html:

<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>

The source code for AddCookieServlet.java is shown in the following listing. It gets the value of the parameter named “data”. It then creates a Cookie object that has the name “MyCookie” and contains the value of the “data” parameter. The cookie is then added to the header of the HTTP response via the addCookie( ) method. A feedback message is then written to the browser.

AddCookieServlet.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet 
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException 
{
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
The source code for GetCookiesServlet.java is shown in the following listing. It invokes the getCookies( ) method to read any cookies that are included in the HTTP GET request. The names and values of these cookies are then written to the HTTP response. Observe that the getName( ) and getValue( ) methods are called to obtain this information.

GetCookiesServlet.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet 
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException 
{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
 {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +
"; value = " + value);
}
pw.close();
}
}

Compile the servlet and perform these steps:

1. Start Tomcat, if it is not already running.
2. Display AddCookie.htm in a browser.
3. Enter a value for MyCookie.
4. Submit the Web page.






After completing these steps you will observe that a feedback message is displayed by the browser.
Next, request the following URL via the browser:

http://localhost:9999/servlets/GCS




Observe that the name and value of the cookie are displayed in the browser. In this example, an expiration date is not explicitly assigned to the cookie via the setMaxAge( ) method of Cookie. Therefore, the cookie expires when the browser session ends. You can experiment by using setMaxAge( ) and observe that the cookie is then saved to the disk on the client machine.






Labels:

Handling Http Request & Responses in Servlets

Handling Http Request & Responses:

The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). The GET and POST requests are commonly used when handling form input.

Handling HTTP GET Requests:

The following programs are for servlets that handles HTTP GET request. The servlet is invoked
when a form on a Web page is submitted.
The example contains two files. A Web page is defined in Get.html and a servlet is defined in GetServlet.java. The HTML source code for Get.htm is shown in the following listing. It defines a form that contains a select element and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request.

Get.html:

<html>
<body>
<center>
<form name="Form1"
action="http://localhost:9999/servlet/GS">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

The source code for GetServlet.java is shown in the following listing. The doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.

GetServlet.java:


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}


Compile the servlet and perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the Web page in a browser.



3. Select a color.



4. Submit the Web page.


After completing these steps, the browser will display the response that is dynamically generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL that is sent to the Web server. Assume that the user selects the green option and submits the form. The URL sent from the browser to the server is 

                    http://localhost:9999/servlet/GS?color=Green

The characters to the right of the question mark are known as the query string.




Handling HTTP POST Requests:

 The servlet is invoked when a form on a Web page is submitted. The example contains two files. A
Web page is defined in Post.html and a servlet is defined in PostServlet.java.The HTML source code for Post.html is shown in the following listing. It isidentical toPost.html except that the method parameter for the form tag explicitly specifies that the POST method should be used, and the action parameter for the form tag specifies a different servlet.

Post.html:

<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:9999/servlet/PS">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

PostServlet.java:


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet 
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException 
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

Compile the servlet and perform the same steps as described in the previous section to test it.





Note: Parameters for an HTTP POST request are not included as part of the URL that
is sent to the Web server. In this example, the URL sent from the browser to the server

             http://localhost:9999/servlet/PS

The parameter names and values are sent in the body of the HTTP request.




Labels:

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:

Reading Servlet Parameters

Reading Servlet Parameters :

The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a client request. We will develop a servlet that illustrates their use. 
The example contains two files. 
A Web page is defined in sum.html and a servlet is defined in Add.java

sum.html:

<html>
<body>
<center>
<form name="Form1" method="post" 
action="Add">
<table>
<tr>
<td><B>Enter First Number</td>
<td><input type=textbox name="Enter First Number" size="25" value=""></td>
</tr>
<tr>
<td><B>Enter Second Number</td>
<td><input type=textbox name="Enter Second Number" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>


The HTML source code for sum.html defines a table that contains two labels and two text fields. One of the labels is Enter First Number,and the other is Enter Second Number. There is also a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to process the HTTP POST request.

Add.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Add
extends HttpServlet 
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException 
{
// Get print writer.
response.getContentType("text/html");
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
int sum=0;
while(e.hasMoreElements()) 
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
sum+=Integer.parseInt(pvalue);
pw.println(pvalue);
}
pw.println("Sum = "+sum);
pw.close();
}
}

The source code for Add.java contains  doPost( ) method is overridden to process client requests. The getParameterNames( ) method returns an enumeration of the parameter names. These are processed in a loop.we can see that the parameter name and value are output to the client. The parameter value is obtained via the getParameter( ) method.

after typing URL : http://localhost:9999/servlets/sum.html





Labels:

Reading Initialization parameters.

Reading Initialization parameters:

Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.
  1. <web-app>  
  2.   <servlet>  
  3.     ......  
  4.       
  5.     <init-param>  
  6.       <param-name>parametername</param-name>  
  7.       <param-value>parametervalue</param-value>  
  8.     </init-param>  
  9.     ......  
  10.   </servlet>  
  11. </web-app>  


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.

DemoServletInit.java
  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class DemoServletInit extends HttpServlet {  
  6. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  7.     throws ServletException, IOException {  
  8.   
  9.     response.setContentType("text/html");  
  10.     PrintWriter PW = response.getWriter();  
  11.       
  12.     ServletConfig config=getServletConfig();  
  13.     String name=config.getInitParameter("name");  
  14.     pw.print("Name is: "+driver);  
  15.           
  16.     pw.close();  
  17.     }  
  18.   
  19. }  
  20. Here web.xml is updated as following

<servlet>
    <servlet-name>D</servlet-name>
    <servlet-class>DemoServletInit</servlet-class>
<init-param>  
<param-name>name</param-name>  
<param-value>DiyaShirley</param-value>  
</init-param>  

</servlet>

<servlet-mapping>
    <servlet-name>D</servlet-name>
    <url-pattern>/Demo</url-pattern>
</servlet-mapping>

  1. after executing output displays like following:








Labels: