Q.1)What is Jakarta Struts Framework?
Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
Q.2)What is MVC ?
The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.
1). Model: The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
2). View :The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
3). Controller: Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In GUIs, the views and the controllers often work very closely together.
Q.3)Why we should use the MVC design pattern?
They are resuable : When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.
They are expressive: By using the MVC design pattern our application becomes more expressive.
Q.4)What is ActionServlet?
A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.
Q.5)What is role of ActionServlet?
ActionServlet performs the role of Controller:
1)Process user requests
2)Determine what the user is trying to achieve according to the request
3)Pull data from the model (if necessary) to be given to the appropriate view,
4)Select the proper view to respond to the user
5)Delegates most of this grunt work to Action classes
6)Is responsible for initialization and clean-up of resources
Q.6)What is Action Class?
The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. The ActionServlet passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.
Q.7)What is the ActionForm?
ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.
Q.8)What is the life cycle of ActionForm?
The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
1)Retrieve or Create Form Bean associated with Action
2)"Store" FormBean in appropriate scope (request or session)
3)Reset the properties of the FormBean
4)Populate the properties of the FormBean
5)Validate the properties of the FormBean
6)Pass FormBean to Action
Q.9)What is the signature of execute() method?
public ActionForward execute(
ActionMapping mapping,
ActionForm form,HttpServletRequest request,
HttpServletResponse response)
throws Exception ;
Q.10)What is Struts Validator Framework?
Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.
Q.11)What design patterns are used in Struts?
1)Service to Worker
2)Dispatcher View
3)Composite View (Struts Tiles)
4)Front Controller
5)View Helper
6)Synchronizer Token
Q12)Give the Details of XML files used in Validator Framework?
The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.
Q.13)How you will display validation fail errors on jsp page?
Use <html:errors/>
Q.14) How you will enable front-end validation based on the xml in validation.xml?
The <html:javascript> tag to allow front-end validation based on the xml in validation.xml.
For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.
Q.15)What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:
ForwardAction
IncludeAction
DispatchAction
LookupDispatchAction
SwitchAction
Q.16)What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.
Q.17)What is the use of ForwardAction?
ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class.You just have to set up the struts-config file properly to use ForwardAction.
Q.18)What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.
Q.19)What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.
Q.20)What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.
Q.21)What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.
Q.22)What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.
Q.23)What are the various Struts tag libraries?
Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:
1)Bean tag library - Tags for accessing JavaBeans and their properties.
2)HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
3)Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
4)Tiles or Template tag library - For the application using tiles
5)Nested tag library - For using the nested beans in the application
6)Template
Q.24)Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:
<servlet>
<servlet-name>banking</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml,
/WEB-INF/struts-authentication.xml,
/WEB-INF/struts-help.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Q.25)What are the core classes of the Struts Framework?
Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc.
Q.26)What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean.
Q.27)How the exceptions are handled in struts?
Struts handle exception in two ways:-
Programmatic exception handling :
Explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs.
Declarative exception handling :You can either define <global-exceptions> handling tags in your struts-config.xml or define the exception handling tags within <action></action> tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.
Q.28)What are differences between <bean:message> and <bean:write>?
<bean:message>: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.
<bean:message key="prompt.customer.firstname"/>
<bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body.
<bean:write name="customer" property="firstName"/>
Q.29)What are difference between ActionErrors and ActionMessage?
ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property.Each individual message is described by an ActionMessage object, which contains a message key,and up to four placeholder arguments used for parametric substitution in the resulting message.
ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property
Q.30)Is struts threadsafe?Give an example?
Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action
Q.31)What are the disadvantages of Struts?
Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts:
a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts.
Harder to learn
Struts are harder to learn, benchmark and optimize.
Q.32)How Struts relates to J2EE?
Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.
Q.33)What if <action> element has <forward> declaration with same name as global forward?
In this case the global forward is not used. Instead the <action> element’s <forward> takes precendence.
This Blog contain the core java and JSP related all interview questions and answers.
Sunday, October 2, 2011
Saturday, October 1, 2011
Java Thread
Introduction to Threads
A thread is a thread of execution in a program. The Java
Virtual Machine allows an application to have multiple threads of
execution running concurrently.
Every thread has a priority. Threads with higher priority are
executed in preference to threads with lower priority. Each thread
may or may not also be marked as a daemon. When code running in
some thread creates a new
Thread
object, the new
thread has its priority initially set equal to the priority of the
creating thread, and is a daemon thread if and only if the
creating thread is a daemon.
This approach of creating a thread by implementing the Runnable Interface must be used whenever the class being used to instantiate the thread object is required to extend some other class.
Multithreading has several advantages over Multiprocessing such as;
- Threads are lightweight compared to process
- Threads share the same address space and therefore can share both data and code
- Context switching between threads is usually less expensive than between processes
- Cost of thread intercommunication is relatively low that that of process intercommunication
- Threads allow different tasks to be performed concurrently.
Methods of the Object and Thread Class.
Object: notify,notifyAll(),wait()
Thread:-sleep(),yield()
Thread Creation
There are two ways to create thread in java;
- Implement the Runnable interface (java.lang.Runnable)
- By Extending the Thread class (java.lang.Thread)
Implementing the Runnable Interface
The Runnable Interface Signature
public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.
Extending Thread Class
The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.
When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:
- Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option.
- A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.
Synchronization:-
With respect to multithreading,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 a particular 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 which may otherwisel lead to dirty reads and significant errors.
Generally critical sections of the code are usually marked with synchronized keyword.
example of using Thread Synchronization is in “The Producer/Consumer Model”.
Locks:-are used to synchronize access to a shared resource. A lock can be associated with a shared resource.Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code.At any given time, at most only one thread can hold the lock and thereby have access to the shared resource.A lock thus implements mutual exclusion.The object lock mechanism enforces the following rules of synchronization:
A thread must acquire the object lock associated with a shared resource, before it can enter the shared resource. The runtime system ensures that no other thread can enter a shared resource if another thread already holds the object lock associated with the shared resource. If a thread cannot immediately acquire the object lock, it is blocked, that is, it must wait for the lock to become available.When a thread exits a shared resource, the runtime system ensures that the object lock is also relinquished.If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain access to the shared resource.
Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually a
lock on the java.lang.Class object associated with the class. Given a class A, the reference A.class
denotes this unique Class object. The class lock can be used in much the same way as an object lock to implement mutual exclusion.
There can be 2 ways through which synchronized can be implemented in Java:
- synchronized methods
- synchronized blocks
Synchronized statements are same as synchronized methods. A synchronized statement can only be
executed after a thread has acquired the lock on the object/class referenced in the synchronized statement.
Synchronized Methods
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. .If the lock is already held by another thread, the calling thread waits. A thread relinquishes the lock simply by returning from the synchronized method, allowing the next thread waiting for this lock to proceed. Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. This is called a race condition. It occurs when two or more threads simultaneously update the same value, and as a consequence, leave the value in an undefined or inconsistent state. While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait until it gets the lock. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread.
Synchronized Blocks
Static methods synchronize on the class lock. Acquiring and relinquishing a class lock by a thread in order to execute a static synchronized method, proceeds analogous to that of an object lock for a synchronized instance method. A thread acquires the class lock before it can proceed with the execution of any static synchronized method in the class, blocking other threads wishing to execute any such methods in the same class. This, of course, does not apply to static, non-synchronized methods, which can be invoked at any time. Synchronization of static methods in a class is independent from the synchronization of instance methods on objects of the class. A subclass decides whether the new definition of an inherited synchronized method will remain synchronized in the subclass.The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.
The general form of the synchronized block is as follows:
synchronized (<object reference expression>) {
<code block>
}
A compile-time error occurs if the expression produces a value of any primitive type. If execution of the block completes normally, then the lock is released. If execution of the block completes abruptly, then the lock is released.
A thread can hold more than one lock at a time. Synchronized statements can be nested. Synchronized statements with identical expressions can be nested. The expression must evaluate to a non-null reference value, otherwise, a NullPointerException is thrown.
The code block is usually related to the object on which the synchronization is being done. This is the case with synchronized methods, where the execution of the method is synchronized on the lock of the current object:
public Object method() {
synchronized (this) { // Synchronized block on current object
// method block
}
}
Once a thread has entered the code block after acquiring the lock on the specified object, no other thread will be able to execute the code block, or any other code requiring the same object lock, until the lock is relinquished. This happens when the execution of the code block completes normally or an uncaught exception is thrown.
Object specification in the synchronized statement is mandatory. A class can choose to synchronize the execution of a part of a method, by using the this reference and putting the relevant part of the method in the synchronized block. The braces of the block cannot be left out, even if the code block has just one statement.
class SmartClient {
BankAccount account;
// …
public void updateTransaction() {
synchronized (account) { // (1) synchronized block
account.update(); // (2)
}
}
}
In summary, a thread can hold a lock on an object
- by executing a synchronized instance method of the object
- by executing the body of a synchronized block that synchronizes on the object
- by executing a synchronized static method of a class
Thread States
A Java thread is always in one of several states which could be running, sleeping, dead, etc.
A thread can be in any of the following states:
- New Thread state (Ready-to-run state)
- Runnable state (Running state)
- Not Runnable state
- Dead state
New Thread
A thread is in this state when the instantiation of a Thread object creates a new thread but does not
start it running. A thread starts life in the Ready-to-run state. You can call only the start() or stop()
methods when the thread is in this state. Calling any method besides start() or stop() causes an
IllegalThreadStateException.
Runnable
When the start() method is invoked on a New Thread() it gets to the runnable state or running state by calling the run() method. A Runnable thread may actually be running, or may be awaiting its turn to run.
Not Runnable
A thread becomes Not Runnable when one of the following four events occurs:
- When sleep() method is invoked and it sleeps for a specified amount of time
- When suspend() method is invoked
- When the wait() method is invoked and the thread waits for notification of a free resource or waits for
the completion of another thread or waits to acquire a lock of an object. - The thread is blocking on I/O and waits for its completion
Example: Thread.currentThread().sleep(1000);
Note: Thread.currentThread() may return an output like Thread[threadA,5,main]
The output shown in bold describes
- the name of the thread,
- the priority of the thread, and
- the name of the group to which it belongs.
A thread can be awakened abruptly by invoking the interrupt() method on the sleeping thread object or at the end of the period of time for sleep is over. Whether or not it will actually start running depends on its priority and the availability of the CPU.
How a thread switches form a non runnable to a runnable state:
either notify() or notifyAll().
Dead State
A thread enters this state when the run() method has finished executing or when the stop() method is invoked. Once in this state, the thread cannot ever run again.
Thread Priority
In Java we can specify the priority of each thread relative to other threads. Those threads having higher priority get greater access to available resources then lower priority threads. A Java thread inherits its priority from the thread that created it. Heavy reliance on thread priorities for the behavior of a program can make the program non portable across platforms, as thread scheduling is host platform–dependent.You can modify a thread’s priority at any time after its creation using the setPriority() method and retrieve the thread priority value using getPriority() method.
The following static final integer constants are defined in the Thread class:
The following static final integer constants are defined in the Thread class:
- MIN_PRIORITY (0) Lowest Priority
- NORM_PRIORITY (5) Default Priority
- MAX_PRIORITY (10) Highest Priority
The priority of an individual thread can be set to any integer value between and including the above defined constants.When two or more threads are ready to be executed and system resource becomes available to execute a thread, the runtime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution.“If two threads of the same priority are waiting for the CPU, the thread scheduler chooses one of them to run in a > round-robin fashion. The chosen thread will run until one of the following conditions is true:
- a higher priority thread becomes Runnable. (Pre-emptive scheduling)
- it yields, or its run() method exits
- on systems that support time-slicing, its time allotment has expired
Thread Scheduler
Schedulers in JVM implementations usually employ one of the two following strategies:
Preemptive scheduling
If a thread with a higher priority than all other Runnable threads becomes Runnable, the scheduler will preempt the running thread (is moved to the runnable state) and choose the new higher priority thread for execution.
Time-Slicing or Round-Robin scheduling
A running thread is allowed to execute for a fixed length of time (a time slot it’s assigned to), after which it moves to the Ready-to-run state (runnable) to await its turn to run again.
A thread scheduler is implementation and platform-dependent; therefore, how threads will be scheduled is unpredictable across different platforms.
A thread scheduler is implementation and platform-dependent; therefore, how threads will be scheduled is unpredictable across different platforms.
Yielding
A call to the static method yield(), defined in the Thread class, will cause the current thread in the Running state to move to the Runnable state, thus relinquishing the CPU. The thread is then at the mercy of the thread scheduler as to when it will run again. If there are no threads waiting in the Ready-to-run state, this thread continues execution. If there are other threads in the Ready-to-run state, their priorities determine which thread gets to execute. The yield() method gives other threads of the same priority a chance to run. If there are no equal priority threads in the “Runnable” state, then the yield is ignored.
Sleeping and Waking Up
The thread class contains a static method named sleep() that causes the currently running thread to pause its execution and transit to the Sleeping state. The method does not relinquish any lock that the thread might have. The thread will sleep for at least the time specified in its argument, before entering the runnable state where it takes its turn to run again. If a thread is interrupted while sleeping, it will throw an InterruptedException when it awakes and gets to execute. The Thread class has several overloaded versions of the sleep() method.
Waiting and Notifying
Waiting and notifying provide means of thread inter-communication that synchronizes on the same object. The threads execute wait() and notify() (or notifyAll()) methods on the shared object for this purpose. The notifyAll(), notify() and wait() are methods of the Object class. These methods can be invoked only from within a synchronized context (synchronized method or synchronized block), otherwise, the call will result in an IllegalMonitorStateException. The notifyAll() method wakes up all the threads waiting on the resource. In this situation, the awakened threads compete for the resource. One thread gets the resource and the others go back to waiting.
wait() method signatures
final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException .
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException .
wait() call can specify the time the thread should wait before being timed out. An another thread can invoke an interrupt() method on a waiting thread resulting in an InterruptedException. This is a checked exception and hence the code with the wait() method must be enclosed within a try catch block.
notify() method signatures
final void notify()
final void notifyAll()
A thread usually calls the wait() method on the object whose lock it holds because a condition for its continued execution was not met. The thread leaves the Running state and transits to the Waiting-for-notification state. There it waits for this condition to occur. The thread relinquishes ownership of the object lock. The releasing of the lock of the shared object by the thread allows other threads to run and execute synchronized code on the same object after acquiring its lock.
The wait() method causes the current thread to wait until another thread notifies it of a condition change.Joining A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.
Consider a thread t1 invokes the method join() on a thread t2. The join() call has no effect if thread t2 has already completed. If thread t2 is still alive, then thread t1 transits to the Blocked-for-join-completion state.
final void notify()
final void notifyAll()
A thread usually calls the wait() method on the object whose lock it holds because a condition for its continued execution was not met. The thread leaves the Running state and transits to the Waiting-for-notification state. There it waits for this condition to occur. The thread relinquishes ownership of the object lock. The releasing of the lock of the shared object by the thread allows other threads to run and execute synchronized code on the same object after acquiring its lock.
The wait() method causes the current thread to wait until another thread notifies it of a condition change.Joining A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.
Consider a thread t1 invokes the method join() on a thread t2. The join() call has no effect if thread t2 has already completed. If thread t2 is still alive, then thread t1 transits to the Blocked-for-join-completion state.
Deadlock
There are situations when programs become deadlocked when each thread is waiting on a resource that cannot become available. The simplest form of deadlock is when two threads are each waiting on a resource that is locked by the other thread. Since each thread is waiting for the other thread to relinquish a lock, they both remain waiting forever in the Blocked-for-lock-acquisition state. The threads are said to be deadlocked.
Note: The following methods namely join, sleep and wait name the InterruptedException in its throws clause and can have a timeout argument as a parameter. The following methods namely wait, notify and notifyAllshould only be called by a thread that holds the lock of the instance on which the method is invoked. The Thread.start method causes a new thread to get ready to run at the discretion of the thread scheduler. The Runnable interface declares the run method. The Thread class implements the Runnable interface. Some implementations of the Thread.yield method will not yield to a thread of lower priority. A program will terminate only when all user threads stop running. A thread inherits its daemon status from the thread that created it
Note: The following methods namely join, sleep and wait name the InterruptedException in its throws clause and can have a timeout argument as a parameter. The following methods namely wait, notify and notifyAllshould only be called by a thread that holds the lock of the instance on which the method is invoked. The Thread.start method causes a new thread to get ready to run at the discretion of the thread scheduler. The Runnable interface declares the run method. The Thread class implements the Runnable interface. Some implementations of the Thread.yield method will not yield to a thread of lower priority. A program will terminate only when all user threads stop running. A thread inherits its daemon status from the thread that created it
Servlet Interview Question and Answers
Q.1)What is the difference between CGI and Servlet?
CGI:-Traditional CGI creates a heavy weight process to handle each http request. N number of copies of the same traditional CGI programs is copied into memory to serve N number of requests.
Servlet:-Its a lightweight Java thread to handle each http request. Single copy of a type of servlet but N number of threads (thread sizes can be configured in an application server).
A Servlet is a Java class that runs within a web container in an application server, servicing multiple client requests concurrently forwarded through the server and the web container. The web browser establishes a socket connection to the host server in the URL , and sends the HTTP request. Servlets can forward requests to other servers and servlets and can also be used to balance load among several servers.
Q.2)Which protocol is used to communicate between a browser and a servlet?
A browser and a servlet communicate using the HTTP protocol (a stateless request/response based protocol).
Q.3) What are the two objects a servlet receives when it accepts a call from its client?
A “ServletRequest”, which encapsulates client request from the client and the “ServletResponse”, which encapsulates the communication from the servlet back to the client.
Q.4) What can you do in your Servlet/JSP code to tell browser not to cache the pages?
response.setHeader(“Cache-Control”,“no-cache”); //document should never be cached. HTTP 1.1
response.setHeader(“Pragma”, “no-cache”); //HTTP 1.0
response.setDateHeader(“Expires”, 0);
Q.5) What is the difference between request parameters and request attributes?
Request parameters:
a)Parameters are form data that are sent in the request from the HTML page. These parameters are generally form fields in an HTML form.
b)You can get them but cannot set them.
Request attributes:
a)Once a servlet gets a request, it can add additional attributes, then forward the request off to other servlets or JSPs for processing. Servlets and JSPs can communicate with each other by setting and getting attributes.
b)You can both set the attribute and get the attribute. You can also get and set the attributes in session and application scopes.
Q.6) What are the different scopes or places where a servlet can save data for its processing?
request
session
application
Q.7)How does a Servlet differ from an Applet?
Applet:
Applets execute on a browser
Applets have a graphical user interface
Servlet:
Servlets execute within a web container in an Application Server.
Servlets do not have a graphical user interface.
Q.8)HTTP is a stateless protocol, so, how do you maintain state? How do you store user data between requests?
HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable.
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.
Q.10)What is the difference between using getSession(true) and getSession(false) methods?
getSession(true): This method will check whether there is already a session exists for the user. If a session exists, it returns that session object. If a session does not already exist then it creates a new session for the user.
getSession(false): This method will check whether there is already a session exists for the user. If a session exists, it returns that session object. If a session does not already exist then it returns null.retrieve stored state information for the supplied JSESSIONID.Servlet Sessions can be timed out (configured in web.xml) or manually invalidated.
Q.11)How can you set a cookie and delete a cookie from within a Servlet?
To add a cookie
Cookie myCookie = new Cookie(“aName”, “aValue”);
response.addCookie(myCookie);
To delete a cookie
myCookie.setValue(“aName”, null);
myCookie.setMax(0);
myCookie.setPath(“/”);
response.addCookie(myCookie);
Q.12) Explain the life cycle methods of a servlet?
These three method going to be call in servlet life cycle:-
1)public void init(ServletConfig config) throws ServletException
2)public void service(ServletRequest req,ServletResponse res) throws
ServletException,IOException
3)public void destroy()
Q.13)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.
Q.14)Explain the directory structure of a Web application?
The directory structure of a Web application consists of two parts:
A public resource directory(document root):The document root is where JSP pages,client-side classes and archives, and static Web resources are stored.
A private directory called WEB-INF:which contains following files and directories:
web.xml:Web application deployment descriptor. application server specific deployment descriptor e.g.jboss-web.xml etc.
*.tld:Tag library descriptor files.
classes:A directory that contains serverside classes like servlets,utility classes,JavaBeans etc.
lib:A directory where JAR(archive files of tag libraries,utility libraries used by the server side classes)
files are stored.
Q.15)What is the difference between doGet () and doPost () or GET and POST?
GET or doGet()
a)The request parameters are transmitted as a query string appended to the request. All the parameters get appended to the URL in the address bar. Allows browser bookmarks but not appropriate for transmitting private or sensitive information.
b)GET was originally intended for static resource retrieval.
c)GET is not appropriate when large amounts of input data are being transferred. Limited to 1024 characters
POST or doPost()
a)The request parameters are passed with the body of the request.
b)POST was intended for form submits where the state of the model and database are expected to change.
c)Since it sends information through a socket back to the server and it won’t show up in the URL address bar, it can send much more information to the server. Unlike doGet(), it is not restricted to sending only textual data. It can also send binary data such as serialized Java objects.
Q.16)What are the ServletContext and ServletConfig objects?
ServletConfig
The ServletConfig parameters are for a particular Servlet. The parameters are specified in the web.xml . It is created after a servlet is instantiated and it is used to pass initialization information to the servlet.
ServletContext :
The ServletContext parameters are specified for the entire Web application. The parameters are specified in the web.xml. Servlet context is common to all Servlets. So all Servlets share information through ServletContext.
Q.17) What is the difference between HttpServlet and GenericServlet?
Both these classes are abstract but:
GenericServlet:
a)A GenericServlet has a service() method to handle requests.
b)Protocol independent. GenericServlet is for servlets that might not use HTTP (for example FTP service).
HttpServlet:
a)The HttpServlet extends GenericServlet and adds support for HTTP protocol based methods like doGet(), doPost(), doHead() etc.HttpServlet also has methods like doHead(), doPut(), doOptions(), doDelete(), and doTrace().
b)Protocol dependent (i.e. HTTP).
Q.18) How do you make a Servlet thread safe?
The shared resources should be appropriately synchronized or should only use variables in a read-only manner. There are situations where synchronizing will not give you the expected results and to achieve the expected results you should store your values in a user session or store them as a hidden field values. Having large chunks of code in synchronized blocks in your service or doPost() methods can adversely affect performance and makes the code more complex.
Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel.
Q.19)How do you get your servlet to stop timing out on a really long database query?
Client-pull or client-refresh: You can use the <META> tag for polling the server. This tag tells the client it must refresh the page after a number of seconds.
<META http-equiv=”Refresh” content=”10; url=”newPage.html” />
Q.20)What is lazy loading of a Servlet?
By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading.
Q.21)What is pre-initialization of a Servlet?
The servlet deployment descriptor (web.xml) defines the
<load-on-startup> element, which can be configured 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 pre-loading or pre-initializing a servlet. We can also specify
the order in which the servlets are initialized.
<load-on-startup>2</load-on-startup>
Q.22)What is a filter, and how does it work?
A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses but typically do not themselves create responses. Filters can also be used to transform the response from the Servlet or JSP before sending it back to client. Filters improve reusability by placing recurring tasks in the filter as a reusable unit.
Q.23)What do you understand by servlet
mapping?
Servlet mapping defines an
association between a URL pattern and a servlet. You can use one servlet to
process a number of url pattern (request pattern). For example in case of Struts
*.do url patterns are processed by Struts Controller Servlet.
Q.24)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.
Q.25)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.
Q.26)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. Q.27)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. Q.28)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.
Q.29)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 <init-param> within the <servlet> tags in the web.xml file | The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.xml file. |
Q.30)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 URL | A 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 retained | Because 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. |
Q.31)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. |
Q.32)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.
Q.33)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.
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
<session-timeout>
tags as follows:
<session-config>
<session-timeout>10</session-timeout>
</session-config>
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 seMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.
Q.35)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.
Q.36)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.
Labels:
cookies,
doGet,
doPost,
filter,
forward,
include,
Life Cycle,
request dispatcher,
sendRedirect,
Servlet,
servlet chaining,
servlet container,
servlet wrapper classes,
ServletConfig,
ServletContext,
session tracking
Subscribe to:
Posts (Atom)