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
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.
Solution: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:
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?
Solution: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.
What is client-side vs. server-side validation ?
client-side validation (client-tier)
server-side validation (presentation-tier)
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:
Note: Prohibit caching of application pages by inserting the following lines in your pages:
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 patternWithout 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
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 ?
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:
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:
What are the main elements of JSP? What are scriptlets? What are expressions?There are two types of data in a JSP page.
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.
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:
Expression Element:It is the embedded Java expression, which gets evaluated by the service method.
Scriptlet Element:They are the embedded Java statements, which get executed as part of the service method.
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 ?
or you can alter the location HTTP header attribute as follows:
How do you prevent the HTML output of your JSP page being cached ?
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.
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:
How do you forward a request to another resource (e.g. another Servlet) from within your 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:
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" %>)
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:
You could retrieve the java.lang.Throwable object within your error.jsp page as follows:
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.
What are the different scope values or what are the different scope values for <jsp:usebean> ?
What are the differences between static and a dynamic include ?
Static include <%@ include %>
Dynamic include <jsp:include ...>
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:
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 java.io.IOException, 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.
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.
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.
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.
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:
JavaBeans declaration and usage example:
Tell me about JSP best practices ?
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.
JDBC Interview Questions >>>