Thursday, August 18, 2011

An included Servlet

package org.best.example;

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

public class AnIncludedServlet extends HttpServlet {

  public void doGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletException, IOException {
    PrintWriter pw = res.getWriter();

    /**
     * note that a servlet that has been included within another
     * servlet has access to both the original request uri, servlet
     * path, path info, context path and query string through the
     * HttpServletRequest object.
     *
     * However it also has access to these values that can be different
     * depending on how the servlet include was dispatched.  The servlet
     * engine gives you access to these though request attributes as
     * demonstrated before.
     */

    pw.println( "<h1>The Included Servlet</h1>" );
    pw.println( "<br>request uri: " +
                req.getAttribute( "javax.servlet.include.request_uri" ) );
    pw.println( "<br>context path: " +
                req.getAttribute( "javax.servlet.include.context_path" ) );
    pw.println( "<br>servlet path: " +
                req.getAttribute( "javax.servlet.include.servlet_path" ) );
    pw.println( "<br>path info: " +
                req.getAttribute( "javax.servlet.include.path_info" ) );
    pw.println( "<br>query string: " +
                req.getAttribute( "javax.servlet.include.query_string" ) );
  }
}

Wednesday, August 17, 2011

Java Interview Questions - 45

Q: Explain the life cycle methods of a Servlet.
A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method.

public void init(ServletConfig config) throws ServletException

public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException

public void destroy()

First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

Accessing a data source from a servlet

package org.best.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * web.xml configuration part of the a data source
 *
 *  <web-app>
 ...
 <resource-ref>
 <description>the database for this app</description>
 <res-ref-name>jdbc/thedatabase</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>CONTAINER</res-auth>
 </resource-ref>
 ...
 </web-app>
 *
 * the vendor-specific mapping of the res-ref-name into their
 * own application server space, eg weblogic does the following
 * in a weblogic.xml file
 *
 <weblogic-web-app>
 ...
 <reference-descriptor>
 ...
 <resource-description>
 <res-ref-name>jdbc/thedatabase</res-ref-name>
 <jndi-name>jdbc/gangland</jndi-name>
 </resource-description>
 ...
 </reference-descriptor>
 ...
 </weblogic-web-app>
 */

public class AccessingADataSourceFromAServlet extends HttpServlet {

  public void init() {
    System.out.println( "### loading -> " + getServletName() + " at " +
                        new Date( System.currentTimeMillis() ).toString() );

  }

  public void doGet( HttpServletRequest req, HttpServletResponse res )
      throws ServletException, IOException {
    res.setContentType( "text/html" );
    PrintWriter pw = res.getWriter();

    Connection con = null;
    try {
      Context ctx = new InitialContext();
      DataSource ds = (DataSource) ctx.lookup( "java:comp/env/jdbc/thedatabase" );
      con = ds.getConnection();
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery( "select * from enemies" );
      while( rs.next() ) {
        pw.println( rs.getString( "name" ) + "<br>" );
      }
    }
    catch( Exception ex ) {
      log( "problem accessing database", ex );
      res.sendError( res.SC_INTERNAL_SERVER_ERROR, ex.getMessage() );
    }
    finally {
      if( con != null ) {
        try {
          con.close();
        }
        catch( SQLException ex ) {
          log( "problem closing connection", ex );
        }
      }
    }
  }
}

Tuesday, August 16, 2011

Remove all values from Java LinkedHashMap

package org.best.example;

    /*
      Remove all values from Java LinkedHashMap example
      This Java Example shows how to remove all values from LinkedHashMap object or empty
      LinkedHashMap or clear LinkedHashMap using clear method.
    */
    
    import java.util.LinkedHashMap;
    
    public class EmptyLinkedHashMapExample {
    
    public static void main(String[] args) {
    
    //create LinkedHashMap object
    LinkedHashMap lHashMap = new LinkedHashMap();
    
    //add key value pairs to LinkedHashMap
    lHashMap.put("1","One");
    lHashMap.put("2","Two");
    lHashMap.put("3","Three");
    
    /*
      To remove all values or clear LinkedHashMap use
      void clear method() of LinkedHashMap class. Clear method removes all
      key value pairs contained in LinkedHashMap.
      */
    
    lHashMap.clear();
    
    System.out.println("Total key value pairs in LinkedHashMap are : "
    + lHashMap.size());
    }
    }
    
    /*
    Output would be
    Total key value pairs in LinkedHashMap are : 0
    */

Java Questions - 44

Question: What do you understand by Synchronization?
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

Monday, August 15, 2011

Iterate through the values of Java LinkedHashMap

package org.best.example;

    /*
      Iterate through the values of Java LinkedHashMap example
      This Java Example shows how to iterate through the values contained in the
      LinkedHashMap object.
    */
    
    import java.util.Collection;
    import java.util.LinkedHashMap;
    import java.util.Iterator;
    
    public class IterateValuesOfLinkedHashMapExample {
    
    public static void main(String[] args) {
    
    //create LinkedHashMap object
    LinkedHashMap lHashMap = new LinkedHashMap();
    
    //add key value pairs to LinkedHashMap
    lHashMap.put("1","One");
    lHashMap.put("2","Two");
    lHashMap.put("3","Three");
    
    /*
      get Collection of values contained in LinkedHashMap using
      Collection values() method of LinkedHashMap class
      */
    Collection c = lHashMap.values();
    
    //obtain an Iterator for Collection
    Iterator itr = c.iterator();
    
    //iterate through LinkedHashMap values iterator
    while(itr.hasNext())
    System.out.println(itr.next());
    }
    }
    
    /*
    Output would be
    One
    Two
    Three
    */

Java Questions - 43

Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.