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 ?


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);
getRequestDispatcher(errorPageURL).forward(request, response);

public void doPost(HttpServletRequest request, HttpServletResponse response)
try {
// do something
} catch (Exception ex) {
try {
} catch (Exception e) {

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();


10 Responses

  1. very nice

  2. The questions & answers, you have provied is very good medium of clearing doubts and confusions spececial for those who already studied. This also helps to renew your previous study and give new dimension to think on which you already know.The thing I appreaciate is that you have used simple language but not become bit technical. Some experts hide their lack of presentation in the curtain of technical jargons. One should use coomon language and examples for his/her presentaion so that everyone understand.
    If you have some other such type of questions & answers on following topics than please inform.
    1) Servlet & JSP
    3) secuirty
    4) redirecting
    5) jsp standard bean action
    6) Lesiteners for (ServletContext, ServletRequest, HttpSession and Listeners for attributes of different scopes etc.)
    7) directives, scripting elements and their XML alternatives)
    8) some question about web.xml and tld files
    9) Tag File, Simple Tags, Classic Tags, and JSTL standard tags
    10) beans
    11) and many more that I have forget to mession

  3. good

  4. why we can create object for servlet interface?

  5. As servelet is an interface how can we create object of it?

  6. how can we create object on servlet interface?

  7. nice explaination

  8. I doubt this is completely true “Servlets can forward requests to other servers and servlets”. Although they can call servlets on other servers via HttpUrlConnection and include the generated response in their own response, I think it’s not possible to forward the whole request to a different server at all. An instance of RequestDispatcher can only forward requests to servlets in the same servlet container where you have access to the other context.

  9. javapapers.com has similar quality interview questions.

  10. Good One..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: