Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Monday, July 7, 2008

Navigating with Servlets

The first thing to understand is how a servlet begins and ends. Similar to an applet, the life cycle of the servlet begins with an automatic call to its init method. The init method is called once by the server for initialization and not again for each user request. Because the server creates a single class instance that handles every request of the servlet, performance is greatly improved, eliminating the need to create overhead that would otherwise be necessary if each request required the server to create a new object.

Next, the service method is called, performing the work of the servlet, and passing ServletRequest and ServletResponse objects as needed. These objects collect or pass information such as the values of the named attributes, theIP address of the agent, or the port number on which the request was received.

Lastly, like an applet, it is time to remove a previously loaded servlet instance, the servlet's destroy method is called. This gives the servlet a chance to close database connections, save information to a log file, or perform other cleanup tasks before it is shut down. If you have special cleanup tasks you'd like your servlet to perform before being removed from memory, the destroy is the place to write those instructions.

All three methods, init, service, and destroy, can be overridden.

If you need a servlet to load with customized initialization behavior, you can override the init method using either of the following two formats:

No argument format:

public void init()throws ServletException{

Takes ServletConfig object:

public void init(ServletConfig config)
throws ServletException {
super.init(config);
//Initialization code . .


The latter is used when the servlet needs to be initialized with server information such as:

1. Password files
2. A hit count number
3. Serialized cookie information
4. Data from previous requests

When using the ServletConfig format, create a call to the super.init so that the super class registers the information where the servlet can find it later.

Which format you use depends on what information needs to be known at initialization time. If no information is needed when the servlet is first invoked, then the no argument format may be used.

The Heart of the Servlet

The javax.servlet package and the javax.servlet.http package provide the classes and interfaces to define servlets. HTML servlet classes extend the javax.servlet.http.HttpServlet abstract class, which provides a framework for handling HTTP protocol. Because HttpServlet is abstract your servlet must extend it and override at least one of the following methods:

1. doGetget information such as a document, the results of a database query, or strings passed from the browser.
2. doPost posts information such as data to be stored in a database, user login and password information, or other strings passed from the browser.
3. doPutplaces documents directly on the server.
doDelete deletes information or documents from the server.
4. getServletInfo returns descriptive information about the servlet, possibly its purpose, author, or version number.

These methods are the heart of the servlet, where instructions and the purpose of the servlet are carried out. You will likely only need to use, or override, a few of the methods. RedirectServlet overrides doGet and doPost, but does not need any of the other methods.

public class Example extends HttpServlet {
public void doGet ( HttpServletRequest req,
HttpServletResponse res)

When a client calls a servlet by typing the URL in the browser, submitting a form, or clicking a button on a menu, the servlet's service method checks the HTTP request type, such as POST or GET. This in turn calls doGet, doPOST, doPUT, or doDelete as needed.

You can override the service method without implementing doGet and doPost, but it's generally better to call both doGet and doPost. See the JDC RedirectServlet.

The doPost and doGet Methods

The doPost or doGet methods instruct the server about what it must do, whether printing information back to the client's browser, writing to a database, or simply redirecting the client to a requested URL. Within these methods you will use Java programming syntax to give specific instructions for the servlet to interact between the client and the server.

Servlets to Process Forms

A form is a powerful web site tool, enabling clients to take polls, enter personal information for online shopping, or subscribe to an e-newsletter. In other words, forms turn static web pages into dynamic pages. But a form cannot give instructions to a server. Without an application between the form and the server, the form is useless.

Servlets process form information in three steps:

1. Retrieve or request the data
2. Store or passing the data
3. Respond to the request

RedirectServlet Servlet

As with most servlets, the JDC RedirectServlet imports the following packages:

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

Servlets extend the abstract HttpServlet class, whichextends the GenericServlet base class.

public class RedirectServlet extends HttpServlet {
So the servlet collects the parameter NAME and corresponding value as a String pair, the String object must be declared:

private String paramName;

To initialized the servlet with the NAME and value String pair, the init method is overridden, and the ServletConfig object is passed as a parameter. Because errors can occur, such as a bad URL, the throws ServletException is included.

public void init(ServletConfig config)
throws ServletException {

When overriding the init method, call super.init(config). After the call to super.init(config), the servlet can invoke its own getInitParameter method as shown.The getInitParameter method returns a string containing the value of the named initialization parameter, or null if the requested parameter does not exist. Init parameters have a single string value.

super.init(config);
paramName =
config.getInitParameter("paramName");
}

A servlet must override doGet or doPost, depending on whether data is sent by POST or GET in the HTML form. The drawback to overriding only one of these methods is that if production changes the HTML form to call POST instead of GET, the servlet won't work. Generally, it is better to override both methods, as shown below.

RedirectServlet overrides the doGet method and takes two arguments:

HttpServletRequest, with the variable req

HttpServletRequest has useful methods such as getParameter that takes the value of a NAME attribute as a string or null if the parameter does not exist.

HttpServletResponse with the variable res has methods that let you specify outgoing information, such as getWriter, which returns a print writer for writing formatted text responses to the browser, or in this case sendRedirect, which sends a temporary redirect response to the client using the specified redirect location URL.

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect(
request.getParameter(paramName));

The doGet method calls the getParameter method through the request object, passing in the paramName object and its value as a string pair, in this case url and the actual URL. A special sendRedirect method then passes the string to the browser and redirects the user to the desired destination.

The RedirectServlet also forces doPost to call doGet, making it possible to use GET or POST in the HTML form without breaking the servlet.


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

As long as the value is not null, the code moves onto the res object and its sendRedirect method, which redirects the client to the URL that was passed to the method.This makes for smooth navigation when a client's browsers cannot support JavaScript, or the user has JavaScript toggled off.

Web site design issues frequently pose challenges because of browser incompatibility, user preferences, and non-browser problems, such as sending information to a database or email address. Servlets serve functionality in these situations, acting as a messenger between HTML pages and the server, or as back-up for other technologies.

RedirectServlet is a short yet reliable servlet that works as back-up to JavaScript, and it doesn't need to deal with browser compatibility, or other client related issues because it works on the server side.

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.