Sunday, November 18, 2007

Servlet Interview Questions

Q: Explain the life cycle methods of a Servlet.

A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

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


Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

A: 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 accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.


Q: Explain the directory structure of a web application.

A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory


Q: What are the common mechanisms used for session tracking?

A: Cookies
SSL sessions
URL- rewriting

Q: Explain ServletContext.

A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.


Q: What is preinitialization of a servlet?

A: 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.


Q: What is the difference between Difference between doGet() and doPost()?

A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.


Q: What is the difference between HttpServlet and GenericServlet?

A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.

Q: What is the difference between ServletContext and ServletConfig?

A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized

ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

What is a servlet?

Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

Whats the advantages using servlets over using CGI?

Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

What are the general advantages and selling points of Servlets?
A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online
real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

Which package provides interfaces and classes for writing servlets?
javax

What’s the 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 such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet.

The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

When a servlet accepts a call from a client, it receives two objects. What are they?
ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package.

What information does ServletRequest allow access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names
of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods.

What type of constraints can ServletResponse interface set on the client?
It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through
which the servlet can send the reply data.

Explain servlet lifecycle?
Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down.
How does HTTP Servlet handle client requests?
An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

when a Servlet doesnt need to call the super.init(ServletConfig) in its init() method
When the servlet directly implements the javax.servlet.Servlet Interface

What is preinitialization of a servlet?

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.

Sunday, October 7, 2007

Installing the EJB 2.0 Container with Weblogic

To install EJB 2.0 for BEA WebLogic Server:

Download the weblogic510ejb20b1.zip file.

Unzip the contents of weblogic510ejb20b1.zip to a temporary directory. You should have three files named ejb20.jar, ejb20-cmp.jar, and ejb20-examples.zip.
Create a persistence20 directory in lib subdirectory of your existing WebLogic Server Version 5.1 installation:

$ mkdir %WL_HOME%\lib\persistence20

Copy the ejb20-cmp.jar file to the /lib/persistence20 subdirectory.
$ cp ejb20-cmp.jar %WL_HOME%\lib\persistence20


Extract the ejb20-examples.zip file to the examples subdirectory of your existing WebLogic Server Version 5.1 installation:
$ cd %WL_HOME%
$ jar xvf path\ejb20-examples.zip


This creates an ejb20 subdirectory containing the EJB 2.0 examples.
Add the path to ejb20.jar to the beginning of the weblogic.classpath and Java classpath variables. For example, if you use setEnv.cmd and startWebLogic.cmd to start the server, edit the following lines.

Note:
ejb20.jar must appear at the beginning of weblogic.classpath.
In setEnv.cmd, add ejb20.jar to the beginning of the classpath, as in:
set CLASSPATH=path\ejb20.jar;c:\weblogic\lib\weblogic510sp3boot.jar;%JDK_CLASSES%%W
L_HOME%\license;%WL_HOME%\classes;%WL_HOME%\lib\weblogicaux.jar;%CLIENT_CLASSES%;%SERVER_CLASSES%%RMIFORMS%


In startWebLogic.cmd, add ejb20.jar to the beginning of the weblogic.classpath, as in:

set
WEBLOGIC_CLASSPATH=path\ejb20.jar;.\lib\persistence\weblogic510sp3.jar;.\licens
e;.\classes;.\lib\weblogicaux.jar;.\myserver\serverclasses

Saturday, October 6, 2007

JSP Interview Questions

What is the difference between JSP and Servlets ?

A JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.


2 Q What is difference between custom JSP tags and beans?
A Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag's behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library

JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags

Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences:

Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.


3 Q What are the different ways for session tracking?
A Cookies, URL rewriting, HttpSession, Hidden form fields


4 Q What mechanisms are used by a Servlet Container to maintain session information?
A Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information


5 Q Difference between GET and POST
A In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.

In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.



6 Q What is session?
A The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server.


7 Q What is servlet mapping?
A The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.


8 Q What is servlet context ?
A The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.


9 Q What is a servlet ?
A servlet is a java program that runs inside a web container.


10 Q Can we use the constructor, instead of init(), to initialize servlet?
A Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.


12 Q How many JSP scripting elements are there and what are they?
A There are three scripting language elements: declarations, scriptlets, expressions.


13 Q How do I include static files within a JSP page?
A Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.


14 Q How can I implement a thread-safe JSP page?
A You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page.


15 Q What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
A In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.


16 Q What are the lifecycle of JSP?
A When presented with JSP page the JSP engine does the following 7 phases.

Page translation: -page is parsed, and a java file which is a servlet is created.

Page compilation: page is compiled into a class file

Page loading : This class file is loaded.

Create an instance :- Instance of servlet is created

jspInit() method is called

_jspService is called to handle service calls

_jspDestroy is called to destroy it when the servlet is not required.


17 Q What are context initialization parameters?
A Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application.


18 Q What is a Expression?
A Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.


19 Q What is a Declaration?
A It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.


20 Q What is a Scriptlet?
A A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a . Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet's service method.

Monday, August 6, 2007

Database Two Phase Commit

Since the 1980s, two phase commit technology has been used to automatically control and monitor commit and/or rollback activities for transactions in a distributed database system. Two phase commit technology is used when data updates need to occur simultaneously at multiple databases within a distributed system. Two phase commits are done to maintain data integrity and accuracy within the distributed databases through synchronized locking of all pieces of a transaction.

Two phase commit is a proven solution when data integrity in a distributed system is a requirement. Two phase commit technology is mostly used for hotel and airline reservations, stock market transactions, banking applications, and credit card systems.

Applying two phase commit protocols ensures that execution of data transactions are synchronized, either all committed or all rolled back (not committed) to each of the distributed databases.

When dealing with distributed databases, such as in the client/server architecture, distributed transactions need to be coordinated throughout the network to ensure data integrity for the users. Distributed databases using the two phase commit technique update all participating databases simultaneously.

Two phase commit has two distinct processes that are accomplished in less than a fraction of a second:

1. The Prepare Phase, where the global coordinator (initiating database) requests that all participants (distributed databases) will promise to commit or rollback the transaction. (Note: Any database could serve as the global coordinator, depending on the transaction.)
2. The Commit Phase, where all participants respond to the coordinator that they are prepared, then the coordinator asks all nodes to commit the transaction. If all participants cannot prepare or there is a system component failure, the coordinator asks all databases to roll back the transaction.

Saturday, July 14, 2007

Portlet Preparer Tool

The Portlet Preparer Tool is used to create .portlet files out of JSR168 portlets contained in war file, thereby allowing Weblogic Workshop to import the contents of that war file as a new Portal Web Project.

import a war file containing JSR168 portlets, complete the following steps:

1. Extract portletConverter.jar to a temporary location on your hard drive (In the following instructions this directory will be called ).
2. Place your war file in .
3. Set the WEBLOGIC_HOME in env.sh or env.bat (depending on your platform).
4. run env.sh or env.bat (depending on your platform).
5. run ant -Dwar.file= (where is the name of the war file).
A directory called tempDir under is created.
Open WebLogic Workshop and import the tempDir as a Portal Web Project.

To add portlets to an existing portal webapp, complete the following steps:
1. Complete steps 1-7 above.
2. Copy any necessary classes to the WEB-INF\classes directory and the necessary jars to the WEB-INF\lib directory.
3. Make necessary changes to the web.xml (example: servlet definitions).
4. Add elements to the portlet.xml for each portlet added (these can be copied from the portlet.xml in the tempDir created above).
5. Copy the .portlet files from tempDir\portlets to your webapp
6. Add the portlets to your portal.


You can download this tool : Download ....

Friday, July 6, 2007

MBeans in Weblogic Server

System administration infrastructure in WebLogic Server is implemented using the Java Management Extension (JMX) specification from Sun Microsystems. The JMX API models system administration functions with Java objects called MBeans.

There are three types of MBeans used to manage a WebLogic Server domain:

1. Administration
2. Configuration
3. Runtime Mbeans

Administration Mbeans :

It contain a set of attributes that define configuration parameters for various management functions. All attributes for administration MBeans have pre-set default values. When the Administration Server starts, it reads a file called config.xml and overrides the default attribute values of the administration MBeans with any attribute values found in the config.xml file.


The config.xml file, located on the machine that hosts the Administration Server, provides persistent storage of Mbean attribute values. Every time you change an attribute using the system administration tools, its value is stored in the appropriate administration MBean and written to the config.xml file. Each WebLogic Server domain has its own config.xml file.

If you set any configuration attributes on the command line when you start the Administration Server using the -D arguments, these values override the values set by the defaults or those read from the config.xml file. These overridden values are also persisted to config.xml file by the Administration Server.

Configuration Mbeans :

It's copies of Administration Mbeans that each Managed Server uses to initialize its configuration. When you start a Managed Server, the server receives a copy of the of all the administration MBeans from the Administration Server and stores them in memory as configuration MBeans. If you override any configuration attributes when starting a Managed Server, those values override the values received from the Administration Server but are not written to the config.xml file.

Runtime Mbeans :

It contain sets of attributes consisting of runtime information for active WebLogic Servers instances and applications. By retrieving the values of attributes in these runtime MBeans, you can monitor the running status of a WebLogic Server domain.

Mbeans may also contain operations used to execute management functions.