« PreviousNext »

Servlets–>Notes

11 October 2006

javax.servlet.Servlet interface is very important because it encapsulates the life cycle methods of a servlet and it is the interface that all servlets must implement. “The javax.servlet Package Reference.”
The seven interfaces are as follows:
• RequestDispatcher
• Servlet
• ServletConfig
• ServletContext
• ServletRequest
• ServletResponse
• SingleThreadModel
The three classes are as follows:
• GenericServlet
• ServletInputStream
• ServletOutputStream
And, finally, the exception classes are these:
• ServletException
• UnavailableException

A Servlet’s Life Cycle
The init( ) Method
The init method is called by the servlet container after the servlet class has been instantiated. The servlet container calls this method exactly once to indicate to the servlet that the servlet is being placed into service. The init method must complete successfully before the servlet can receive any requests. You can override this method to write initialization code that needs to run only once, such as loading a database driver, initializing values
public void init(ServletConfig config) throws ServletException
The service( ) Method
Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Therefore, you must be aware to synchronize access to any shared resources, such as files, network connections, and the servlet’s class and instance variables.
public void service(ServletRequest request, ServletResponse response)
  throws ServletException, java.io.IOException
The destroy( ) Method
The servlet container calls the destroy method before removing a servlet instance from service. This normally happens when the servlet container is shut down or the servlet container needs some free memory.
This method is called only after all threads within the servlet’s service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.
The destroy method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, and threads) and make sure that any persistent state is synchronized with the servlet’s current state in memory.
The signature of this method is as follows:
public void destroy()
servlet’s config you have the option of specifying a set of initial parameter name/value pairs that you can retrieve from inside the servlet
The getInitParameterNames does not take an argument and returns an Enumeration containing all the parameter names in the ServletConfig object.
 getInitParameter takes a String containing the parameter name and returns a String containing the value of the parameter.

Preserving the ServletConfig :you may want to have access to the ServletConfig object from the service method, when you are servicing the user. In this case, you need to preserve the ServletConfig object to a class level variable.
ServletConfig servletConfig;

servlet’s context, the servlet context is the environment where the servlet runs. The servlet container creates a ServletContext object that you can use to access information about the servlet’s environment.

How do you obtain the ServletContext object? Indirectly, from the ServletConfig object passed by the servlet container to the servlet’s init method. The ServletConfig interface has a method called getServletContext that returns the ServletContext object.

• getAttributeNames. This method returns an enumeration of strings representing the names of the attributes currently stored in the ServletContext.
• getAttribute. This method accepts a String containing the attribute name and returns the object bound to that name.
• setAttribute. This method stores an object in the ServletContext and binds the object to the given name. If the name already exists in the ServletContext, the old bound object will be replaced by the object passed to this method.
• removeAttribute. This method removes from the ServletContext the object bound to a name. The removeAttribute method accepts one argument: the name of the attribute to be removed.
The ServletRequest Interface
The ServletRequest interface defines an object used to encapsulate information about the user’s request, including parameter name/value pairs, attributes, and an input stream.
The ServletResponse Interface
The ServletResponse interface represents the response to the user. The most important method of this interface is getWriter, from which you can obtain a java.io.PrintWriter object that you can use to write HTML tags and other text to the user.

 
The HttpServlet Class
As mentioned previously, the HttpServlet class extends the javax.servlet.GenericServlet class. The HttpServlet class also adds a number of interesting methods for you to use. The most important are the six doxxx methods that get called when a related HTTP request method is used. The six methods are doPost, doPut, doGet, doDelete, doOptions and doTrace. Each doxxx method is invoked when a corresponding HTTP method is used. For instance, the doGet method is invoked when the servlet receives an HTTP request that was sent using the GET method.
setHeader method. This method allows you to add a name/value field to the response header.

sendRedirect method to redirect the user to another page:. When you call this method, the web server sends a special message to the browser to request another page. Therefore, there is always a round trip to the client side before the other page is fetched.
display a special character, you need to encode it. The less-than character (< ) is encoded as "<" and the greater-than character (>) as “>”. Other special characters are the ampersand (&) and double quotation mark (”) characters. You replace the ampersand (&) with “&” and the double quotation marks (”) with “"”. Additionally, two or more white spaces are always displayed as a single space, unless you convert each individual space to “ ”.

Buffering the Response
If response buffering is enabled, the output to the browser is not sent until the servlet processing is finished or the buffer is full. Buffering enhances the performance of your servlet because the servlet needs to send the string output only once, instead of sending it every time the print or println method of the PrintWriter object is called. By default, buffering is enabled and the buffer size is 8,192 characters. You can change this value by using the HttpServletResponse interface’s setBufferSize method. This method can be called only before any output is sent

Populating HTML Elements
two rules:
1. Always enclose a value with double quotation marks (”). This way, white spaces will be rendered correctly.
2. If the value contains a double quotation mark character, you need to encode the double quotation marks (”).

Request Dispatching
In some circumstances, you may want to include the content from an HTML page or the output from another servlet. Additionally, there are cases that require that you pass the processing of an HTTP request from your servlet to another servlet. The current servlet specification responds to these needs with an interface called RequestDispatcher, which is found in the javax.servlet package. This interface has two methods, which allow you to delegate the request-response processing to another resource: include and forward. Both methods accept a javax.servlet.ServletRequest object and a javax.servlet.ServletResponse object as arguments.

As the name implies, the include method is used to include content from another resource, such as another servlet, a JSP page, or an HTML page. The method has the following signature:
public void include(javax.servlet.ServletRequest request,
  javax.servlet.ServletResponse response)
  throws javax.servlet.ServletException, java.io.IOException
The forward method is used to forward a request from one servlet to another. The original servlet can perform some initial tasks on the ServletRequest object before forwarding it. The signature of the forward method is as follows:
public void forward(javax.servlet.ServletRequest request,
  javax.servlet.ServletResponse response)
  throws javax.servlet.ServletException, java.io.IOException

 

The Difference Between sendRedirect and forward
Both the sendRedirect and forward methods bring the user to a new resource. There is a fundamental difference between the two, however, and understanding this can help you write a more efficient servlet.
The sendRedirect method works by sending a status code that tells the browser to request another URL. This means that there is always a round trip to the client side. Additionally, the previous HttpServletRequest object is lost. To pass information between the original servlet and the next request, you normally pass the information as a query string appended to the destination URL.
The forward method, on the other hand, redirects the request without the help from the client’s browser. Both the HttpServletRequest object and the HttpServletResponse object also are passed to the new resource.

To perform a servlet include or forward, you first need to obtain a RequestDispatcher object. You can obtain a RequestDispatcher object three different ways, as follows:
• Use the getRequestDispatcher method of the javax.servlet.ServletContext interface, passing a String containing the path to the other resource. The path is relative to the root of the ServletContext.
• Use the getRequestDispatcher method of the javax.servlet.ServletRequest interface, passing a String containing the path to the other resource. The path is relative to the current HTTP request.
• Use the getNamedDispatcher method of the javax.servlet.ServletContext interface, passing a String containing the name of the other resource.
The include method of the RequestDispatcher interface may be called at any time. The target servlet has access to all aspects of the request object, but can only write information to the ServletOutputStream or Writer object of the response object. The target servlet also can commit a response by either writing content past the end of the response buffer or explicitly calling the flush method of the ServletResponse interface. The included servlet cannot set headers or call any method that affects the header of the response.
When a servlet is being called from within an include method, it is sometimes necessary for that servlet to know the path by which it was invoked. The following request attributes are set and accessible from the included servlet via the getAttribute method on the request object:
• javax.servlet.include.request_uri
• javax.servlet.include.context_path
• javax.servlet.include.servlet_path
• javax.servlet.include.path_info
• javax.servlet.include.query_string
These attributes are not set if the included servlet was obtained by using the getNamedDispatcher method

Forwarding Processing Control
Unlike the include method, the forward method of the RequestDispatcher interface may be called only by the calling servlet if no output has been committed to the client. If output exists in the response buffer that has not been committed, the buffer must be cleared before the target servlet’s service method is called. If the response has been committed prior to calling the forward method, an IllegalStateException will be thrown.

 

Session Management
Once users have logged in, they do not have to login again. The application will remember them. This is called session management.Needed because of HTTP statelessness.

By principle, you manage a user’s session by performing the following to servlets/pages that need to remember a user’s state:
1. When the user requests a servlet, in addition to sending the response, the servlet also sends a token or an identifier.
2. If the user does not come back with the next request for the same or a different servlet, that is fine. If the user does come back, the token or identifier is sent back to the server. Upon encountering the token, the next servlet should recognize the identifier and can do a certain action based on the token. When the servlet responds to the request, it also sends the same or a different token. This goes on and on with all the servlets that need to remember a user’s session.
Methods
URL Rewriting
A name and a value is separated using an equal sign (=); a parameter name/value pair is separated from another parameter name/value pair using the ampersand (&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a servlet, you can use the HttpServletRequest interface’s getParameter method to obtain a parameter value.
url?name1=value1&name2=value2&…
The use of URL rewriting is easy. When using this technique, however, you need to consider several things:
• The number of characters that can be passed in a URL is limited. Typically, a browser can pass up to 2,000 characters.
• The value that you pass can be seen in the URL. Sometimes this is not desirable. For example, some people prefer their password not to appear on the URL.
• You need to encode certain characters—such as & and ? characters and white spaces—that you append to a URL.
Hidden Fields
Another technique for managing user sessions is by passing a token as the value for an HTML hidden field. Unlike the URL rewriting, the value does not show on the URL but can still be read by viewing the HTML source code.

Cookies
The third technique that you can use to manage user sessions is by using cookies. A cookie is a small piece of information that is passed back and forth in the HTTP request and response. Even though a cookie can be created on the client side using some scripting language such as JavaScript, it is usually created by a server resource, such as a servlet. The cookie sent by a servlet to the client will be passed back to the server when the client requests another page from the same application. You can choose to persist cookies so that they last longer. The javax.servlet.http.Cookie class has the setMaxAge method that sets the maximum age of the cookie in seconds.

Session Objects
the Session object, represented by the javax.servlet.http.HttpSession interface, is the easiest to use and the most powerful. For each user, the servlet can create an HttpSession object that is associated with that user only and can only be accessed by that particular user. The HttpSession object acts like a Hashtable into which you can store any number of key/object pairs. The HttpSession object is accessible from other servlets in the same application. To retrieve an object previously stored, you need only to pass the key. however, the server does not send any value. What it sends is simply a unique number called the session identifier. This session identifier is used to associate a user with a Session object in the server
1. An HttpSession object is created by a servlet called Servlet1. A session identifier is generated for this HttpSession object. In this example, the session identifier is 1234, but in reality, the servlet container will generate a longer random number that is guaranteed to be unique. The HttpSession object then is stored in the server and is associated with the generated session identifier. Also the programmer can store values immediately after creating an HttpSession.
2. In the response, the servlet sends the session identifier to the client browser.
3. When the client browser requests another resource in the same application, such as Servlet2, the session identifier is sent back to the server and passed to Servlet2 in the javax.servlet.http.HttpServletRequest object.
4. For Servlet2 to have access to the HttpSession object for this particular client, it uses the getSession method of the javax.servlet.http.HttpServletRequest interface. This method automatically retrieves the session identifier from the request and obtains the HttpSession object associated with the session identifier.

What if the user never comes back after an HttpSession object is created? Then the servlet container waits for a certain period of time and removes that HttpSession object.
The getSession method of the javax.servlet.http.HttpServletRequest interface has two overloads. They are as follows:
• HttpSession getSession()
• HttpSession getSession(boolean create)
The first overload returns the current session associated with this request, or if the request does not have a session identifier, it creates a new one.
The second overload returns the HttpSession object associated with this request if there is a valid session identifier in the request. If no valid session identifier is found in the request, whether a new HttpSession object is created depends on the create value. If the value is true, a new HttpSession object is created if no valid session identifier is found in the request. Otherwise, the getSession method will return null.

The javax.servlet.http.HttpSession Interface
This interface has the following methods:
• getAttribute
• getAttributeNames
• getCreationTime
• getId
• getLastAccessedTime
• getMaxInactiveInterval
• getServletContext
• getSessionContext
• getValue
• getValueNames
• invalidate
• isNew
• putValue
• removeAttribute
• removeValue
• setAttribute
• setMaxInactiveInterval

 

 

Posted in Miscellaneous Topics | Trackback | del.icio.us | Top Of Page

No comments yet

Leave a Reply


anti-spam developed by thruSITES; the UK web design company
Enter the following characters/numbers into the box below, please!
Sample verification