J2EE Overview

J2EE Servlet 1

J2EE Servlet 2










J2EE Best Practices

J2EE Logging

J2EE Testing

J2EE Deployment

J2EE Development Process

JSP Interview Questions

Did JSPs make servlets obsolete ?

No. JSPs did not make Servlets obsolete. Both Servlets and JSPs are complementary technologies. You can look at the JSP technology from an HTML designerís perspective as an extension to HTML with embedded dynamic content and from a Java developerís as an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println("<html>.. </html>") statements, where "out" is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.

What is a model 0 pattern (i.e. model-less pattern) and why is it not recommended? What is a model-2 or MVC architecture?

Problem in Model 0:

The model 0 pattern is fine for a very basic JSP page as shown above. But real web applications would have business logic, data access logic etc, which would make the above code hard to read, difficult to maintain, difficult to refactor, and untestable. It is also not recommended to embed business logic and data access logic in a JSP page since it is protocol dependent (i.e. HTTP protocol) and makes it unable to be reused elsewhere like a wireless application using a WAP protocol, a standalone XML based messaging application etc.


You can refactor the processing code containing business logic and data access logic into Java classes, which adhered to certain standards. This approach provides better testability, reuse and reduced the size of the JSP pages. This is known as the "model 1" pattern where JSPs retain the responsibility of a controller, and view renderer with display logic but delegates the business processing to java classes known as Java Beans.
The Java Beans are Java classes, which adhere to following items:
  • Implement or interface.
  • Provide a no-arguments constructor.
  • Private properties must have corresponding getXXX/setXXX methods.
The Model 1 provides a great improvement from the Model 0 or model-less pattern, but there are still some problems and limitations.

Problem in Model 1:

In the model 1 architecture the JSP page is alone responsible for processing the incoming request and replying back to the user. This architecture may be suitable for simple applications, but complex applications will end up with significant amount of Java code embedded within your JSP page, especially when there is significant amount of data processing to be performed. This is a problem not only for java developers due to design ugliness but also a problem for web designers when you have large amount of Java code in your JSP pages. In many cases, the page receiving the request is not the page, which renders the response as an HTML output because decisions need to be made based on the submitted data to determine the most appropriate page to be displayed. This would require your pages to be redirected (i.e. sendRedirect ("")) or forwarded to each other resulting in a messy flow of control and design ugliness for the application. So, why should you use a JSP page as a controller, which is mainly designed to be used as a template?


You can use the Model 2 architecture (MVC : Model, View, Controller architecture), which is a hybrid approach for serving dynamic content, since it combines the use of both Servlets and JSPs. It takes advantage of the predominant strengths of both technologies where a Servlet is the target for submitting a request and performing flow-control tasks and using JSPs to generate the presentation layer. As shown in the diagram below, the servlet acts as the controller and is responsible for request processing and the creation of any beans or objects used by the JSP as well as deciding, which JSP page to forward or redirect the request to (i.e. flow control) depending on the data submitted by the user. The JSP page is responsible for retrieving any objects or beans that may have been previously created by the servlet, and as a template for rendering the view as a response to be sent to the user as an HTML.

If you set a request attribute in your JSP, would you be able to access it in your subsequent request within your servlet code?

The answer is no because your request goes out of scope, but if you set a request attribute in your servlet then you would be able to access it in your JSP.
Servlets and JSPs are server side technologies and it is essential to understand the HTTP request/response paradigm. A common misconception is that the Java code embedded in the HTML page is transmitted to the browser with the HTML and executed in the browser. As shown in the diagram above, this is not true. A JSP is a server side component where the page is translated into a Java servlet and executed on the server. The generated servlet (from the JSP) outputs only HTML code to the browser. if you set a request attribute in your servlet code, it can be retrieved in your JSP code, since it is still in scope. Once the response has been sent back to the user (i.e. the browser) the current request goes out of scope. When the user makes another request, a new request is created and the request attribute set by the JSP code in your previous request is not available to the new request object. If you set a session attribute in your JSP, then it will be available in your subsequent request because it is still in scope. You can access it by calling session.getAttribute("JSPText").

How to get a pop-up window when clicking on a button ?

By using Java Script in your HTML code. The following Java Script is executed in the client side within your web browser.

<SCRIPT type="text/javascript">
function displayWarningMessage() {
var answer = confirm("This process may take a while, please click 'OK' to continue.");
if (!answer){
    return false;
    return disableSendBtton();
// -->

What is client-side vs. server-side validation ?

client-side validation (client-tier)

  • Java Script is used for client-side validation. Validation takes place in client-side within your browser. Java Script can be used to submit your form data after successful validation.
  • No extra network trip is required when there are validation errors because form does not have to be submitted.

server-side validation (presentation-tier)

  • Form data is submitted to the server and validation is carried out in the server.
  • Extra network round trip is required when there are validation errors because validation errors need to be reported back to the client and the form data has to be resubmitted.

How do you prevent multiple submits due to repeated "refresh button" clicks ?

Problem: Very often a user is completely unaware that a browser resends information to the server when a "refresh button" in Microsoft Internet Explorer or a "reload button" in Netscape/Mozilla is clicked. Even if a browser warns user, a user cannot often understand the technical meaning of the warning. This action can cause form data to be resubmitted, possibly with unexpected results such as duplicate/multiple purchases of a same item, attempting to delete the previously deleted item from the database resulting in a SQLException being thrown. Non-idempotent methods are methods that cause the state to change. But some operations like reading a list of products or customer details etc are safe because they do not alter the state of the model and the database.
These methods are known as idempotent methods.
Solution 1: You can use a Post/Redirect/Get (aka PRG) pattern. This pattern involves the following steps:
  • Step-1: First a user filled form is submitted to the server (i.e. a Servlet) using a "POST" (also a "GET" method). Servlet performs a business operation by updating the state in the database and the business model.
  • Step-2: Servlet replies with redirect response (i.e. sendRedirect() operation as opposed to the forward() operation) for a view page.
  • Step-3: Browser loads a view using a "GET" where no user data is sent. This is usually a separate JSP page, which is safe from "multiple submits". For e.g. reading data from a database, a confirmation page etc.
  • Advantages: Separates the view from model updates and URLs can be bookmarked.
  • Disadvantage: Extra network round trip.
Solution-2: The solution-1 has to make an extra network round trip. The synchronizer token pattern can be applied in conjunction with request forward (i.e. instead of redirect) to prevent multiple form submits with unexpected side effects without the extra round trip. The basic idea of this pattern is to set a use once only token in a "session", when a form is requested and the token is stored in the form as a hidden field. When you submit the form the token in the request (i.e. due to hidden field) is compared with the token in the session. If tokens match, then reset the token in the session to null or increment it to a different value and proceed with the model & database update. If you inadvertently resubmit the form by clicking the refresh button, the request processing servlet (i.e. PurchaseServlet) first tests for the presence of a valid token in the request parameter by comparing it with the one stored in the session. Since the token was reset in the first submit, the token in the request (i.e 123) would not match with the token in the session (i.e. null or 124). Since the tokens do not match, an alternate course of action is taken like forwarding to an error.jsp page.
Note: Prohibit caching of application pages by inserting the following lines in your pages:

<meta HTTP-EQUIV="pragma" content="no-cache" />
<meta HTTP-EQUIV="Expires" content="-1" />

What is a Front Controller pattern with command objects uses the command design pattern ?

The model-2 MVC pattern can be further improved and simplified by using the Front Controller pattern with command objects. In a complex Web site there are many similar input control operations like security, internationalization, controlling and logging userís progress through the site etc you need to perform while handling a request. If these input control operations are scattered across multiple objects, much of these behaviors can end up duplicated resulting in maintenance issues. The Front Controller pattern uses a single servlet, which acts as initial point of contact for handling all the requests, including invoking services such as security (authentication and authorization), logging, gathering user input data from the request, gathering data required by the view etc by delegating to the helper classes, and managing the choice of an appropriate view with the dispatcher classes. These helper and dispatcher classes are generally instances of a command design pattern and therefore usually termed as command objects. The Front Controller pattern centralizes services like security, internationalization, auditing, logging etc to improve manageability, and improves reusability by moving common behavior among command objects into the centralized controller or controller managed helper classes. Front Controller uses a single servlet to process all requests, which means only one servlet controller will be declared (i.e. servlet declaration and servlet mapping) in the web.xml and hence eliminates the need to have more than one servlet and consequently the need to have to declare more than one servlet in the web.xml deployment descriptor.

Without the Front Controller pattern

Without the "Front Controller" pattern, the web.xml would have the following set of entries for each servlet in your application.


So, if you say you have 50 servlets in your web application, then you would have the above declarations 50 times in your web.xml file. This would make your web.xml file to be large and hard to maintain.

With the Front Controller pattern

    <servlet-class>com. MyControllerServlet </servlet-class>
    <servlet-name> MyControllerServlet </servlet-name>

There will be only one central controller servlet configured in the web.xml file.
The popular request based web framework Struts uses the Front Controller pattern, where a centralized single servlet is used for channeling all requests and creating instances of "Action" classes for processing user requests. The Struts "Action" classes are command objects.

What do you understand by the term JSP translation phase or compilation phase ?

As shown below in the figure the JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution phase (run time) where they can handle requests and send responses. Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On large production sites, or in situations involving complicated JSP files, compilation may cause unacceptable delays to users first accessing the JSP page. The JSPs can be compiled ahead of time (i.e. precompiled) using application server tools/settings or by writing your own script.

Explain the life cycle methods of a JSP ?

  • Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
  • Translated: The JSP file has been translated and compiled as a Servlet.
  • Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
  • Servicing: Services the client requests. Container calls the _jspService() method for each request.
  • Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.

Can you have your JSP-generated servlet subclass your own servlet instead of the default HttpServlet ?

Your JSP generated servlet can extend your own servlet with the directive:

<%@ page extends="com.CRMServlet"%>

But, you should be very careful when having your JSP pages extend your own servlet class. By doing so you may lose any advanced optimization that may be provided by your JSP engine. If you do have a compelling reason to do so then your own superclass servlet has to fulfill the contract with the JSP engine by:
  • Implementing the HttpJspPage interface for HTTP protocol or JspPage interface. If you do not then you will have to make sure that all your super-class servlet methods are declared as final.
  • Implementing your super-class servlet methods as follows:
    • The service() method has to invoke the _jspService() method.
    • The init() method has to invoke the jspInit() method.
    • The destroy() method has invoke jspDestroy() method.
If the above conditions are not met, then a translation error may be thrown by your JSP engine.

What are the main elements of JSP? What are scriptlets? What are expressions?

There are two types of data in a JSP page.
  • Static part (i.e. HTML, CSS etc), which gets copied directly to the response by the JSP Engine.
  • Dynamic part, which contains anything that can be translated and compiled by the JSP Engine.
There are three types of dynamic elements. (TIP: remember SAD as an abbreviation for Scripting, Action and Directive elements). Scripting Elements: A JSP element that provides embedded Java statements. There are three types of scripting elements. They are Declaration, Expression and Scriplet elements.

Declaration Element:

It is the embedded Java declaration statement, which gets inserted at the Servlet class level.
<%! Calendar c = Calendar.getInstance(); %>
Important: declaring variables via this element is not thread-safe, because this variable ends up in the generated Servlet as an instance variable, not within the body of the _jspService() method. Ensure their access is either read-only or synchronized. You can make your JSP generated servlets implement the SingleThreadModel with the directive
<%@ page isThreadSafe="false" %> but not recommended
Can you declare a method within your JSP page ?
You can declare methods within your JSP pages as declarations, and your methods can be invoked from within your other methods you declare, expression elements or scriptlets. These declared methods do not have direct access to the JSP implicit objects (Refer Q32 in Enterprise section) like session, request, response etc but you can pass them to your methods you declare as parameters.

    //JSP method where implicit session object as method argument
    public String myJspMethod(HttpSession session) {
      String str = (String)session.getAttribute("someAttrName");
      return str.substring(0,3);

Note: Declaring methods within a JSP page is a bad practice because it will make your JSP page hard to read, reuse and maintain.
If it is not a good practice to implement methods within your JSPs then can a JSP page process HTML form data ?
Yes. Unlike servlets you do not have to implement HTTP specific methods like doGet(), doPost() etc in your JSPs. In JSPs you can obtain the form data via the "request" implicit object within a scriptlet or expression as follows:

    String firstName = request.getParameter("param1");
    int units = new Integer(request.getParameter("param2")).intValue();

Expression Element:

It is the embedded Java expression, which gets evaluated by the service method.

<%= new Date() %>

Scriptlet Element:

They are the embedded Java statements, which get executed as part of the service method.

    String username = null;
    username = request.getParameter("userName"); //"request" is a JSP implicit object

Important: Not recommended to use Scriptlet elements because they donít provide reusability and maintainability. Use custom tags like JSTL, JSF tags, etc or beans instead.

How will you perform a browser redirection from a JSP page ?

<% response.sendRedirect(""); %>

or you can alter the location HTTP header attribute as follows:
<% response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", "/someNewPath/index.html"); %>

How do you prevent the HTML output of your JSP page being cached ?

    response.setHeader("Cache-Control", "no=store"); //HTTP 1.1
    response.setDateHeader("Expires", 0);

How would you invoke a Servlet from a JSP? Or invoke a JSP form another JSP ?

You can invoke a Servlet from a JSP through the jsp:include and jsp:forward action tags.
<jsp:include page="/servlet/MyServlet" flush="true" />

Generally you would be invoking a JSP page from a Servlet. Why would you want to invoke a Servlet from a JSP ?

JSP technology is intended to simplify the programming of dynamic textual content. If you want to output any binary data (e.g. pdfs, gifs etc) then JSP pages are poor choice for the following reasons and should use Servlets instead:
  • There are no methods for writing raw bytes in the JspWriter object.
  • During execution, the JSP engine preserves whitespace. Whitespace is sometimes unwanted (a .gif file, for example), making JSP pages a poor choice for generating binary data. In the following example, the browser receives unnecessary newline characters in the middle or at the end of the binary data depending on the buffering of your output. "out" is a JspWriter implicit object.
    <% out.getOutputStream().write(...some binary data...) %>
    <% out.getOutputStream().write(...some more binary data...) %>

    How do you forward a request to another resource (e.g. another Servlet) from within your JSP ?

    //Without passing any parameters
    <jsp:forward page="/anotherPage.jsp" />

    How does JSP handle run-time exceptions ?

    You can use the attribute "errorPage" of the "page" directive to have your uncaught RuntimeExceptions automatically forwarded to an error processing page. Example: <%@ page errorPage="error.jsp" %>
    Note: You must always use a relative URL as the "errorPage" attribute value. The above code redirects the browser client to the error.jsp page. Within your error.jsp page, you need to indicate that it is an error processing page with the "isErrorPage" attribute of the "page" directive as shown below.
    "exception" is an implicit object accessible only within error pages (i.e. pages with directive <%@ page isErrorPage="true" %>)

    <%@ page isErrorPage="true" %>
    <%= exception.gerMessage() %>

    How will you specify a global error page as opposed to using "errorPage" and "isErrorPage" attributes ?

    You could specify your error page in the web.xml deployment descriptor as shown below:

    // by exception type
    //or by HTTP error codes

    You could retrieve the java.lang.Throwable object within your error.jsp page as follows:
    <%= request.getAttribute("javax.servlet.error.exception") %>
    Note: You cannot use the "exception" implicit object for the global error pages. This is because of mismatch in the way servlet (uses javax.servlet.error.exception) and JSP (uses javax.servlet.jsp.jspException) let you get the java.lang.Throwable.

    How can you prevent the automatic creation of a session in a JSP page ?

    Sessions consume resources and if it is not necessary, it should not be created. By default, a JSP page will automatically create a session for the request if one does not exist. You can prevent the creation of useless sessions with the attribute "session" of the page directive.
    <%@ page session="false" %>

    What are the different scope values or what are the different scope values for <jsp:usebean> ?

    Page PageContext Available to the handling JSP page only.
    Request Request Available to the handling JSP page or Servlet and forwarded JSP page or Servlet.
    Session Session Available to any JSP Page or Servlet within the same session.
    Application Application Available to all the JSP pages and Servlets within the same Web Application.

    What are the differences between static and a dynamic include ?

    Static include <%@ include %>

    • During the translation or compilation phase all the included JSP pages are compiled into a single Servlet.
    • No run time performance overhead.

    Dynamic include <jsp:include ...>

    • The dynamically included JSP is compiled into a separate Servlet.It is a separate resource, which gets to process the request, and the content generated by this resource is included in the JSP response.
    • Has run time performance overhead.

    Which one to use:

    Use "static includes" when a JSP page does not change very often. For the pages, which change frequently, use dynamic includes. JVM has a 64kb limit on the size of the method and the entire JSP page is rendered as a single method (i.e. _jspService (..)). If a JSP page is greater than 64kb, this probably indicates poor implementation. When this method reaches its JVM limit of 64kb, the JVM throws an error. This error can be overcome by splitting the JSP files and including them dynamically (i.e. using <jsp:include...>) because the dynamic includes generate a separate JSP Servlet for each included file.
    Note: The "dynamic include" <jsp:include> has a flush attribute. This attribute indicates whether the buffer should be flushed before including the new content. In JSP 1.1 you will get an error if you omit this attribute. In JSP 1.2 you can omit this attribute because the flush attribute defaults to false.

    What are implicit objects and list them ?

    Implicit objects are the objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated Servlet. The implicit objects are:
    • request: Refers to the current request from the client.
    • response: Refers to the current response to the client.
    • pageContext: Refers to the pageís environment.
    • session: Refers to the userís session.
    • application: Same as ServletContext. Refers to the web applicationís environment.
    • out: Refers to the outputstream.
    • config: same as ServletConfig. Refers to the servletís configuration.
    • page: Refers to the pageís Servlet instance.
    • exception: exception created on this page. Used for error handling. Only available if it is an errorPage with the following directive: <%@ page isErrorPage="true" %> The "exception" implicit object is not available for global error pages declared through web.xml.
    You can retrieve the java.lang.Throwable object as follows: <%= request.getAttribute("javax.servlet.error.exception") %>
      String username = null;
      username = request.getParameter("userName"); //"request" is an implicit object
      out.print(username); //"out" is an implicit object

    What is the difference between a JspWriter denoted by the "out" implicit object and the PrintWriter object obtained from response.getWriter() method ?

    JSPs should use the JspWriter denoted by the "out" implicit object for sending output back to the client. A JspWriter is a buffered version of the PrintWriter. Refer JspWriter API for details. JspWriter also differs from a PrintWriter by throwing, which a PrintWriter does not. The advantage of throwing an exception is that if your HTTP connection is broken for some reason, your JSP won't sit there trying to send characters to a broken connection.

    Explain hidden and output comments ?

    An output comment is a comment that is sent to the client where it is viewable in the browserís source.

    <!-- This is a comment which is sent to the client -->

    A hidden comment documents a JSP page but does not get sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags.

    <%-- This comment will not be visible to the client --%>

    Is JSP variable declaration thread safe ?

    No. The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated Servlet as an instance variable, not within the body of the _jspService() method. The following declaration is not thread safe: because these declarations end up in the generated servlet as instance variables.

    <%! int a = 5 %>

    The following declaration is thread safe: because the variables declared inside the scriplets end up in the generated servlet within the body of the _jspService() method as local variables.

    <% int a = 5 %>

    What is URL hiding or protecting the JSP page ?

    As shown in the figure, the JSP resources usually reside directly or under subdirectories (e.g. myPath) of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files, css (cascading style sheets) files, Java Script files, pdf files, image files, html files etc from direct access. The request should be made to a servlet who is responsible for authenticating and authorizing the user before returning the protected JSP page or its resources.

    What are JSP custom tags ?

    Custom JSP tag is a tag you define. 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. So basically it is a reusable and extensible JSP only solution. The pre-built tags also can speed up Web development.

    What is the difference between custom JSP tags and JavaBeans ?

    In the context of a JSP page, both accomplish similar goals but the differences are:

    Custom Tags

    • Can manipulate JSP content.
    • Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up.
    • Used only in JSPs in a relatively self-contained manner.


    • Can't manipulate JSP content.
    • Easier to set up.
    • Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page.

    JavaBeans declaration and usage example:

    <jsp:useBean id="identifier" class="packageName.className"/>
    <jsp:setProperty name="identifier" property="classField" value="someValue" />
    <jsp:getProperty name="identifier" property="classField" /> <%=identifier.getclassField() %>

    Tell me about JSP best practices ?

    • Separate HTML code from the Java code: Combining HTML and Java code in the same source code can make the code less readable. Mixing HTML and scriptlet will make the code extremely difficult to read and maintain. The display or behavior logic can be implemented as a custom tags by the Java developers and Web designers can use these tags as the ordinary XHTML tags.
    • Place data access logic in JavaBeans: The code within the JavaBean is readily accessible to other JSPs and Servlets.
    • Factor shared behavior out of Custom Tags into common JavaBeans classes: The custom tags are not used outside JSPs. To avoid duplication of behavior or business logic, move the logic into JavaBeans and get the custom tags to utilize the beans.
    • Choose the right "include" mechanism.
    • Use style sheets (e.g. css), template mechanism (e.g. struts tiles etc) and appropriate comments (both hidden and output comments). The traditional HTML approach was to "hardcode" all of the appearance information about a page. Say you want all your headings in Arial, and you have hard coded that in more than 50 pages ? That is a lot of editing, and a lot of re-editing if you decide to modify the headings to courier. With all of that editing there are plenty of possibility for introducing errors. With CSS, you can decide how headings should appear, and enter that information once. Every heading in every page that is linked to this style sheet now has that appearance.
    • Use pagination for large resultsets: If you display long lists (i.e. resultsets) in the browser, it is difficult for the user to find what he or she wants and also can prove impractical due to memory limitation, response-time limitation, page design limitation (i.e long scrollable pages are not desirable) etc. Pagination is the most common way to break up large amount of data into manageable chunks.

    How will you avoid scriptlet code in JSP ?

    Use JavaBeans or custom tags instead.

    How do you connect to the database from JSP/Servlet ?

    A connection can be established to a database as shown below via scriptlet. It is not the best practice to embed data access logic in your JSP/Servlet. The best practice should make use of a separate "Data Access Object (using DAO pattern)" , which gets invoked by JSP, Servlet, plain Java class, EJBs etc. The next section discusses basics and best practices relating to data access. <%@ page language="java" contentTpe="text/html" import="java.sql.*"%>
    <title>Simple JSP Page</title>
    <h1>Output to Browser</h1>
      //1. load the driver from specific vendor
      //2. open connection to the databse by passing the URL to the database
      Connection con = DriverManager.getConnection("jdbc:oracle:thin:@hostname:1526:myDB");
      //3. create a statement object
      Statement stmt = con.createStatement();
      //4. Create a ResultSet
      ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
      //5. you can use the ResultSet Object to read data

    JDBC Interview Questions >>>

    Home Clouds