EJB3 Message Driven Bean

 EJB3 Message Driven Bean

In this example, we are going to create an MDB which consumes the message sent to the Queue Destination and a JMS Application Client which sends the message to the Queue using JMS API.

The client sends two types of messages – TextMessage and ObjectMessage. For ObjectMessage we create a Transfer Object ‘Employee’ with some basic fields as follows.

This example uses JBoss 7.1 as application server.

1.1. Transfer Object Class

We create a simple ‘Employee’ class and use it to create an object which will be sent to the destination by the client as an ObjectMessage.

package com.theopentutorials.mdb.to;
import java.io.Serializable;

public class Employee implements Serializable{
private int id;
private String name;
private String designation;
private double salary;

public Employee() { }

public Employee(int id, String name, String designation, double salary) {
this.id = id;
this.name = name;
this.designation = designation;
this.salary = salary;
}
public String toString() { return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + ", salary=" + salary + "]"; } }

2. JMS Application Client – Message Producer

We create a Java application which uses JMS API to send messages to the queue. This application client sends a text message and an employee object message and hence is the message producer.

The client needs to get the JMS Administered Objects – ConnectionFactory and the Destination objects by using JNDI lookup.

First, we need to get the Context object to lookup the JBoss’s JNDI namespace. We can use the following context properties to get the context object.

 Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, "username");
env.put(Context.SECURITY_CREDENTIALS, "password");
Context remoteContext = new InitialContext(env);

JBoss JNDI is protected by ApplicationRealm. So you need to provide username and password or create a new one by using the add user script available in ‘bin’ folder of JBoss.

Using the context object we can lookup the JMS administered objects and retrieve the connection factory and destination objects. Since the client is outside the JBoss container (normal java application), we need to use RemoteConnectionFactory.

ConnectionFactory factory = (ConnectionFactory)remoteContext.lookup("jms/RemoteConnectionFactory"); Queue queue = (Queue) remoteContext.lookup("jms/queue/MyQueue");

Next, we can use the connection factory to create a connection to the JMS provider which in turn can be used to create a session.

Using the session object, we can create the message and message producer which sends the message to the queue using the send() method.

The complete code is as follows.

package com.theopentutorials.client;
import java.util.Properties;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.theopentutorials.mdb.to.Employee;

public class JMSApplicationClient1 {

public static void main(String[] args) {
Connection connection;
try {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, "user1");
env.put(Context.SECURITY_CREDENTIALS, "pass1");
Context remoteContext = new InitialContext(env);
ConnectionFactory factory = (ConnectionFactory)remoteContext. lookup("jms/RemoteConnectionFactory"); Queue queue = (Queue) remoteContext. lookup("jms/queue/MyQueue");
connection = factory.createConnection();
Session session = connection.createSession(false, QueueSession.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue);

//1. Sending TextMessage to the Queue
TextMessage message = session.createTextMessage();
message.setText("Hello EJB3 MDB Queue!!!");
producer.send(message);
System.out.println("1. Sent TextMessage to the Queue");

//2. Sending ObjectMessage to the Queue
ObjectMessage objMsg = session.createObjectMessage();
Employee employee = new Employee();
employee.setId(2163);
employee.setName("Lakshmikar");
employee.setDesignation("SE");
employee.setSalary(100000);
objMsg.setObject(employee);
producer.send(objMsg);
System.out.println("2. Sent ObjectMessage to the Queue");
session.close();
} catch (JMSException e) {
e.printStackTrace();
} catch (NamingException e) {
 e.printStackTrace();
}
}
}

2.1. Message-Driven Bean – Message Consumer

Lastly, we need to create an MDB which will receive the message from the destination. While creating the MDB, we specify the destination type and destination JNDI in @ActivationConfigProperty annonation of @MessageDriven.

The MDB should implement the javax.jms.MessageListener interface and provide the onMessage() method implementation. Inside that method we retrieve the message and cast it to the appropriate message type (TextMessage or ObjectMessage). For TextMessage we can use the getText() method to get the message and for ObjectMessage, getObject() method returns the object sent to the destination by the producer.

The code is as follows.

package com.theopentutorials.mdb;
import java.util.Date;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
import com.theopentutorials.mdb.to.Employee;
@MessageDriven( activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/MyQueue") })

public class QueueListenerMDB implements MessageListener {
public QueueListenerMDB() { }
public final void onMessage(Message message){
try {
if (message instanceof TextMessage) {
System.out.println("Queue: I received a TextMessage at " + new Date());
TextMessage msg = (TextMessage) message;
System.out.println("Message is : " + msg.getText());
 } else if (message instanceof ObjectMessage) {
System.out.println("Queue: I received an ObjectMessage " + " at " + new Date());
ObjectMessage msg = (ObjectMessage) message;
Employee employee = (Employee) msg.getObject();
System.out.println("Employee Details: ");
System.out.println(employee.getId());
System.out.println(employee.getName());
System.out.println(employee.getDesignation());
System.out.println(employee.getSalary());
} else {
System.out.println("Not valid message for this Queue MDB");
} } catch (JMSException e) { e.printStackTrace(); } } }

Deploy the MDB and start the JBoss server. Run the application client which sends the message and verify that the MDB consumes it.



JAX-WS

JAX-WS Tutorial

Developing WebService End Point

1) Open Eclipse, and create a java project "WS-Server".
2) Create WS-Service Endpoint Interface:

package mopuri.lakshmikar;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface Greeting {
  @WebMethod String sayHello(String name); }

3) Create WS-Service Endpoint Implementation class:

package mopuri.lakshmikar;
import javax.jws.WebService;
@WebService(endpointInterface = "mopuri.lakshmikar.Greeting")
public class GreetingImpl implements Greeting {
  @Override
   public String sayHello(String name) {
       return "Hello, Welcom to jax-ws " + name;    } }

4) Create Endpoint Publisher class:

package mopuri;
import javax.xml.ws.Endpoint;
import mopuri.lakshmikar.GreetingImpl;
public class WSPublisher {
  public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/WS/Greeting",new GreetingImpl());   } }

5) Run the WSPublisher…. Guess what .. your WebService is published..
Wow.. check your service wsdl http://localhost:8080/WS/Greeting?wsdl

Developing WebService Client :

1) Open eclipse and create a new java project WS-Client
2) As you know we need to generate the client stubs... but how? 
open your command line, and enter the wsimport command:

1.CD %CLIENT_PROJECT_HOME%\src
2.wsimport –s . http://localhost:8080/WS/Greeting?wsdl

You will find 6 java classes generated, and compiled under src/mopuri/lakshmikar.
You can remove *.class files , no need for them :)

3) Now Lets create Client Class which will be dependent on the stubs:

package mopuri;
import mopuri.lakshmikar.Greeting;
import mopuri.lakshmikar.GreetingImplService;
public class Client {
   public static void main(String[] args){
GreetingImplService service = new GreetingImplService();
Greeting greeting = service.getGreetingImplPort();
System.out.println("------->>  Call Started");
System.out.println(greeting.sayHello("Ali"));
System.out.println("------->>  Call Ended");
  }
}

4) Run the Client Class.... the output should looks like:

----->>  Call Started
Hello, Welcom to jax-ws Ali
----->>  Call Ended


Congratulations.... you managed to develop jax-ws Endpoint , Client.. 

What is immutable class in Java


How to create Immutable Class and Object in Java - Tutorial Example

Writing or creating immutable classes in Java is becoming popular day by day, because of concurrency and multithreading advantage provided by immutable objects. Immutable objects offers several benefits over conventional mutable object, especially while creating concurrent Java application. Immutable object not only guarantees safe publication of object’s state, but also can be shared among other threads without any external synchronization. In fact JDK itself contains several immutable classes like String, Integer and other wrapper classes. For those, who doesn’t know what is immutable class or object, Immutable objects are those, whose state can not be changed once created e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase. All modification in String result in new object, see why String is immutable in Java for more details. In this Java programming tutorial, we will learn, how to write immutable class in Java or how to make a class immutable. By the way making a class immutable is not difficult on code level, but its the decision to make, which class mutable or immutable which makes difference. I also suggest reading, Java Concurrency in Practice to learn more about concurrency benefit offered by Immutable object.

What is immutable class in Java

As said earlier, Immutable classes are those class, whose object can not be modified once created, it means any modification on immutable object will result in another immutable object. best example to understand immutable and mutable objects are, String and StringBuffer. Since String is immutable class, any change on existing string object will result in another string e.g. replacing a character into String, creating substring from String, all result in a new objects. While in case of mutable object like StringBuffer, any modification is done on object itself and no new objects are created. Some times this immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.

How to write immutable class in Java

Despite of few disadvantages, Immutable object still offers several benefits in multi-threaded programming and it’s a great choice to achieve thread safety in Java code. here are few rules, which helps to make a class immutable in Java :


1. State of immutable object can not be modified after construction, any modification should result in new immutable object.

2. All fields of Immutable class should be final.

3. Object must be properly constructed i.e. object reference must not leak during construction process.

4. Object should be final in order to restrict sub-class for altering immutability of parent class.



By the way, you can still create immutable object by violating few rules, like String has its hashcode in non final field, but its always guaranteed to be same. No matter how many times you calculate it, because it’s calculated from final fields, which is guaranteed to be same. This required a deep knowledge of Java memory model, and can create subtle race conditions if not addressed properly. In next section we will see simple example of writing immutable class in Java. By the way, if your Immutable class has lots of optional and mandatory fields, then you can also use Builder design pattern to make a class Immutable in Java.

Immutable Class Example in Java

Here is complete code example of writing immutable class in Java. We have followed simplest approach and all rules for making a class immutable, including it making class final to avoid putting immutability at risk due to Inheritance and Polymorphism.

public final class Contacts {

private final String name;

private final String mobile;

public Contacts(String name, String mobile) {

this.name = name;

this.mobile = mobile;

}

public String getName(){

return name;

}

public String getMobile(){

return mobile;

}

}


This Java class is immutable, because its state can not be changed once created. You can see that all of it’s fields are final. This is one of the most simple way of creating immutable class in Java, where all fields of class also remains immutable like String in above case. Some time you may need to write immutable class which includes mutable classes like java.util.Date, despite storing Date into final field it can be modified internally, if internal date is returned to the client. In order to preserve immutability in such cases, its advised to return copy of original object, which is also one of the Java best practice. here is another example of making a class immutable in Java, which includes mutable member variable.

public final class ImmutableReminder{

private final Date remindingDate;

public ImmutableReminder (Date remindingDate) {

if(remindingDate.getTime() < System.currentTimeMillis()){

throw new IllegalArgumentException("Can not set reminder” +

“ for past time: " + remindingDate);

}

this.remindingDate = new Date(remindingDate.getTime());

}

public Date getRemindingDate() {

return (Date) remindingDate.clone();

}

}

In above example of creating immutable class, Date is a mutable object. If getRemindingDate() returns actual Date object than despite remindingDate being final variable, internals of Date can be modified by client code. By returning clone() or copy of remindingDate, we avoid that danger and preserves immutability of class.

Benefits of Immutable Classes in Java

As I said earlier Immutable classes offers several benefits, here are few to mention:


1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.

2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.

3) Immutable object boost performance of Java application by reducing synchronization in code.


4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers. You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one.


Apart from above advantages, immutable object has disadvantage of creating garbage as well. Since immutable object can not be reused and they are just a use and throw. String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection, but again that's extreme case and if used properly Immutable object adds lot of value.


That's all on how to write immutable class in Java. we have seen rules of writing immutable classes, benefits offered by immutable objects and how we can create immutable class in Java which involves mutable fields. Don’t forget to read more about concurrency benefit offered by Immutable object in one of the best Java book recommended to Java programmers, Concurrency Practice in Java.


Why String is immutable or final in Java


This is one of the most popular String Interview questions in Java, which starts with discussion of, What is String, How String in Java is different than String in C and C++, and then shifted towards what is immutable object in Java , what are the benefits of immutable object , why do you use it and which scenarios do you use it. This is some time also asked as "Why String is final in Java" . Though there could be many possible answer for this question, and only designer of String class can answer this , I think below two does make sense

1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say


String A = "Test"

String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.

3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"


Security and String pool being primary reason of making String immutable, I believe there could be some more very convincing reasons as well, Please post those reasons as comments and I will include those on this post. By the way, above reason holds good to answer, another Java interview questions "Why String is final in Java". Also to be immutable you have to be final, so that your subclass doesn't break immutability. what do you guys think ?


what is finalize method in Java


10 points on finalize method in Java – Tutorial Example

finalize method in java is a special method much like main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc. Main issue with finalize method in java is its not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called its not guaranteed it will be immediately collected. Because of above reason it make no sense to use finalize method for releasing critical resources or perform any time critical activity inside finalize. It may work in development in one JVM but may not work in other JVM. In this java tutorial we will see some important points about finalize method in Java, How to use finalize method, what to do and what not to do inside finalize in Java.


what is finalize method in Java – Tutorial Example

1) finalize() method is defined in java.lang.Object class, which means it available to all the classes for sake of overriding. finalize method is defined as protected which leads to a popular core java question "Why finalize is declared protected instead of public"? well I don't know the exact reason its falls in same category of questions like why java doesn't support multiple inheritance which can only be answer accurately by designers of Java. any way making finalize protected looks good in terms of following rule of encapsulation which starts with least restrictive access modifier like private but making finalize private prevents it from being overridden in subclass as you can not override private methods, so making it protected is next obvious choice.

2) One of the most important point of finalize method is that its not automatically chained like constructors. If you are overriding finalize method than its your responsibility to call finalize() method of super-class, if you forgot to call then finalize of super class will never be called. so it becomes critical to remember this and provide an opportunity to finalize of super class to perform cleanup. Best way to call super class finalize method is to call them in finally block as shown in below example. this will granted that finalize of parent class will be called in all condition except when JVM exits:

@Override

protected void finalize() throws Throwable {

try{

System.out.println("Finalize of Sub Class");

//release resources, perform cleanup ;

}catch(Throwable t){

throw t;

}finally{

System.out.println("Calling finalize of Super Class");

super.finalize();

}



}

3) finalize method is called by garbage collection thread before collecting object and if not intended to be called like normal method.


4) finalize gets called only once by GC thread, if object revive itself from finalize method than finalize will not be called again.


5) Any Exception thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact I doubt if you find any trace of it.


6) There is one way you can guarantee running of finalize method by calling System.runFinalization() and

Runtime.getRuntime().runFinalization(). These methods ensures that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called.


Alternative of finalize method for cleanup.

So far its seems we are suggesting not to use finalize method because of its non guaranteed behavior but than what is alternative of releasing resource, performing cleanup because there is no destructor in Java. Having a method like close() or destroy() make much sense for releasing resources held by classes. In fact JDK library follows this. if you look at java.io package which is a great example of acquiring system resource like file descriptor for opening file, offers close() method for opening stream and close() for closing it. in fact its one of the best practice to call close method from finally block in java. Only caveat with this approach is its not automatic, client has to do the cleanup and if client forgot to do cleanup there are chances of resources getting leaked, which again suggest us that we could probably give another chance to finalize method. You will be pleased to know that Java 7 has added automatic resource management feature which takes care of closing all resource opened inside try block automatically, leaving no chance of manual release and leakage.


When to use finalize method in Java

As last paragraph pointed out that there are certain cases where overriding finalize make sense, like an ultimate last attempt to cleanup the resource. If a Java class is made to held resource like input output devices, JDBC connection than you should override finalize and call its close() method from finalize. though there is no guarantee that it will run and release the resource timely best part is we are not relying on it. It just another last attempt to release the resource which most likely have been already released due to client calling close() method. This technique is heavily used inside Java Development library. look at below example of finalize method from FileInputStream.java

protected void finalize() throws IOException {

if ((fd != null) && (fd != FileDescriptor.in)) {


/*

* Finalize should not release the FileDescriptor if another

* stream is still using it. If the user directly invokes

* close() then the FileDescriptor is also released.

*/

runningFinalize.set(Boolean.TRUE);

try {

close();

} finally {

runningFinalize.set(Boolean.FALSE);

}

}



}


What not to do in finalize method in Java

trusting finalize method for releasing critical resource is biggest mistake java programmer can made. suppose instead of relying on close() method to release file descriptor, you rely on finalize to relapse it for you. Since there is no guaranteed when finalize method will run you could effectively lock hundreds of file-descriptor of earlier opened file or socket and there is high chance that your application will ran out of file-descriptor and not able to open any new file. Its best to use finalize as last attempt to do cleanup but never use finalize as first or only attempt.


That's all on finalize method in Java. as you have seen there are quite lot of specifics about finalize method which java programmer should remember before using finalize in java. In one liner don’t do time critical task on finalize method but use finalize with caution.

Why Java doesn't support multiple inheritance


Why Java doesn't support multiple inheritance

1) First reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below


A foo()
/ \
/ \
foo() B C foo()
\ /
\ /
D foo()

In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.


Some times if you give this reason to interviewer he asks if C++ can support multiple inheritance than why not Java. hmmmmm in that case I would try to explain him the second reason which I have given below that its not because of technical difficulty but more to maintainable and clearer design was driving factor though this can only be confirmed by any of java designer and we can just speculate. Wikipedia link has some good explanation on how different language address problem arises due to diamond problem while using multiple inheritances.


2) Second and more convincing reason to me is that multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

Servlets Interview questions

SERVLETS
1.What is the Servlet?
A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request- response programming model.

2.What are the new features added to Servlet 2.5?
Following are the changes introduced in Servlet 2.5:
  • A new dependency on J2SE 5.0
  • Support for annotations
  • Loading the class
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications
3.What are the uses of Servlet?
Typical uses for HTTP Servlets include:
  • Processing and/or storing data submitted by an HTML form.
  • Providing dynamic content, e.g. returning the results of a database query to the client.
  • A Servlet can handle multiple request concurrently and be used to develop high performance system
  • Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.
4.What are the advantages of Servlet over CGI?
Servlets have several advantages over CGI:
  • A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
  • A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications
5.What are the phases of the servlet life cycle?
The life cycle of a servlet consists of the following phases:
  • Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
  • Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.
  • Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
  • Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
  • Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
6.Why do we need a constructor in a servlet if we use the init method?
Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.

7.How the servlet is loaded?
A servlet can be loaded when:
  • First request is made.
  • Server starts up (auto-load).
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Administrator manually loads.

8.How a Servlet is unloaded?
A servlet is unloaded when:
  • Server shuts down.
  • Administrator manually unloads.
9.What is Servlet interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending a class that implements it.

Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.

10.What is the GenericServlet class?
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.
Note: This class is known as generic servlet, since it is not specific to any protocol.
11.What's the difference between GenericServlet and HttpServlet?
GenericServlet
HttpServlet
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods. An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers. The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.
GenericServlet is not specific to any protocol. HttpServlet only supports HTTP and HTTPS protocol.
12.Why is HttpServlet declared abstract?
The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.

13.Can servlet have a constructor ?
One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.

14.What are the types of protocols supported by HttpServlet ?
It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.
15.What is the difference between doGet() and doPost()?
#
doGet()
doPost()
1
In doGet() the parameters are appended to the URL and sent along with header information.In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar.
2
The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
3
doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent)doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4
Parameters are not encryptedParameters are encrypted
5
doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performancedoPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length
6
doGet() should be idempotent. i.e. doget should be able to be repeated safely many timesThis method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7
doGet() should be safe without any side effects for which user is held responsibleThis method does not need to be either safe
8
It allows bookmarks.It disallows bookmarks.


16.When to use doGet() and when doPost()?
Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason:
  • If data is sensitive
  • Data is greater than 1024 characters
  • If your application don't need bookmarks.

17.How do I support both GET and POST from the same Servlet?
The easy way is, just support POST, then have your doGet method call your doPost method:

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

18.Should I override the service() method?
We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

19.How the typical servlet code look like ?

20.What is a servlet context object?
A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it.

21.What are the differences between the ServletConfig interface and the ServletContext interface?
ServletConfig
ServletContext
The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
There is one ServletConfig parameter per servlet. There is one ServletContext for the entire webapp and all the servlets in a webapp share it.
The param-value pairs for ServletConfig object are specified in the within the tags in the web.xml fileThe param-value pairs for ServletContext object are specified in the tags in the web.xml file.


22.What's the difference between forward() and sendRedirect() methods?
forward()
sendRedirect()
A forward is performed internally by the servlet.A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
The browser is completely unaware that it has taken place, so its original URL remains intact.The browser, in this case, is doing the work and knows that it's making a new request.
Any browser reload of the resulting page will simple repeat the original request, with the original URLA browser reloads of the second URL ,will not repeat the original request, but will rather fetch the second URL.
Both resources must be part of the same context (Some containers make provisions for cross-context communication but this tends not to be very portable)This method can be used to redirect users to resources that are not part of the current context, or even in the same domain.
Since both resources are part of same context, the original request context is retainedBecause this involves a new request, the previous request scope objects, with all of its parameters and attributes are no longer available after a redirect.
(Variables will need to be passed by via the session object).
Forward is marginally faster than redirect.redirect is marginally slower than a forward, since it requires two browser requests, not one.


23.What is the difference between the include() and forward() methods?
include()
forward()
The RequestDispatcher include() method inserts the the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet.The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.
If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored. The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
The include() method is often used to include common "boilerplate" text or template markup that may be included by many servlets. The forward() method is often used where a servlet is taking a controller role; processing some input and deciding the outcome by returning a particular response page
24.What's the use of the servlet wrapper classes??
The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.
25.What is the directory structure of a WAR file?

26.What is a deployment descriptor?
A deployment descriptor is an XML document with an .xml extension. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
The JavaEE server reads the deployment descriptor at run time and acts upon the component accordingly.

27.What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
ServletRequest.getRequestDispatcher(String path)
ServletContext.getRequestDispatcher(String path)
The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept relative paths. All path must start with a “/” and are interpreted as relative to current context root.


28.What is preinitialization of a servlet?
A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

29.What is the element?
The element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The element is written in the deployment descriptor as follows:

ServletName
ClassName
1
Note: The container loads the servlets in the order specified in the element.
30.What is session?
A session refers to all the requests that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.


31.What is Session Tracking?
Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

32.What is the need of Session Tracking in web application?
HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is reffered as "state". To keep track of this state we need session tracking.

Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests.

33.What are the types of Session Tracking ?
Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:
  • URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies.
  • Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.
  • Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie's value can uniquely identify a client.
  • Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation.
Learn more about Session Tracking




34.How do I use cookies to store session state on the client?
In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted during client requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code.
  • To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values.
  • To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest

35.What are some advantages of storing session state in cookies?
  • Cookies are usually persistent, so for low-security sites, user data that needs to be stored long-term (such as a user ID, historical information, etc.) can be maintained easily with no server interaction.
  • For small- and medium-sized session data, the entire session data (instead of just the session ID) can be kept in the cookie.
36.What are some disadvantages of storing session state in cookies?
  • Cookies are controlled by programming a low-level API, which is more difficult to implement than some other approaches.
  • All data for a session are kept on the client. Corruption, expiration or purging of cookie files can all result in incomplete, inconsistent, or missing information.
  • Cookies may not be available for many reasons: the user may have disabled them, the browser version may not support them, the browser may be behind a firewall that filters cookies, and so on. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Using cookies, and then switching to an alternate client-side session state strategy in cases where cookies aren't available, complicates development and maintenance.
  • Browser instances share cookies, so users cannot have multiple simultaneous sessions.
  • Cookie-based solutions work only for HTTP clients. This is because cookies are a feature of the HTTP protocol. Notice that the while package javax.servlet.http supports session management (via class HttpSession), package javax.servlet has no such support.

37.What is URL rewriting?
URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session.
Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages
  • URL rewriting works just about everywhere, especially when cookies are turned off.
  • Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances.
  • Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.

DisAdvantages
  • Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead.
  • URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page.
  • URL rewriting does not work well with JSP technology.
  • If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.


38.How can an existing session be invalidated?
An existing session can be invalidated in the following two ways:
  • Setting timeout in the deployment descriptor: This can be done by specifying timeout between the tags as follows:

<
session-timeout>10
This will set the time for session timeout to be ten minutes.

  • Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
public void setMaxInactiveInterval(int interval)
The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.Note :Setting the inactive period as negative(-1), makes the container stop tracking session, i.e, session never expires.

39.How can the session in Servlet can be destroyed?
An existing session can be destroyed in the following two ways:
  • Programatically : Using session.invalidate() method, which makes the container abonden the session on which the method is called.
  • When the server itself is shutdown.

40.A client sends requests to two different web components. Both of the components access the session. Will they end up using the same session object or different session ?
Creates only one session i.e., they end up with using same session .
Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session.

41.What is servlet lazy loading?
  • A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.
  • The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
  • The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

42.What is Servlet Chaining?
Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

43.How are filters?
Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows:
  • Security checks
  • Modifying the request or response
  • Data compression
  • Logging and auditing
  • Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.

44.What are the functions of an intercepting filter?
The functions of an intercepting filter are as follows:
  • It intercepts the request from a client before it reaches the servlet and modifies the request if required.
  • It intercepts the response from the servlet back to the client and modifies the request if required.
  • There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.


45.What are the functions of the Servlet container?
The functions of the Servlet container are as follows:
  • Lifecycle management : It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
  • Communication support : It handles the communication between the servlet and the Web server.
  • Multithreading support : It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
  • Declarative security : It manages the security inside the XML deployment descriptor file.
  • JSP support : The container is responsible for converting JSPs to servlets and for maintaining them.