Sunday, January 13, 2013

Steps to create a simple servlet

The article assumes, you have JDK 5.0/6.0 and Tomcat 6.0.

The following are the steps to be taken by you to create a simple servlet.

Download Tomcat 6.0 from http://tomcat.apache.org
Install Tomcat 6.0 into c:\ApacheTomcat6.0
Go to webapps directory of Tomcat and create the following directory structure for demo application. Any directory placed with required structure of Java EE web application is treated as a web application by Tomcat.
demo
WEB-INF
classes
TestServlet.java
web.xml

Creating Servlet Source Code

The following is the code for TestServlet.java. It simply sends a message to browser.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Test Servlet </h1></body></html>");
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
}



Create web.xml as follows. It is better you copy web.xml from some other application in Tomcat webapps directory instead of typing it from scratch. Make sure it is placed in WEB-INF (in uppercase) folder of demo application with the following content.

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>

</web-app>

TestServlet is associated with url pattern /test in web.xml. From the client, we have to make request for url pattern /test.
Compiling Servlet

Go to classes directory, where .java file is placed as enter the following commands at the command prompt to compile the servlet.
path=d:\jdk1.6.0\bin
set classpath=.;c:\apachetomcat6.0\lib\servlet-api.jar
javac TestServlet.java

Make sure you change JDK and Tomcat directories according to your installation.

Set path to the directory where JDK is installed. Servlet-api.jar contains API related to servlet like HttpServlet, HttpServletRequest etc., so it must be placed in the classpath. Compile the servlet (.java) to create .class file.

Starting Tomcat and Running Servlet

Start Tomcat by taking the follwing steps from BIN directory of Tomcat.
set java_home=d:\jdk1.6.0
startup

Once, tomcat is successfully started, go to browser and enterer the following URL.
http://localhost:8080/demo/test
You must see the output as follows.

[IMG]

Servlet QUIZ Questions -1



    1. Which of the following are interfaces? (3 correct answers)
      1. Servlet
      2. HttpServlet
      3. ServletRequest
      4. HttpServletRequest
ANS : a,c,d

    1. Which of the following are abstract classes? (2 correct answers)
      1. Servlet
      2. HttpServlet
      3. GenericServlet
      4. HttpServletRequest
ANS: b,c

    1. Which of the following statements is true? (1 correct answer)
      1. HttpServlet extends GenericServlet that implements Servlet.
      2. HttpServlet extends GenericServlet that extends Servlet.
      3. HttpServlet implements GenericServlet that extends Servlet.   
ANSWER : a

    1. Which of the following statements are true? (2 correct answers)
      1. HttpServlet IS-A GenericServlet.
      2. HttpServlet IS-A Servlet.
      3. HttpServlet IS-A ServletRequest.
Answer : a,b

    1. Here are some actions taken by the Container when a client request arrives. Place them in the correct order starting from what happens first.
      1. Calls the void service(HttpServletRequest, HttpServletResponse) method of the servlet.
      2. Creates a pair of request and response objects.
      3. Finds the correct servlet based on the URL.
      4. Creates a new thread or allocates an existing thread to the client’s request.
Answer : b,c,d,a

Tuesday, November 6, 2012

Java Clone, Shallow Copy and Deep Copy


Clone (κλών) is a Greek word meaning “branch”, referring to the process whereby a new plant can be created from a twig. In biology it is about copying the DNAs. In real world, if you clone Marilyn Monroe, will you get a copy of her with same beauty and characteristics? No, you will not get! This exactly applies to java also. See how java guys are good at naming technologies.
In java, though clone is ‘intended’ to produce a copy of the same object it is not guaranteed. Clone comes with lots of its and buts. So my first advice is to not depend on clones. If you want to provide a handle / method to deliver a copy of the current instance write a kind of factory methodand provide it with a good documentation. When you are in a situation to use a third party component and produce copies of it using the clone method, then investigate that implementation carefully and get to know what is underlying. Because when you ask for a rabbit, it may give monkeys!

Shallow Copy

Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as type and you need to explicitly cast back to your original object.
Since the Object class has the clone method (protected) you cannot use it in all your classes. The class which you want to be cloned should implement clone method andoverwrite it. It should provide its own meaning for copy or to the least it should invoke the super.clone(). Also you have to implement Cloneable marker interface or else you will get CloneNotSupportedException. When you invoke the super.clone() then you are dependent on the Object class’s implementation and what you get is a shallow copy.

Deep Copy

When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in deep copy. When you implement deep copy be careful as you might fall for cyclic dependencies. If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.
One more disadvantage with this clone system is that, most of the interface / abstract class writers in java forget to put a public clone method. For example you can take List. So when you want to clone their implementations you have to ignore the abstract type and use actual implementations like ArrayList by name. This completely removes the advantage and goodness of abstractness.
When implementing a singleton pattern, if its superclass implements a public clone() method, to prevent your subclass from using this class’s clone() method to obtain a copy overwrite it and throw an exception of type  CloneNotSupportedException.
Note that clone is not for instantiation and initialization. It should not be synonymously used as creating a new object. Because the constructor of the cloned objects may never get invoked in the process. It is about copying the object in discussion and not creating new. It completely depends on the clone implementation. One more disadvantage (what to do there are so many), clone prevents the use of final fields. We have to find roundabout ways to copy the final fields into the copied object.
Clone is an agreement between you, compiler and implementer. If you are confident that you all three have good knowledge of java, then go ahead and use clone. If you have a slightest of doubt better copy the object manually.


IP address of localhost from Java Program

Example source code for java clone and shallow copy

class Employee implements Cloneable {
 private String name;
 private String designation;
 public Employee() {
 this.setDesignation("Programmer");
 }
 public String getDesignation() {
 return designation;
 }
 public void setDesignation(String designation) {
 this.designation = designation;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public Object clone() throws CloneNotSupportedException {
 /*
 Employee copyObj = new Employee();
 copyObj.setDesignation(this.designation);
 copyObj.setName(this.name);
 return copyObj;
 */
 return super.clone();
 }
}
public class CloneExample {
 public static void main(String arg[]){
 Employee jwz = new Employee();
 jwz.setName("Jamie Zawinski");
 try {
 Employee joel = (Employee) jwz.clone();
 System.out.println(joel.getName());
 System.out.println(joel.getDesignation());
 } catch (CloneNotSupportedException cnse) {
 System.out.println("Cloneable should be implemented. " + cnse );
 }
 }
}
Output of the above program:
Jamie Zawinski
Programmer