How to improve Servlet performance

  • Use the servlet init() method to cache static data, and release them in the destroy() method.
  • Use StringBuffer rather than using + operator when you concatenate multiple strings.
  • Use the print() method rather than the println() method.
  • Use a ServletOutputStream rather than a PrintWriter to send binary data.
  • Initialize the PrintWriter with the optimal size for pages you write.
  • Flush the data in sections so that the user can see partial pages more quickly.
  • Minimize the synchronized block in the service method.
  • Implement the getLastModified() method to use the browser cache and the server cache.
  • Use the application server’s caching facility.
  • Session mechanisms from fastest to slowest are: HttpSession, Hidden fields, Cookies, URL rewriting, the persistency mechanism.
  • Remove HttpSession objects explicitly in your program whenever you finish the session.
  • Set the session time-out value as low as possible.
  • Use transient variables to reduce serialization overheads.
  • Disable the servlet auto reloading feature.
  • Tune the thread pool size.

Can servlet have a constructor ?

Servlet can have a constructor. But you never call the constructor for the servlet / instantiate them , because the container handles it.
So you are better of doing initialization / one-time setup code in the init method of the servlet. Also, the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.However, you might still need the init parameters, so initialization is done in init instead of a constructor.

39. What is the differences between Http Servlet and generic Servlet

HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

  • doGet, if the servlet supports HTTP GET requests
  • doPost, for HTTP POST requests
  • doPut, for HTTP PUT requests
  • doDelete, for HTTP DELETE requests
  • init and destroy, to manage resources that are held for the life of the servlet
  • getServletInfo, which the servlet uses to provide information about itself

There’s almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there’s almost no reason to override the doOptions and doTrace methods.

GenericServlet defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.

GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it’s more common to extend a protocol-specific subclass such as HttpServlet.

GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface.

To write a generic servlet, you need only override the abstract service method.

38. Servlets 20 mins drill and Quiz.

What is the servlet?

Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently

What’s the difference between servlets and applets?

Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.

What are the uses of Servlets?

A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

When doGET() method will going to execute?

When we specified method=’GET’ in HTML
Example : < form name=’SSS’ method=’GET’>

When doPOST() method will going to execute?

When we specified method=’POST’ in HTML
< form name=’SSS’ method=’POST’ >

Which code line must be set before any of the lines that use the PrintWriter?

setContentType() method must be set.

Which protocol will be used by browser and servlet to communicate ?

HTTP

How Can You invoke other web resources (or other servelt / jsp ) ?

Servelt can invoke other Web resources in two ways: indirect and direct.
Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)
Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.
You can get this object using getRequestDispatcher(“URL”) method. You can get this object from either a request or a Context.
Example :
RequestDispatcher dispatcher = request.getRequestDispatcher(“/jspsample.jsp”);
if (dispatcher != null)
dispatcher.forward(request, response);
}

How Can you include other Resources in the Response?

Using include method of a RequestDispatcher object.
Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.
Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(“/banner”);
            if (dispatcher != null)
            dispatcher.include(request, response);
}

Is there any way to generate PDF’S dynamically in servlets?

We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples.

What is the difference between using getSession(true) and getSession(false) methods?

getSession(true) – This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object.
getSession(false) – This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

Can I invoke a JSP error page from a servlet?

Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets.

If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:

java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained

The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:

protected void sendErrorRedirect(HttpServletRequest request,
HttpServletResponse response, String errorPageURL, Throwable e) throws
ServletException, IOException {
request.setAttribute (“javax.servlet.jsp.jspException”, e);
getServletConfig().getServletContext().
getRequestDispatcher(errorPageURL).forward(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,”/jsp/MyErrorPage.jsp”,ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}

What is 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.

If you want a servlet to take the same action for both GET and POST request, what should you do?

Simply have doGet call doPost, or vice versa.

When a servlet accepts a call from a client, it receives two objects. What are they?

ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

What information that the ServletResponse interface gives the servlet methods for replying to the client?

It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

What information that the ServletRequest interface allows the servlet 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. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

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.

What must be implemented by all Servlets?
The Servlet Interface must be implemented by all servlets.

What are the uses of Servlets?

  • Servlets are used to process the client request.
  • A Servlet can handle multiple request concurrently and be used to develop high performance system
  • A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

What is Session ID?
A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages. 

What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.

Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not. 
In url  rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.

What is session hijacking?
If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user’s Web application session while that session is still in progress.

What is Session Migration?
Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.

How to track a user session in Servlets?
The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet:

HttpSession session = req.getSession(true);

How you can destroy the session in Servlet?
You can call invalidate() method on the session object to destroy the session.

e.g. session.invalidate();

37. What is servlet lazy loading.

  • A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.
  • The servlet specification defines the <load-on-startup> 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.

32. What is the difference between ServletContext and ServletConfig

public interface 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.
  • There is one context per “web application” per Java Virtual Machine.
  • The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

public interface ServletConfig

  • A servlet configuration object used by a servlet container used to pass information to a servlet during initialization.
  • This object defines how a servlet is to be configured is passed to a servlet in its init method.
  • Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters.
  • The container, in turn, passes these parameters to the servlet via the ServetConfig.

31. Explain Servlet Life Cycle.

  1. Servlets are normal Java classes which are created when needed and destroyed when not needed. Since Servlets run within a Servlet Container, creation and destruction of Servlets is the duty of Servlet Container and not yours.
  2. Implementing the init() and destory() methods of Servlet interface allows you to be told by the Servlet Container that when it has created an instance of your Servlet and when it has destroyed that instance.
  3. An important point to remember is that your Servlet is not created and destroyed for every request it receives, rather it is created and kept in memory where requests are forwarded to it and your Servlet then generates response.

  

Servlet Initialization (init())
So you have created your Servlet class by extending the HttpServlet class and have placed it in /WEB-INF/classes/ directory of your application.

Now when will Servlet Container create an instance of your Servlet? there are two situations :

  • When you have specifically told the Servlet Container to preload your Servlet when the Servlet Container starts by setting the load-on-startup tag to a non-zero value e.g.
    <web-app>
    
      <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>com.wordpress.sharat.servlets.TestServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
    </web-app>

    So when the Servlet Container starts it will preload your Servlet in the memory.

  • If your Servlet is not already loaded, it’s instance will be created as soon as a request is received for it by the Servlet Container.
  • During the loading of the Servlet into the memory, Servlet Container will call your Servlet’s init() method.
  • Since init() is going to be called only once you can put Servlet initialization code in it like getting hold of a database connection or whatever.

Responding to Requests(service())

  1. Once your Servlet is initialized and it’s init() method called, any request that the Servlet Container receives will be forwarded to your Servlet’s service() method.
  2. HttpServlet class breakes this service() method into more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace() methods depending on the type of HTTP request it receives.
  3. So in order to generate respose you should override the doGet() or doPost() method as required.
  4. At this moment all the requests will be forwarded to the appropriate doGet() or doPost() or whatever method as required. No new instance will be created for your Servlet.

Servlet Destruction(destory())

When your application is stopped or Servlet Container shuts down, your Servlet’s destroy() method will be called. This allows you to free any resources you may have got hold of in your Servlet’s init() method.

Always Remember

  • init() and destroy() methods will be called only once during the life time of your Servlet
  •  while service() and it’s broken down methods ( doGet(), doPost() etc ) will be called as many times as requests are received for them by the Servlet Container.