Friday, June 12, 2015

Improve knowledge about Servlets - Cookies Handling

Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
  • Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  • Browser stores this information on local machine for future use.
  • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
This chapter will teach you how to set or reset cookies, how to access them and how to delete them.

The Anatomy of a Cookie:

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; 
                 path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A servlet will then have access to the cookie through the request methodrequest.getCookies() which returns an array of Cookie objects.

Servlet Cookies Methods:

Following is the list of useful methods which you can use while manipulating cookies in servlet.
S.N.Method & Description
1
public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example tutorialspoint.com.
2
public String getDomain()
This method gets the domain to which cookie applies, for example tutorialspoint.com.
3
public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.
4
public int getMaxAge()
This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
5
public String getName()
This method returns the name of the cookie. The name cannot be changed after creation.
6
public void setValue(String newValue)
This method sets the value associated with the cookie.
7
public String getValue()
This method gets the value associated with the cookie.
8
public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.
9
public String getPath()
This method gets the path to which this cookie applies.
10
public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.
11
public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.
12
public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

Setting Cookies with Servlet:

Setting cookies with servlet involves three steps:
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of the following characters:
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24); 
(3) Sending the Cookie into the HTTP response headers: You use response.addCookieto add cookies in the HTTP response header as follows:
response.addCookie(cookie);

Example:

Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
 
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Create cookies for first and last names.      
      Cookie firstName = new Cookie("first_name",
                      request.getParameter("first_name"));
      Cookie lastName = new Cookie("last_name",
                      request.getParameter("last_name"));

      // Set expiry date after 24 Hrs for both the cookies.
      firstName.setMaxAge(60*60*24); 
      lastName.setMaxAge(60*60*24); 

      // Add both the cookies in the response header.
      response.addCookie( firstName );
      response.addCookie( lastName );

      // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "Setting Cookies Example";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>First Name</b>: "
                + request.getParameter("first_name") + "\n" +
                "  <li><b>Last Name</b>: "
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
}
Compile above servlet HelloForm and create appropriate entry in web.xml file and finally try following HTML page to call servlet.
 
<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Keep above HTML content in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT directory. When you would accesshttp://localhost:8080/Hello.htm, here is the actual output of the above form.
First Name:  
Last Name:  
Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button.
Next section would explain you how you would access these cookies back in your web application.

Reading Cookies with Servlet:

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

Example:

Let us read cookies which we have set in previous example:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class ReadCookies extends HttpServlet {
 
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      Cookie cookie = null;
   Cookie[] cookies = null;
      // Get an array of Cookies associated with this domain
      cookies = request.getCookies();
      
   // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "Reading Cookies Example";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" );
      if( cookies != null ){
         out.println("<h2> Found Cookies Name and Value</h2>");
         for (int i = 0; i < cookies.length; i++){
            cookie = cookies[i];
            out.print("Name : " + cookie.getName( ) + ",  ");
            out.print("Value: " + cookie.getValue( )+" <br/>");
         }
      }else{
          out.println(
            "<h2>No cookies founds</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}
Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would have set first_name cookie as "John" and last_name cookie as "Player" then runninghttp://localhost:8080/ReadCookies would display the following result:

Found Cookies Name and Value

Name : first_name, Value: John Name : last_name, Value: Player

Delete Cookies with Servlet:

To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:
  • Read an already exsiting cookie and store it in Cookie object.
  • Set cookie age as zero using setMaxAge() method to delete an existing cookie.
  • Add this cookie back into response header.

Example:

Following example would delete and existing cookie named "first_name" and when you would run ReadCookies servlet next time it would return null value for first_name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Extend HttpServlet class
public class DeleteCookies extends HttpServlet {
 
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      Cookie cookie = null;
   Cookie[] cookies = null;
      // Get an array of Cookies associated with this domain
      cookies = request.getCookies();
      
   // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "Delete Cookies Example";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" );
       if( cookies != null ){
         out.println("<h2> Cookies Name and Value</h2>");
         for (int i = 0; i < cookies.length; i++){
            cookie = cookies[i];
            if((cookie.getName( )).compareTo("first_name") == 0 ){
                 cookie.setMaxAge(0);
                 response.addCookie(cookie);
                 out.print("Deleted cookie : " + 
                              cookie.getName( ) + "<br/>");
            }
            out.print("Name : " + cookie.getName( ) + ",  ");
            out.print("Value: " + cookie.getValue( )+" <br/>");
         }
      }else{
          out.println(
            "<h2>No cookies founds</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}
Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running http://localhost:8080/DeleteCookies would display the following result:

Cookies Name and Value

Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as follows:

Found Cookies Name and Value

Name : last_name, Value: Player

Thursday, June 11, 2015

Created permission function for view PDF file in DMS project

Our  project is Document Management System. A document management system (DMS) is a system (based on computer programs in the case of the management of digital documents) used to track, manage and store documents. Most are capable of keeping a record of the various versions created and modified by different users (history tracking). The term has some overlap with the concepts of content management systems. It is often viewed as a component of enterprise content management (ECM) systems and related to digital asset management, document imaging, workflow systems and records management systems. So I also assign to this project in my supervisor. So I also created some parts in this project. I created permission function for view PDF file for this project.All steps are mention below.











































Tuesday, June 9, 2015

Improve knowledge about Servlets - Exception Handling

When a servlet throws an exception, the web container searches the configurations in web.xml that use the exception-type element for a match with the thrown exception type.
You would have to use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes.

web.xml Configuration:

Consider, you have an ErrorHandler servlet which would be called whenever there is any defined exception or error. Following would be the entry created in web.xml.
<!-- servlet definition -->
<servlet>
        <servlet-name>ErrorHandler</servlet-name>
        <servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
        <servlet-name>ErrorHandler</servlet-name>
        <url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>

<!-- error-code related error pages -->
<error-page>
    <error-code>404</error-code>
    <location>/ErrorHandler</location>
</error-page>
<error-page>
    <error-code>403</error-code>
    <location>/ErrorHandler</location>
</error-page>

<!-- exception-type related error pages -->
<error-page>
    <exception-type>
          javax.servlet.ServletException
    </exception-type >
    <location>/ErrorHandler</location>
</error-page>

<error-page>
    <exception-type>java.io.IOException</exception-type >
    <location>/ErrorHandler</location>
</error-page>
If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception:
<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page>
Following are the points to be noted about above web.xml for Exception Handling:
  • The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml.
  • If there is any error with status code either 404 ( Not Found) or 403 ( Forbidden ), then ErrorHandler servlet would be called.
  • If the web application throws either ServletException or IOException, then the web container invokes the /ErrorHandler servlet.
  • You can define different Error Handlers to handle different type of errors or exceptions. Above example is very much generic and hope it serve the purpose to explain you the basic concept.

Request Attributes - Errors/Exceptions:

Following is the list of request attributes that an error-handling servlet can access to analyse the nature of error/exception.
S.N.Attribute & Description
1
javax.servlet.error.status_code
This attribute give status code which can be stored and analysed after storing in a java.lang.Integer data type.
2
javax.servlet.error.exception_type
This attribute gives information about exception type which can be stored and analysed after storing in a java.lang.Class data type.
3
javax.servlet.error.message
This attribute gives information exact error message which can be stored and analysed after storing in a java.lang.String data type.
4
javax.servlet.error.request_uri
This attribute gives information about URL calling the servlet and it can be stored and analysed after storing in a java.lang.String data type.
5
javax.servlet.error.exception
This attribute gives information the exception raised which can be stored and analysed after storing in a java.lang.Throwable data type.
6
javax.servlet.error.servlet_name
This attribute gives servlet name which can be stored and analysed after storing in a java.lang.String data type.

Error Handler Servlet Example:

Following is the Servlet Example that would be used as Error Handler in case of any error or exception occurs with your any of the servlet defined.
This example would give you basic understanding of Exception Handling in Servlet, but you can write more sophisticated filter applications using the same concept:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class
public class ErrorHandler extends HttpServlet {
 
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Analyze the servlet exception       
      Throwable throwable = (Throwable)
      request.getAttribute("javax.servlet.error.exception");
      Integer statusCode = (Integer)
      request.getAttribute("javax.servlet.error.status_code");
      String servletName = (String)
      request.getAttribute("javax.servlet.error.servlet_name");
      if (servletName == null){
         servletName = "Unknown";
      }
      String requestUri = (String)
      request.getAttribute("javax.servlet.error.request_uri");
      if (requestUri == null){
         requestUri = "Unknown";
      }

      // Set response content type
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
   String title = "Error/Exception Information";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor=\"#f0f0f0\">\n");

      if (throwable == null && statusCode == null){
         out.println("<h2>Error information is missing</h2>");
         out.println("Please return to the <a href=\"" + 
           response.encodeURL("http://localhost:8080/") + 
           "\">Home Page</a>.");
      }else if (statusCode != null){
         out.println("The status code : " + statusCode);
      }else{
         out.println("<h2>Error information</h2>");
         out.println("Servlet Name : " + servletName + 
                             "</br></br>");
         out.println("Exception Type : " + 
                             throwable.getClass( ).getName( ) + 
                             "</br></br>");
         out.println("The request URI: " + requestUri + 
                             "<br><br>");
         out.println("The exception message: " + 
                                 throwable.getMessage( ));
      }
      out.println("</body>");
      out.println("</html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}
Compile ErrorHandler.java in usual way and put your class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.
Let us add the following configuration in web.xml to handle exceptions:
<servlet>
        <servlet-name>ErrorHandler</servlet-name>
        <servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
        <servlet-name>ErrorHandler</servlet-name>
        <url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
<error-page>
    <error-code>404</error-code>
    <location>/ErrorHandler</location>
</error-page>
<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page>
Now try to use a servlet which raise any exception or type a wrong URL, this would trigger Web Container to call ErrorHandler servlet and display an appropriate message as programmed. For example, if you type a wrong URL then it would display the following result:
The status code : 404
Above code may not work with some web browsers. So try with Mozilla and Safari and it should work.

Monday, June 8, 2015

Improve knowledge about JavaScript Object Notation -Comparison with XML

JSON and XML are human readable formats and are language independent. They both have support for creation, reading and decoding in real world situations. We can compare JSON with XML based on the following factors:

Verbose

XML is more verbose than JSON, so it's faster to write JSON for humans.

Arrays Usage

XML is used to describe structured data which doesn't include arrays whereas JSON include arrays.

Parsing

JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object.

Example

This shows individual examples of XML and JSON:

JSON

{
   "company": Volkswagen,
   "name": "Vento",
   "price": 800000
}

XML

<car>
   <company>Volkswagen</company>
   <name>Vento</name>
   <price>800000</price>
</car>