Chitika

Monday, January 3, 2011

Java Servlets

What is Java Servlets?

Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls, receive all the benefits of the mature java language including portability, performance, reusability, and crash protection. Today servlets are the popular choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server and others.
Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language.
HTTP Servlet typically used to:
  • Priovide dynamic content like getting the results of a database query and returning to the client.
  • Process and/or store the data submitted by the HTML.
  • Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.

Methods of Servlets

A Generic servlet contains the following five methods:
init()

public void init(ServletConfig config) throws ServletException
The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service. 
The servlet cannot be put into the service if
  •  The init() method does not return within a fix time set by the web server. 
  •  It throws a ServletException
Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred.

service()

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

Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and  javax.servlet.ServletResponse are passed by the servlet container.

The status code of the response always should be set for a servlet that throws or sends an error.

Parameters -  The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception.
 
getServletConfig()

public ServletConfig getServletConfig() 
This method contains parameters for initialization and startup of the servlet and returns aServletConfig object. This object is then passed to the init method. When this interface is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface.
Returns -  the ServletConfig object
getServletInfo()

public String getServletInfo() 
The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup. 
 Returns - a string that contains the information about the servlet
destroy()

public void destroy() 
This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held. 

Life cycle of Servlet

The life cycle of a servlet can be categorized into four parts:
  1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
  2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

    The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
  3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
  4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet  releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.


                  Life Cycle of a Servlet 


Advantages of Java Servlets

PortabilityAs we know that the servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations.  We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server running on the iPlanet/Netscape Application server. So servlets are write once, run anywhere (WORA)program.
PowerfulWe can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to  request. It can do many other things which are difficult to implement in the CGI programs.
EfficiencyAs compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. 
SafetyAs servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to  Java's exception handling mechanism. If any exception occurs then it will throw an exception.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc.
ExtensibilityThe servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets.
InexpensiveThere are number of  free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.

Tuesday, October 26, 2010

Fundemantals

Source code of the java program is first written in plain text files ending with the .java extension. When you compile the java program Those source files are then converted into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes

Figure showing MyProgram.java, compiler, MyProgram.class, Java VM, and My Program running on a computer.
Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS.


Identifiers and Keywords

The rules the compiler uses to determine whether a name is legal. 
  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.
  • You can't use a Java keyword as an identifier.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers
Examples:
The following identifiers are legal

int _a;  //starting with underscore
int $c;  //starting with $ sign
int ______2_w;  //starting with underscore
int _$;       //starting with underscore
int this_is_a_very_detailed_name_for_an_identifier; // starting with a letter

The following identifiers are illegal

int :b; // starting letter is not valid
int -d; // starting letter is not valid
int e#; // special charactor # is not legal
int .f; // starting (.) is not valid
int 7g; //starting with number not allowed.

Java Keywords

You cannot use any of the following as identifiers in your programs

abstract   continue   for    new
switch    assert***    default   goto*
package    synchronized    boolean    do
if   private    this    break
double    implements    protected    throw
byte    else     import    public
case    enum****    instanceof    return
transient    catch    extends    int
short    try    char    final
interface    static    void    throws
class    finally    long    strictfp**
volatile    const*    float    native
super    while

* not used 
** added in 1.2 *** added in 1.4 **** added in 5.0

Through the Java VM, the same application is capable of running on multiple platforms.

Figure showing source code, compiler, and Java VM's for Win32, Solaris OS/Linux, and Mac OS

Legal Identifiers

Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).

All the Java components —classes, variables, and methods—need names. In Java these names are called
there are rules for what constitutes a legal Java identifier.

Monday, September 13, 2010

Review Questions



  1. Write a java program to display your name on the command prompt
  2. Write a java program to display numbers from 1-10 using a for loop
  3. Write a java program to display numbers for a given range on the command prompt
    eg. Java NumDemo 12 30
    will display numbers starting from 12 to 30
  4. write a java program to sort and display a given number series as user arguments, and also display the maximum and the minimum in the series.
  5. Write a java program to find the mean and the median of a given number series as user arguments: (use two methods to find the two attributes and invoke them inside the main method)
  6. Write a java program to find the mode of a given number series as user arguments.
  7. Identify what are the java keywords from the followings
    a. abstract b. boolean c. interface d.public e. method f. subclasses
  8. Which one of these lists contains only Java programming language keywords? (Choose one.)
    A. class, if, void, long, Int, continue
    B. goto, instanceof, native, finally, default, throws
    C. try, virtual, throw, final, volatile, transient
    D. strictfp, constant, super, implements, do
    E. byte, break, assert, switch, include
  9. Which three are legal array declarations? (Choose three.)
    A. int [] myScores [];
    B. char [] myChars;
    C. int [6] myScores;
    D. Dog myDogs [];
    E. Dog myDogs [7];
  10. Which will legally declare, construct, and initialize an array? (Choose one.)
    A. int [] myList = {“1”, “2”, “3”};
    B. int [] myList = (5, 8, 2);
    C. int myList [] [] = {4,9,7,0};
    D. int myList [] = {4, 3, 7};
    E. int [] myList = [3, 5, 6];
    F. int myList [] = {4; 6; 5};
  11. What is the output of the following program
public class CharDemo{
    public static void main(String arg[]){
       char a = 'A';
       char b = (char)(a+1);
       System.out.println(a+b);
       System.out.println("a+b is "+a+b);
       int x = 75;
       char y = (char)x;
       char half = '\u00AC';
       System.out.println("Y is "+y+"and half is"+half);

       }
    } 

Wrte your answers in the comments area and submit
    Sample solutions

    1. public class NameDisplay{
        public static void main(String[] arg){
          System.out.println("Chaminda Wijesinghe");
        }
       }
    

    Write the above program on a notepad and
    Save the above program using the file name NameDisplay.java and filetype All Files
    Open command prompt and compile the program using "Javac NameDisplay.java"
    Run the program using  "Java DisplayName"

    2. public class NumberDisplay{
       public static void main(String[] arg){
         for(int i=1;i<=10;i++){
           System.out.println(""+i);
           } // end of for loop
        } //end of main method
        } // end of the class
    
    3. public class NumberDisplay2{
       public static void main(String[] arg){
    
       int i = Integer.parseInt(arg[0]);
       int j = Integer.parseInt(arg[1]);
     
       for(int x=i; x<=j; x++){
          System.out.println(""+x);
          }
      }
      }
    
    
    Sample Java Programms

    A program to display prime Numbers

    public class prime{
    private static boolean checkprime(int num)
     {
     boolean done = false;
     
      for(int i=2;i<num;i++)
      {
      if(num%i!=0)
        done=true;
      else
        return false;
      }
      return done;
     }
    public static void main(String[] arg)
     {
     for(int i=2;i<=100;i++)
      {
      if(checkprime(i))
      {
      System.out.println("prime "+i);
      }
      }
     }
    }
    A program to implement a Calculator

    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class CalculatorApplet extends Applet implements ActionListener
    {
    private Button keysArray[];
    private Panel keyPad;
    private TextField lcdField;
    private double result;
    private boolean first;
    private boolean foundKey;
    static boolean clearText;
    private int prevOperator;
    public void init()
    {
      lcdField = new TextField(20);
      keyPad = new Panel ();
      keysArray = new Button[17];
      result = 0.0;
      prevOperator = 0;
      first = true;
      clearText = true;
      //Set frame layout manager setLayout(new BorderLayout());
      lcdField.setEditable(false);
      //Create buttons
      for (int i = 0; i <=9; i++)
       keysArray[i] = new Button(String.valueOf(i));
       keysArray[10] = new Button("/");
       keysArray[11] = new Button("*");
       keysArray[12] = new Button("-");
       keysArray[13] = new Button("+");
       keysArray[14] = new Button("=");
       keysArray[15] = new Button(".");
       keysArray[16] = new Button("CLR");

       //Set panel layout manager
       keyPad.setLayout(new GridLayout (4,4));
       //Add button to keyPad panel
       for (int i = 7; i <=10; i++) //adds Button 7,8,9, and divide to Panel
        keyPad.add(keysArray[i]);
       for (int i = 4; i <6; i++) //adds buttons 4,5,6 to Panel
        keyPad.add(keysArray[i]);
       keyPad.add(keysArray[11]); //adds multiply button to Panel
       for (int i = 1; i <= 3;i++) //adds buttons 1,2 and 3 to Panel
        keyPad.add(keysArray[i]);
       keyPad.add(keysArray[12]);//adds minus button to Panel
       keyPad.add(keysArray[0]); //adds 0 key to Panel
       for (int i = 15; i >=13; i--)
        keyPad.add(keysArray[i]); //adds decimal point, equal, and addition keys Panel
        add(lcdField, BorderLayout.NORTH); //adds text field to top of Frame
        add(keyPad, BorderLayout.CENTER); //adds Panel to center of Frame
        add(keysArray[16], BorderLayout.EAST); //adds Clear key to right side of applet
        for(int i = 0; i < keysArray.length; i++)
         keysArray[i].addActionListener(this);
     }
     public void actionPerformed(ActionEvent e)
     {
       foundKey = false;
       //Search for the key pressed
       for (int i = 0; i < keysArray.length && !foundKey; i++)
       if(e.getSource() == keysArray[i]) //key match found
       {
         foundKey = true;
         switch(i)
         {
         case 0: case 1: case 2: case 3: case 4: //number buttons
         case 5: case 6: case 7: case 8: case 9: //0-9
         case 15:
         if (clearText)
         {
         lcdField.setText("");
         clearText = false;
      }
      lcdField.setText(lcdField.getText() +
      keysArray[i].getLabel());
      break;
      case 10:// divide button
      case 11:// multiply button
      case 12:// minus button
      case 13:// plus button
      case 14:// equal button
        clearText = true;
        if (first) // First operand
        {
        if(lcdField.getText().length()==0)
         result = 0.0;
        else
         result = Double.valueOf(lcdField.getText()).doubleValue();
      first = false;
                    prevOperator = i; //save previous operator
         }
           else //second operand already enter, so calculator total
           {
       switch(prevOperator)
       {
       case 10: //divide Button
        result /= Double.valueOf(lcdField.getText()).
        doubleValue();
      break;
      case 11: //multiply Button
      result *= Double.valueOf(lcdField.getText()).
      doubleValue();
      break;
      case 12: //minus button
      result -= Double.valueOf(lcdField.getText()).
      doubleValue();
      break;
      case 13: //plus button
      result += Double.valueOf(lcdField.getText()).
      doubleValue();
      break;
        }
        lcdField.setText(Double.toString(result));
        if (i==14)//equal button
         first = true;
        else
         prevOperator = i; //save previous opetator
         }
         break;
         case 16://Clear button
         clearText = true;
         first = true;
         lcdField.setText("");
         result = 0.0;
         prevOperator = 0;
         break;
         }
         }
        }
       }
    A program to display Candidate's preferencial votes as a Histogram
    import javax.swing.*;
    public class Histogram
         {
         public static void main( String args[] )
             {
             int n[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
             String output = "";
           
             output += "Canidate No\tVotes\tHistogram";
           
             for ( int i = 0; i < n.length; i++ )
                 {
                 output += "\n" + i + "\t" + n[ i ] + "\t";
               
                 for ( int j = 1; j <= n[ i ]; j++ ) // print a bar
                 output += "*";
             }
           
             JTextArea outputArea = new JTextArea( 11, 30 );
             outputArea.setText( output );
           
             JOptionPane.showMessageDialog( null, outputArea,"Histogram Printing Program",JOptionPane.INFORMATION_MESSAGE );
           
             System.exit( 0 );
         }
    }