JSP Interview Questions

JSP Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of JSP. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:

Q: What is JSP?
A: JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.

Q: What are advantages of using JSP?
A: JSP offer several advantages as listed below:
·         Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself.
·         JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
·         JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
·         JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
Q: What are the advantages of JSP over Active Server Pages (ASP)?
A: The advantages of JSP are twofold.
First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.
Q: What are the advantages of JSP over Pure Servlets?
A: It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. Other advantages are:
·         Embedding of Java code in HTML pages.
·         Platform independence.
·         Creation of database-driven Web applications.
·         Server-side programming capabilities.
Q: What are the advantages of JSP over Server-Side Includes (SSI)?
A: SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.

Q: What are the advantages of JSP over JavaScript?
A: JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.

Q: What are the advantages of JSP over Static HTML?
A: Regular HTML, of course, cannot contain dynamic information.

Q: Explain lifecycle of a JSP.
A:A JSP Lifecycle consists of following steps:
·         Compilation: When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
o    Parsing the JSP.
o    Turning the JSP into a servlet.
o    Compiling the servlet.
·         Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests
·         Execution: Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
·         Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets.

Q: What is a sciptlet in JSP and what is its syntax?
A: A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet:
<% code fragment %>

Q: What are JSP declarations?
A: A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file.
<%! declaration; [ declaration; ]+ ... %>

Q: What are JSP expressions?
A: A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
Its syntax is:
<%= expression %>

Q: What are JSP comments?
A:JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments:
<%-- This is JSP comment --%>

Q: What are JSP Directives?
A: A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value"%>

Q: What are the types of directive tags?
A: The types directive tags are as follows:
·         <%@ page ... %> : Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
·         <%@ include ... %> : Includes a file during the translation phase.
·         <%@ taglib ... %> : Declares a tag library, containing custom actions, used in the page.

Q: What are JSP actions?
A: JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
Its syntax is as follows:
<jsp:action_name attribute="value"/>

Q: Name some JSP actions.
A: jsp:include, jsp:useBean,jsp:setProperty,jsp:getProperty, jsp:forward,jsp:plugin,jsp:element, jsp:attribute, jsp:body, jsp:text

Q: What are JSP literals?
A:Literals are the values, such as a number or a text string, that are written literally as part of a program code. The JSP expression language defines the following literals:
·         Boolean: true and false
·         Integer: as in Java
·         Floating point: as in Java
·         String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
·         Null: null

Q: What is a page directive?
A: The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page.

Q: What are various attributes Of page directive?
A:Page directive contains the following 13 attributes.
language
extends
import
session
isThreadSafe
info
errorPage
isErrorpage
contentType
isELIgnored
buffer
autoFlush
isScriptingEnabled
Q: What is a buffer attribute?
A: The buffer attribute specifies buffering characteristics for the server output response object.

Q: What happens when buffer is set to a value “none”?
A: When buffer is set to “none”, servlet output is immediately directed to the response output object.

Q: What is autoFlush attribute?
A: The autoFlush attribute specifies whether buffered output should be flushed automatically when the buffer is filled, or whether an exception should be raised to indicate buffer overflow.
A value of true (default) indicates automatic buffer flushing and a value of false throws an exception.

Q: What is contentType attribute?
A: The contentType attribute sets the character encoding for the JSP page and for the generated response page. The default content type is text/html, which is the standard content type for HTML pages.

Q: What is errorPage attribute?
A: The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL.

Q: What is isErrorPage attribute?
A:The isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP.
The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false.

Q: What is extends attribute?
A: The extends attribute specifies a superclass that the generated servlet must extend.

Q: What is import attribute?
A: The import attribute serves the same function as, and behaves like, the Java import statement. The value for the import option is the name of the package you want to import.

Q: What is info attribute?
A: The info attribute lets you provide a description of the JSP.

Q: What is isThreadSafe attribute?
A: The isThreadSafe option marks a page as being thread-safe. By default, all JSPs are considered thread-safe. If you set the isThreadSafe option to false, the JSP engine makes sure that only one thread at a time is executing your JSP.

Q: What is language attribute?
A: The language attribute indicates the programming language used in scripting the JSP page.

Q: What is session attribute?
A: The session attribute indicates whether or not the JSP page uses HTTP sessions. A value of true means that the JSP page has access to a builtin session object and a value of false means that the JSP page cannot access the builtin session object.

Q: What is isELIgnored Attribute?
A: The isELIgnored option gives you the ability to disable the evaluation of Expression Language (EL) expressions. The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.

Q: What is isScriptingEnabled Attribute?
A: The isScriptingEnabled attribute determines if scripting elements are allowed for use.
The default value (true) enables scriptlets, expressions, and declarations. If the attribute's value is set to false, a translation-time error will be raised if the JSP uses any scriptlets, expressions (non-EL), or declarations.
Q: What is a include directive?
A:The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >

Q: What is a taglib directive?
A:The taglib directive follows the following syntax:
<%@ taglib uri="uri"prefix="prefixOfTag">
uri attribute value resolves to a location the container understands
prefix attribute informs a container what bits of markup are custom actions.
The taglib directive follows the following syntax:
<%@ taglib uri="uri"prefix="prefixOfTag" >

Q: What do the id and scope attribute mean in the action elements?
A:
·         Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext
·         Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.

Q: what is the function of <jsp:include> action?
A:This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:includepage="relative URL" flush="true"/>
Where page is the the relative URL of the page to be included.
Flush is the boolean attribute the determines whether the included resource has its buffer flushed before it is included.

Q: What is the difference between include action and include directive?
A: Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, include action inserts the file at the time the page is requested.

Q: What is <jsp:useBean> action?
A: The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows:
<jsp:useBeanid="name"class="package.class" />

Q: What is <jsp:setProperty> action?
A: The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action.

Q: What is <jsp:getProperty> action?
A: The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.

Q: What is <jsp:forward> Action?
A:The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet.
The simple syntax of this action is as follows:
<jsp:forwardpage="Relative URL" />

Q: What is <jsp:plugin> Action?
A: The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean.
Q: What are the different scope values for the JSP action?
A: The scope attribute identifies the lifecycle of the Action element. It has four possible values: (a) page, (b)request, (c)session, and (d) application.

Q: What are JSP implicit objects?
A: JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.

Q: What implicit objects are supported by JSP?
A: request,response,out,session,application,config,pageContext,page, Exception

Q: What is a request object?
A: The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.
Q: How can you read a request header information?
A: Using getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request.

Q: What is a response object?
A: The response object is an instance of a javax.servlet.http.HttpServletRequest object. Just as the server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
Q: What is the out implicit object?
A:The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.

Q: What is the difference between JspWriter and PrintWriter?
A: The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.

Q: What is the session Object?
A: The session object is an instance of javax.servlet.http.HttpSession and is used to track client session between client requests

Q: What is an application Object?
A: The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
Q: What is a config Object?
A: The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.
Q: What is a pageContext Object?
A:The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.
This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
Q: What is a page object?
A: This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.
The page object is really a direct synonym for the this object.
Q: What is an exception Object?
A: The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.

Q: What is difference between GET and POST method in HTTP protocol?
A: The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? Character.
The POST method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing.
Q: How to read form data using JSP?
A:JSP handles form data parsing automatically using the following methods depending on the situation:
·         getParameter(): You call request.getParameter() method to get the value of a form parameter.
·         getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
·         getParameterNames(): Call this method if you want a complete list of all parameters in the current request.
·         getInputStream(): Call this method to read binary data stream coming from the client.

Q: What are filters?
A:JSP Filters are Java classes that can be used in JSP Programming for the following purposes:
·         To intercept requests from a client before they access a resource at back end.
·         To manipulate responses from server before they are sent back to the client.
Q: How do you define filters?
A: Filters are defined in the deployment descriptor file web.xml and then mapped to either servlet or JSP names or URL patterns in your application's deployment descriptor.
When the JSP container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
Q: What are cookies?
A: Cookies are text files stored on the client computer and they are kept for various information tracking purpose.

Q: How cookies work?
A: Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser).If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.

Q: How do you set cookies in the JSP?
A:Setting cookies with JSP involves three steps:
·         Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
·         Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid.
·         Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header

Q: How to read cookies with JSP?
A: To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

Q: How to delete cookies with JSP?
A:To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:
·         Read an already existing cookie and store it in Cookie object.
·         Set cookie age as zero using setMaxAge() method to delete an existing cookie.
·         Add this cookie back into response header.
Q: How is Session Management done in JSP?
A:Session management can be achieved by the use of:
·         Cookies: A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
·         Hidden Form Fields: A web server can send a hidden HTML form field along with a unique session ID as follows:
<input type="hidden" name="sessionid" value="12345">
This implies that when the form is submitted, the specified name and value will be getting included in GET or POST method.
·         URL Rewriting: In URL rewriting some extra information is added on the end of each URL that identifies the session. This URL rewriting can be useful where a cookie is disabled.
·         The session Object: JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

Q: How can you delete a session data?
A:When you are done with a user's session data, you have several options:
·         Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key.
·         Delete the whole session: You can call public void invalidate() method to discard an entire session.
·         Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
·         Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
·         web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.

Q: How can you upload a file using JSP?
A: To upload a single file you should use a single <input .../> tag with attribute type="file".To allow multiple files uploading, include more than one input tags with different values for the name attribute.

Q: Where will be the uploaded files stored?
A: You can hard code this in your program or this directory name could also be added using an external configuration such as a context-param element in web.xml.

Q: What is JSP page redirection?
A: Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization.

Q: What is the difference between <jsp:forward page = ... > and response.sendRedirect(url)?
A: The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page.
Q: What is a hit count for a web page?
A: A hit counter tells you about the number of visits on a particular page of your web site.

Q: How do you impement hit counter in JSP?
A: To implement a hit counter you can make use of Application Implicit object and associated methods getAttribute() and setAttribute().
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
Q: How can you implement hit counter to avoid loss of count data with each restart of thh application?
A: You can follow the below steps:
·         Define a database table with a single count, let us say hitcount. Assign a zero value to it.
·         With every hit, read the table to get the value of hitcount.
·         Increase the value of hitcount by one and update the table with new value.
·         Display new value of hitcount as total page hit counts.
·         If you want to count hits for all the pages, implement above logic for all the pages.
Q: What is auto refresh feature?
A:Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your web page regularly using refresh or reload button with your browser.
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.
Q: How do you implement the auto refresh in JSP?
A: The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method:
public void setIntHeader(String header, int headerValue)
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.
Q: What is JSTL?
A: The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags.
Q: What the different types of JSTL tags are ?
A: Types of JSTL tags are:
·         Core Tags
·         Formatting tags
·         SQL tags
·         XML tags
·         JSTL Functions

Q: What is the use of <c:set > tag?
A: The <c:set > tag is JSTL-friendly version of the setProperty action. The tag is helpful because it evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map object.

Q: What is the use of <c:remove > tag?
A: The <c:remove > tag removes a variable from either a specified scope or the first scope where the variable is found (if no scope is specified).

Q: What is the use of <c:catch> tag?
A: The <c:catch> tag catches any Throwable that occurs in its body and optionally exposes it. Simply it is used for error handling and to deal more gracefully with the problem.

Q: What is the use of <c:if> tag?
A: The <c:if> tag evaluates an expression and displays its body content only if the expression evaluates to true.

Q: What is the use of <c:choose> tag?
A: The <c:choose> works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <c:choose> tag has <c:when> tags. A a switch statement has default clause to specify a default action and similar way <c:choose> has <otherwise> as default clause.

Q: What is the use of <c:forEach >, <c:forTokens> tag?
A: The <c:forEach >, <c:forTokens> tags exist as a good alternative to embedding a Java for, while, or do-while loop via a scriptlet.

Q: What is the use of <c:param> tag?
A: The <c:param> tag allows proper URL request parameter to be specified with URL and it does any necessary URL encoding required.

Q: What is the use of <c:redirect > tag?
A: The <c:redirect > tag redirects the browser to an alternate URL by providing automatically URL rewriting, it supports context-relative URLs, and it supports the <c:param> tag.

Q: What is the use of <c:url> tag?
A: The <c:url> tag formats a URL into a string and stores it into a variable. This tag automatically performs URL rewriting when necessary.

Q: What are JSTL formatting tags ?
A:The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites. Following is the syntax to include Formatting library in your JSP:
<%@ taglib prefix="fmt"
           uri="http://java.sun.com/jsp/jstl/fmt" %>

Q: What are JSTL SQL tags?
A: The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql"
           uri="http://java.sun.com/jsp/jstl/sql" %>

Q: What are JSTL XML tags?
A: The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. Following is the syntax to include JSTL XML library in your JSP.
<%@ taglib prefix="x"
           uri="http://java.sun.com/jsp/jstl/xml" %>

Q: What is a JSP custom tag?
A: A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.

Q: What is JSP Expression Language?
A: JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. A simple syntax for JSP EL is :

${expr}
Here expr specifies the expression itself.
Q: What are the implicit EL objects in JSP ?
A: The JSP expression language supports the following implicit objects:
·         pageScope: Scoped variables from page scope
·         requestScope: Scoped variables from request scope
·         sessionScope: Scoped variables from session scope
·         applicationScope: Scoped variables from application scope
·         param: Request parameters as strings
·         paramValues: Request parameters as collections of strings
·         headerHTTP: request headers as strings
·         headerValues: HTTP request headers as collections of strings
·         initParam: Context-initialization parameters
·         cookie: Cookie values
·         pageContext: The JSP PageContext object for the current page

Q: How can we disable EL ?
A: We can disable using isELIgnored attribute of the page directive:

<%@ page isELIgnored ="true|false" %>
If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.

Q: What type of errors you might encounter in a JSP code?
A:
·         Checked exceptions: Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
·         Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
·         Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Q: In JSP page how can we handle runtime exception?
A: We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
Example: <%@ page errorPage="error.jsp" %>
It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage="true" %>
Q: What is Internationalization?
A: Internationalization means enabling a web site to provide different versions of content translated into the visitor's language or nationality.

Q: What is Localization?
A: Localiztion means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site.

Q: What is locale?
A: This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example "en_US" represents english locale for US.

Q: What is difference between <%-- comment --%> and <!-- comment -->?
A: <%-- comment --%> is JSP comment and is ignored by the JSP engine.
<!-- comment --> is an HTML comment and is ignored by the browser.
Q: Is JSP technology extensible?
A: YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Q: How do I include static files within a JSP page?
A: Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

Q: Can a JSP page process HTML FORM data?
A: Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression.

Q: How do you pass control from one JSP page to another?
A: Use the following ways to pass control of a request from one servlet to another or one jsp to another:
·         The RequestDispatcher object ‘s forward method to pass the control.
·         Using the response.sendRedirect method.
Q: Can you make use of a ServletOutputStream object from within a JSP page?
A: No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.
A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not.
Q: What is the page directive is used to prevent a JSP page from automatically creating a session?
A: <%@ page session="false">

Q: How to pass information from JSP to included JSP?
A: Using <%jsp:param> tag.

Q: Can we override the jspInit(), _jspService() and jspDestroy() methods?
A: We can override jspinit() and jspDestroy() methods but not _jspService().

Q: Why is _jspService() method starting with an '_' while other life cycle methods do not?
A: _jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.

Q: A JSP page, include.jsp, has a instance variable "int a", now this page is statically included in another JSP page, home.jsp, which also has an instance variable "int a" declared. What happens when the home.jsp page is requested by the client?
A: It causes compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error.

Q: How is scripting disabled?
A: Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:

<jsp-property-group>
   <url-pattern>*.jsp</url-pattern>
   <scripting-invalid>true</scripting-invalid>
</jsp-property-group>

Q: When do use application scope?
A: If we want to make our data available to the entire application then we have to use application scope.

Q: What are the options in JSP to include files?
A: In JSP, we can perform inclusion in the following ways:
·         By include directive: For example:
·          
<%@ include file=”header.jsp %>
·         By include action: For example:
·          
<%@ include file=”header.jsp %>
·         By using pageContext implicit object For example:
·          
·         <%
·              pageContext.include(“/header.jsp”);
%>
·         By using RequestDispatcher object: For example:
·          
·         <%
·          RequestDispatcherrd = request.getRequestDispatcher(“/header.jsp”);
·           Rd.incliude(request,response);
%>

Q: How does JSP engines instantiate tag handler classes instances?
A: JSP engines will always instantiate a new tag handler instance every time a tag is encountered in a JSP page. A pool of tag instances are maintained and reusing them where possible. When a tag is encountered, the JSP engine will try to find a Tag instance that is not being used and use the same and then release it.

Q: What’s the difference between JavaBeans and taglib directives?
A: JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them:
·         Taglibs are for generating presentation elements while JavaBeans are good for storing information and state.
·         Use custom tags to implement actions and JavaBeans to present information.

Q: What is JSP and why do we need it?
A: JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. JSP is extension of Servlet technology to help developers create dynamic pages with HTML like syntax.
We can create user views in servlet also but the code will become very ugly and error prone. Also most of the elements in web page is static, so JSP page is more suitable for web pages. We should avoid business logic in JSP pages and try to use it only for view purpose. JSP scripting elements can be used for writing java code in JSP pages but it’s best to avoid them and use JSP action elements, JSTL tags or custom tags to achieve the same functionalities.
One more benefit of JSP is that most of the containers support hot deployment of JSP pages. Just make the required changes in the JSP page and replace the old page with the updated jsp page in deployment directory and container will load the new JSP page. We don’t need to compile our project code or restart server whereas if we make change in servlet code, we need to build the complete project again and deploy it. Although most of the containers now provide hot deployment support for applications but still it’s more work that JSP pages.

Q: What are the JSP lifecycle phases?
A: If you will look into JSP page code, it looks like HTML and doesn’t look anything like java classes. Actually JSP container takes care of translating the JSP pages and create the servlet class that is used in web application. JSP lifecycle phases are:
A.     Translation – JSP container checks the JSP page code and parse it to generate the servlet source code. For example in Tomcat you will find generated servlet class files atTOMCAT/work/Catalina/localhost/WEBAPP/org/apache/jsp directory. If the JSP page name is home.jsp, usually the generated servlet class name is home_jsp and file name is home_jsp.java
B.     Compilation – JSP container compiles the jsp class source code and produce class file in this phase.
C.    Class Loading – Container loads the class into memory in this phase.
D.    Instantiation – Container invokes the no-args constructor of generated class to load it into memory and instantiate it.
E.     Initialization – Container invokes the init method of JSP class object and initializes the servlet config with init params configured in deployment descriptor. After this phase, JSP is ready to handle client requests. Usually from translation to initialization of JSP happens when first request for JSP comes but we can configure it to be loaded and initialized at the time of deployment like servlets using load-on-startup element.
F.     Request Processing – This is the longest lifecycle of JSP page and JSP page processes the client requests. The processing is multi-threaded and similar to servlets and for every request a new thread is spawned and ServletRequest and ServletResponse object is created and JSP service method is invoked.
G.    Destroy – This is the last phase of JSP lifecycle where JSP class is unloaded from memory. Usually it happens when application is undeployed or the server is shut down.

Q: What are JSP lifecycle methods?
A: JSP lifecycle methods are:
jspInit(): This method is declared in JspPage and it’s implemented by JSP container implementations. This method is called once in the JSP lifecycle to initialize it with config params configured in deployment descriptor. We can override this method using JSP declaration scripting element to initialize any resources that we want to use in JSP page.

_jspService(): This is the JSP method that gets invoked by JSP container for each client request by passing request and response object. Notice that method name starts with underscore to distinguish it from other lifecycle methods because we can’t override this method. All the JSP code goes inside this method and it’s overridden by default. We should not try to override it using JSP declaration scripting element. This method is defined in HttpJspPage interface.

jspDestroy(): This method is called by container when JSP is unloaded from memory such as shutting down application or container. This method is called only once in JSP lifecycle and we should override this method to release any resources created in JSP init method.


Q: Which JSP lifecycle methods can be overridden?
A: We can override jspInit() and jspDestroy() methods using JSP declaration scripting element. We should override jspInit() methods to create common resources that we would like to use in JSP service method and override jspDestroy() method to release the common resources.

Q: How can we avoid direct access of JSP pages from client browser?
A: We know that anything inside WEB-INF directory can’t be accessed directly in web application, so we can place our JSP pages in WEB-INF directory to avoid direct access to JSP page from client browser. But in this case, we will have to configure it in deployment descriptor just like Servlets. Sample configuration is given below code snippet of web.xml file.

<servlet>
  <servlet-name>Test</servlet-name>
  <jsp-file>/WEB-INF/test.jsp</jsp-file>
  <init-param>
    <param-name>test</param-name>
    <param-value>Test Value</param-value>
  </init-param>
</servlet>
   
<servlet-mapping>
  <servlet-name>Test</servlet-name>
  <url-pattern>/Test.do</url-pattern>
</servlet-mapping>

Q: What are different types of comments in JSP?
A: JSP pages provide two types of comments that we can use:
·         HTML Comments: Since JSP pages are like HTML, we can use HTML comments like <-- HTML Comment -->. These comments are sent to client also and we can see it in HTML source. So we should avoid any code level comments or debugging comments using HTML comments.
·         JSP Comments: JSP Comments are written using scriptlets like <%-- JSP Comment --%>. These comments are present in the generated servlet source code and doesn’t sent to client. For any code level or debugging information comments we should use JSP comments.

Q: What is Scriptlet, Expression and Declaration in JSP?
A: Scriptlets, Expression and Declaration are scripting elements in JSP page using which we can add java code in the JSP pages.
A scriptlet tag starts with <% and ends with %>. Any code written inside the scriptlet tags go into the_jspService() method. For example;


<%
Date d = new Date();
System.out.println("Current Date="+d);
%>
Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this through JSP Expressions. JSP Expression starts with <%= and ends with %>.
<% out.print("Pankaj"); %> can be written using JSP Expression as <%= "Pankaj" %>
Notice that anything between <%= %> is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements and always ends with semicolon (;) but expression doesn’t end with semicolon.
JSP Declarations are used to declare member methods and variables of servlet class. JSP Declarations starts with <%! and ends with %>.
For example we can create an int variable in JSP at class level as <%! public static int count=0; %>.

Q: What are JSP implicit objects?
A: JSP implicit objects are created by container while translating JSP page to Servlet source to help developers. We can use these objects directly in scriptlets that goes in service method, however we can’t use them in JSP Declaration because that code will go at class level.
We have 9 implicit objects that we can directly use in JSP page. Seven of them are declared as local variable at the start of _jspService() method whereas two of them are part of _jspService() method argument that we can use.

out Object
request Object
response Object
config Object
application Object
session Object
pageContext Object
page Object
exception Object

Q: Can we use JSP implicit objects in a method defined in JSP Declaration?
A: No we can’t because JSP implicit objects are local to service method and added by JSP Container while translating JSP page to servlet source code. JSP Declarations code goes outside the service method and used to create class level variables and methods and hence can’t use JSP implicit objects.

Q: Which implicit object is not available in normal JSP pages?
A: JSP exception implicit object is not available in normal JSP pages and it’s used in JSP error pages only to catch the exception thrown by the JSP pages and provide useful message to the client.

Q: What are the benefits of PageContext implicit object?
A: JSP pageContext implicit object is instance of javax.servlet.jsp.PageContext abstract class implementation. We can use pageContext to get and set attributes with different scopes and to forward request to other resources. pageContext object also hold reference to other implicit object.
This is the only object that is common in both JSP implicit objects and in JSP EL implicit objects.

Q: How do we configure init params for JSP?
A: We can configure init params for JSP similar to servlet in web.xml file, we need to configure JSP init params with servlet and servlet-mapping element. The only thing differs from servlet is jsp-file element where we need to provide the JSP page location.

Q: Why use of scripting elements in JSP is discouraged?
A: JSP pages are mostly used for view purposes and all the business logic should be in the servlet or model classes. We should pass parameters to JSP page through attributes and then use them to create the HTML response in JSP page.
Most part of the JSP page contains HTML code and to help web designers to easily understand JSP page and develop them, JSP technology provides action elements, JSP EL, JSP Standard Tag Library and custom tags that we should use rather than scripting elements to bridge the gap between JSP HTML part and JSP java part.

Q: How can we disable java code or scripting in JSP page?
A: We can disable scripting elements in JSP pages through deployment descriptor configuration like below.




<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

Above url-pattern will disable scripting for all the JSP pages but if you want to disable it only for specific page, you can give the JSP file name itself.

Q: Explain JSP Action Elements or Action Tags?
A: JSP action elements or action tags are HTML like tags that provide useful functionalities such as working with Java Bean, including a resource, forwarding the request and to generate dynamic XML elements. JSP action elements always starts with jsp: and we can use them in JSP page directly without the need to import any tag libraries or any other configuration changes. Some of the important action elements are jsp:useBean, jsp:getProperty, jsp:setProperty, jsp:include and jsp:forward.

Q: What is difference between include directive and jsp:include action?
A: The difference between JSP include directive and include action is that in include directive the content to other resource is added to the generated servlet code at the time of translation whereas with include action it happens at runtime.
Another difference is that in JSP include action, we can pass params to be used in the included resource with jsp:param action element but in JSP include directive we can’t pass any params.
When included resource is static such as header, footer, image files then we should use include directive for faster performance but if the included resource is dynamic and requires some parameters for processing then we should use include action tag.

Q: What is JSP Expression Language and what are it’s benefits?
A: Most of the times we use JSP for view purposes and all the business logic is present in servlet code or model classes. When we receive client request in servlet, we process it and then add attributes in request/session/context scope to be retrieved in JSP code. We also use request params, headers, cookies and init params in JSP to create response views.
We can use scriptlets and JSP expressions to retrieve attributes and parameters in JSP with java code and use it for view purpose. But for web designers, java code is hard to understand and that’s why JSP Specs 2.0 introduced Expression Language (EL) through which we can get attributes and parameters easily using HTML like tags.
Expression language syntax is ${name} and we can use EL implicit objects and EL operators to retrieve the attributes from different scopes and use them in JSP page.

Q: What are JSP EL implicit objects and how it’s different from JSP implicit Objects?
A: JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and parameter values. Note that these are different from JSP implicit objects and contains only the attributes in given scope. The only common implicit object in JSP EL and JSP page is pageContext object.
JSP EL Implicit Objects
Type
Description
pageScope
Map
A map that contains the attributes set with page scope.
requestScope
Map
Used to get the attribute value with request scope.
sessionScope
Map
Used to get the attribute value with session scope.
applicationScope
Map
Used to get the attributes value from application scope.
param
Map
Used to get the request parameter value, returns a single value
paramValues
Map
Used to get the request param values in an array, useful when request parameter contain multiple values.
header
Map
Used to get request header information.
headerValues
Map
Used to get header values in an array.
cookie
Map
Used to get the cookie value in the JSP
initParam
Map
Used to get the context init params, we can’t use it for servlet init params
pageContext
pageContext
Same as JSP implicit pageContext object, used to get the request, session references etc. example usage is getting request HTTP Method name.
Table provides list of implicit object in JSP EL.

Q: How to use JSP EL to get HTTP method name?
A: We can use pageContext JSP EL implicit object to get the request object reference and use dot operator to get the HTTP method name in JSP page. The JSP EL code for this will be ${pageContext.request.method}.

Q: What is JSP Standard Tag Library, provide some example usage?
A: JSP Standard Tag Library or JSTL is more versatile than JSP EL or Action elements because we can loop through a collection or escape HTML tags to show them like text in response.
JSTL is part of the Java EE API and included in most servlet containers. But to use JSTL in our JSP pages, we need to download the JSTL jars for your servlet container. Most of the times, you can find them in the example projects and you can use them. You need to include these libraries in the project WEB-INF/lib directory. These jars are container specific, for example in Tomcat, we need to include jstl.jar and standard.jar jar files in project build path.

Q: What are the types of JSTL tags?
A: Based on the JSTL functions, they are categorized into five types.
Core Tags – Core tags provide support for iteration, conditional logic, catch exception, url, forward or redirect response etc.
Formatting and Localization Tags – These tags are provided for formatting of Numbers, Dates and i18n support through locales and resource bundles.
SQL Tags – JSTL SQL Tags provide support for interaction with relational databases such as Oracle, MySql etc.
XML Tags – XML tags are used to work with XML documents such as parsing XML, transforming XML data and XPath expressions evaluation.
JSTL Functions Tags – JSTL tags provide a number of functions that we can use to perform common operation, most of them are for String manipulation such as String Concatenation, Split String etc.

Q: What is JSP Custom Tag and what are it’s components?
A: Sometimes JSP EL, Action Tags and JSTL tags are not enough and we might get tempted to write java code to perform some operations in JSP page. Fortunately JSP is extendable and we can create our own custom tags to perform certain operations.
We can create JSP Custom Tags with following components:
·         JSP Custom Tag Handler
·         Creating Tag Library Descriptor (TLD) File
·         Deployment Descriptor Configuration for TLD
We can add custom tag library in JSP page using taglib directive and then use it.

Q: Give an example where you need JSP Custom Tag?
A: Let’s say we want to show a number with formatting with commas and spaces. This can be very useful for user when the number is really long. So we want some custom tags like below:
<mytags:formatNumber number="123456.789" format="#,###.00"/>
Based on the number and format passed, it should write the formatted number in JSP page, for above example it should print 123,456.79
We know that JSTL doesn’t provide any inbuilt tags to achieve this, so we will create our own custom tag implementation and use it in the JSP page.

Q: Why don’t we need to configure JSP standard tags in web.xml?
A: We don’t need to configure JSP standard tags in web.xml because the TLD files are inside the META-INF directory of the JSTL jar files. When container loads the web application and find TLD files inside the META-INF directory of JAR file, it automatically configures them to be used directly in the application JSP pages. All we need to do it to include it in the JSP page using taglib directive.

Q: How can we handle exceptions thrown by JSP service method?
A: To handle exceptions thrown by the JSP page, all we need is an error page and define the error page in JSP using page directive.
To create a JSP error page, we need to set page directive attribute isErrorPage value to true, then we can access exception implicit object in the JSP and use it to send customized error message to the client.
We need to define exception and error handler JSP pages in the deployment descriptor like below.







<error-page>
     <error-code>404</error-code>
     <location>/error.jsp</location>
</error-page>
  
<error-page>
     <exception-type>java.lang.Throwable</exception-type>
     <location>/error.jsp</location>
</error-page>

Q: How do we catch exception and process it using JSTL?
A: We can use JSTL Core tags c:catch and c:if to catch exception inside the JSP service method and process it. c:catch tag catches the exception and wraps it into the exception variable and we can use c:if condition tag to process it. Below code snippet provide sample usage.






<c:catch var ="exception">
   <% int x = 5/0;%>
</c:catch>
  
<c:if test = "${exception ne null}">
   <p>Exception is : ${exception} <br />
   Exception Message: ${exception.message}</p>
</c:if>
Notice the use of JSP EL in the c:if condition.

Q: How do we print “<br> creates a new line in HTML” in JSP?
A: We can use c:out escapeXml attribute to escape the HTML elements so that it get’s shown as text in the browser, for this scenario we will write code like below.
<c:out value="<br> creates a new line in HTML" escapeXml="true"></c:out>

Q: What is jsp-config in deployment descriptor?
A: jsp-config element is used to configure different parameters for JSP pages. Some of it’s usage are:
·         Configuring tag libraries for the web application like below.
<jsp-config>
        <taglib>
            <taglib-uri>http://journaldev.com/jsp/tlds/mytags</taglib-uri>
            <taglib-location>/WEB-INF/numberformatter.tld</taglib-location>
        </taglib>
</jsp-config>
·         We can control scripting elements in JSP pages.
·         We can control JSP Expression Language (EL) evaluation in JSP pages.
·         We can define the page encoding for URL pattern.
·         To define the buffer size to be used in JSP page out object.
·         To denote that the group of resources that match the URL pattern are JSP documents, and thus must be interpreted as XML documents.

Q: How to ignore the EL expression evaluation in a JSP?
A: We can ignore EL evaluation in JSP page by two ways.
Using page directive as <%@ page isELIgnored="true" %>
Configuring in web.xml – better approach when you want to disable EL evaluation for many JSP pages.

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <el-ignored>true</el-ignored>
    </jsp-property-group>
</jsp-config>

Q: When will Container initialize multiple JSP/Servlet Objects?
A: If we have multiple servlet and servlet-mapping elements in deployment descriptor for a single servlet or JSP page, then container will initialize an object for each of the element and all of these instances will have their own ServletConfig object and init params.
For example, if we configure a single JSP page in web.xml like below.
<servlet>
  <servlet-name>Test</servlet-name>
  <jsp-file>/WEB-INF/test.jsp</jsp-file>
  <init-param>
    <param-name>test</param-name>
    <param-value>Test Value</param-value>
  </init-param>
</servlet>
   
<servlet-mapping>
  <servlet-name>Test</servlet-name>
  <url-pattern>/Test.do</url-pattern>
</servlet-mapping>
   
<servlet>
  <servlet-name>Test1</servlet-name>
  <jsp-file>/WEB-INF/test.jsp</jsp-file>
</servlet>
   
<servlet-mapping>
  <servlet-name>Test1</servlet-name>
  <url-pattern>/Test1.do</url-pattern>
</servlet-mapping>
Then if we can access same JSP page with both the URI pattern and both will have their own init params values.


Q: Can we use JavaScript with JSP Pages?
A: Yes why not, I have seen some developers getting confused with this. Even though JSP is a server side technology, it’s used to generate client side response and we can add javascript or CSS code like any other HTML page.

Q: How can we prevent implicit session creation in JSP?
A: By default JSP page creates a session but sometimes we don’t need session in JSP page. We can use JSP page directive session attribute to indicate compiler to not create session by default. It’s default value is true and session is created. To disable the session creation, we can use it like below.
<%@ page session ="false" %>

Q: What is difference between JspWriter and Servlet PrintWriter?
A: PrintWriter is the actual object responsible for writing the content in response. JspWriter uses the PrintWriter object behind the scene and provide buffer support. When the buffer is full or flushed, JspWriter uses the PrintWriter object to write the content into response.

Q: How can we extend JSP technology?
A: We can extend JSP technology with custom tags to avoid scripting elements and java code in JSP pages.

Q: Provide some JSP Best Practices?
A: Some of the JSP best practices are:
Avoid scripting elements in JSP pages. If JSP EL, action elements and JSTL not serve your needs then create custom tags.
Use comment properly, use JSP comments for code level or debugging purpose so that it’s not sent to client.
Avoid any business logic in JSP page, JSP pages should be used only for response generation for client.
Disable session creation in JSP page where you don’t need it for better performance.
Use page, taglib directives at the start of JSP page for better readability.
Proper use of jsp include directive or include action based on your requirements, include directive is good for static content whereas include action is good for dynamic content and including resource at runtime.
Proper exception handling using JSP error pages to avoid sending container generated response incase JSP pages throw exception in service method.
If you are having CSS and JavaScript code in JSP pages, it’s best to place them in separate files and include them in JSP page.
Most of the times JSTL is enough for our needs, if you find a scenario where it’s not then check your application design and try to put the logic in a servlet that will do the processing and then set attributes to be used in JSP pages.

JSP Interview Questions and Answers

Here are collection of 10 most frequently asked interview questions on JSP , there were lot on my kitty but I only included 10 to avoid getting post lengthy, also my purpose was to prepare a list of questions which can be easily reference before going for any JSP or Java interview. Not wasting any more time here are my top 10 JSP interview questions answers:
Interview Questions Answers on JSP

Q: Explain include Directive and include Action of JSP
A:  This is a very popular interview question on JSP, which has been asked from long time and still asked in various interview. This question is good to test some fundamental concept like translation of JSP and difference between translation time and run time kind of concept.
Syntax for include Directive is <%@ include file="fileName" %> which means we are including some file to our JSP Page when we use include directive contents of included file will be added to calling JSP page at translation time means when the calling JSP is converted to servlet ,all the contents are added to that page .one important thing is that any JSP page is complied if we make any changes to that particular page but if we have changed the included file or JSP page the main calling JSP page will not execute again so the output will not be according to our expectation, this one is the main disadvantage of using the include directive that why it is mostly use to add static  resources, like Header and footer .
Syntax for include action is <jsp:include page=”relativeURL” /> it’s a runtime procedure means the result of the JSP page which is mentioned in relative URL is appended  to calling JSP at runtime on their response object at the location where we have used this tag
So any changes made to included page is being effected every time, this is the main advantage of this action but only relative URL we can use here ,because request and response object is passed between calling JSP and included JSP.

Q: Difference Between include Directive and include Action of JSP
A: This JSP interview question is a continuation of earlier question I just made it a separate one to write answer in clear tabular format.

Include Directive  Include Action
include directive is processed at the translation time  Include action is processed at the run time.
include directive can use relative or absolute path      Include action always use relative path
Include directive can only include contents of resource it will not process the dynamic resource     Include action process the dynamic resource and result will be added to calling JSP
We can not pass any other parameter            Here we can pass other parameter also using JSP:param
We cannot  pass any request or response object to calling jsp to included file or JSP or vice versa In this case it’s possible.

Q: Is it possible for one JSP to extend another java class if yes how?
A: Yes it is possible we can extends another JSP using this <%@ include page extends="classname" %> it’s a perfectly correct because when JSP is converted to servlet its implements javax.servlet.jsp.HttpJspPage interface, so for jsp page its possible to extend another java class . This question can be tricky if you don’t know some basic fact ?, though its not advisable to write java code in jsp instead its better to use expression language and tag library.

Q: What is < jsp:usebean >tag why it is used.
A: This was very popular JSP interview question during early 2000, it has lost some of its shine but still asked now and then on interviews.

JSP Syntax
<jsp:useBean
        id="beanInstName"
        scope="page | request | session | application"
       
            class="package.class"    type="package.class"

           </jsp:useBean>

This tag is used to create a instance of java bean first of all it tries to find out the bean if bean instance already exist assign stores a reference to it in the variable. If we specified type, gives the Bean that type.otherwise instantiates it from the class we specify, storing a reference to it in the new variable.so jsp:usebean is simple way to create a java bean.
Example:
    
<jsp:useBean id="stock" scope="request" class="market.Stock" />
<jsp:setProperty name="bid" property="price" value="0.0" />
a <jsp:useBean> element contains a <jsp:setProperty> element that sets property values in the Bean,we have <jsp:getProperty>element also to get the value from the bean.

Explanation of Attribute
 id="beanInstanceName"
A variable that identifies the Bean in the scope we specify. If the Bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.
scope="page | request | session | application"
The scope in which the Bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:
•               page – we can use the Bean within the JSP page with the <jsp:useBean> element
•               request – we can use the Bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another file.
•               session – we can use the Bean from any JSP page in the same session as the JSP page that created the Bean. The Bean exists across the entire session, and any page that participates in the session can use it..
•               application – we can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean.
class="package.class"
Instantiates a Bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor.
type="package.class"
If the Bean already exists in the scope, gives the Bean a data type other than the class from which it was instantiated. If you use type without class or beanName, no Bean is instantiated.

Q: How can one Jsp Communicate with Java file.
A: We have import tag <%@ page import="market.stock.*” %> like this we can import all the java file to our jsp and use them as a regular class another way is  servlet can send  the instance of the java class to our  jsp and we can retrieve that object from the request obj and use it in our page.

Q: What are the implicit Object
A: This is a fact based interview question what it checks is how much coding you do in JSP if you are doing it frequently you definitely know them. Implicit object are the object that are created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.
They are: request, response, pageContext, session, and application, out, config, page, and exception.

Q: In JSP page how can we handle runtime exception?
A: This is another popular JSP interview question which has asked to check how candidate used to handle Error and Exception in JSP. We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.

Example: <%@ page errorPage="error.jsp" %>
It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage="true" %>

Q: Why is _jspService() method starting with an '_' while other life cycle methods do not?
A: main JSP life cycle method are jspInit() jspDestroy() and _jspService() ,bydefault whatever content we write in our jsp page will go inside the _jspService() method by the container if again will try to override this method JSP compiler will give error but we can override other two life cycle method as we have implementing this two in jsp so making this difference container use _ in jspService() method and shows that we cant override this method.

Q: How can you pass information form one jsp to included jsp:
A: This JSP interview question is little tricky and fact based. Using < Jsp: param> tag we can pass parameter from main jsp to included jsp page
Example:
<jsp:include page="newbid.jsp" flush="true">
<jsp:param name="price" value="123.7"/>
<jsp:param name="quantity" value="4"/>

Q: what is the need of tag library?
A: tag library is a collection of custom tags. Custom actions helps recurring tasks will be handled more easily they can be reused across more than one application and increase productivity. JSP tag libraries are used by Web application designers who can focus on presentation issues rather than being concerned with how to access databases and other enterprise services. Some of the popular tag libraries are Apache display tag library and String tag library. You can also check my post on display tag library example on Spring.
JSP Interview Questions
The following are some questions you might encounter with respect to Java Server Pages or JSPs in any Interview. JSPs are an integral part of almost all J2EE Web Applications and any interviewer who is selecting people for his J2EE project would want a person who is confident & comfortable using them.

JSP Questions:

Q: What is JSP?
A: JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications.

Q: What do you understand by JSP Actions?
A: JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions:

< jsp : include / >
< jsp : forward / >
< jsp : plugin / >
< jsp : usebean / >
< jsp : setProperty / >
< jsp : getProperty / >

Q: What is the difference between < jsp : include page = ... > and < % @ include file = ... >?
A: Both the tags include information from one JSP page in another. The differences are:

< jsp : include page = ... >

This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful while modularizing a web application. If the included file changes then the new content will be included in the output automatically.

< % @ include file = ... >

In this case the content of the included file is textually embedded in the page that have < % @ include file=".."> directive. In this case when the included file changes, the changed content will not get included automatically in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.

Q: What is the difference between < jsp : forward page = ... > and response.sendRedirect(url)?
A: The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect also kills the session variables.

Q: Name one advantage of JSP over Servlets?
A: Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets.
However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen.

Q: What are implicit Objects available to the JSP Page?
A: Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:

                application
                config
                exception
                out
                page
                pageContext
                request
                response and
                session

Q: What are all the different scope values for the < jsp : useBean > tag?
A: < jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag:
                a) page
                b) request
                c) session and
                d) application

Q: What is JSP Output Comments?
A: JSP Output Comments are the comments that can be viewed in the HTML source file. They are comments that are enclosed within the < ! - - Your Comments Here - - >

Q: What is expression in JSP?
A: Expression tag is used to insert Java values directly into the output.
Syntax for the Expression tag is: < %= expression % >
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The most commonly used language is regular Java.

Q: What types of comments are available in the JSP?
A: There are two types of comments that are allowed in the JSP. They are hidden and output comments.
A hidden comment does not appear in the generated HTML output, while output comments appear in the generated output.
Example of hidden comment:
< % - - This is a hidden comment - - % >

Example of output comment:
< ! - - This is an output comment - - >

Q: What is a JSP Scriptlet?
A: JSP Scriptlets is a term used to refer to pieces of Java code that can be embedded in a JSP PAge. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.

Q: What are the life-cycle methods of JSP?
A: Life-cycle methods of the JSP are:

a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.

b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.

c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

Q: What are JSP Custom tags?
A: JSP Custom tags are user defined JSP language elements. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tags to encapsulate both simple and complex behaviors in an easy to use syntax. The use of custom tags greatly enhances the functionality and simplifies the readability of JSP pages.

Q: What is the role of JSP in MVC Model?
A: JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.

Q: What do you understand by context initialization parameters?
A: The context-param element contains the declaration of a web application's servlet context initialization parameters.
< context - param >
< param - name > name < / param - name > < param - value > value < / param - value >
< / context-param >

The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.

Q: Can you extend JSP technology?
A: Yes. JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions & tag libraries can be developed to enhance/extend its features.

Q: What do you understand by JSP translation?
A: JSP translation is an action that refers to the convertion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.

Q: How can you prevent the Browser from Caching data of the Pages you visit?
A: By setting properties that prevent caching in your JSP Page. They are:
<% response.setHeader("pragma","no-cache");//HTTP 1.1 response.setHeader("Cache-Control","no-cache"); response.setHeader("Cache-Control","no-store"); response.addDateHeader("Expires", -1); response.setDateHeader("max-age", 0); //response.setIntHeader ("Expires", -1); //prevents caching at the proxy server response.addHeader("cache-Control", "private"); %>

Q: How will you handle the runtime exception in your jsp page?
A: The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. You can define the error page to which you want the request forwarded to, in case of an exception, in each JSP Page. Also, there should be another JSP that plays the role of the error page which has the flag isErrorPage set to True.

Q: What is JavaServer Pages Standard Tag Library (JSTL) ?
A: A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.

Q: What is JSP container ?
A: A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

Q: What is JSP custom action ?
A: A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.

Q: What is JSP custom tag ?
A: A tag that references a JSP custom action.

Q: What is JSP declaration ?
A: A JSP scripting element that declares methods, variables, or both in a JSP page.

Q: What is JSP directive ?
A: A JSP element that gives an instruction to the JSP container and is interpreted at translation time.

Q: What is JSP document ?
A: A JSP page written in XML syntax and subject to the constraints of XML documents.

Q: What is JSP element ?
A: A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.

Q: What is JSP expression ?
A: A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object.

Q: What is JSP expression language ?
A: A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression.

Q: What is JSP page ?
A: A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.

Q: What is JSP scripting element ?
A: A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java".

Q: What is JSP scriptlet ?
A: A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java".

Q: What is JSP tag file ?
A: A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.

Q: What is JSP tag handler ?
A: A Java programming language object that implements the behavior of a custom tag.
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

Q: How to use forEach tag in JSP page
A: forEach tag is part of standard JSTL core package and written as <foreach> or <c:foreach> or <core:foreach> whatever prefix you are using in taglib directive while importing JSTL core library. In order to use foreach tag in JSP pages you need to import JSTL tag library in jsp and also need to include jstl.jar in your WEB-INF/lib directory or in Java classpath. if you are using Eclipse or Netbeans IDE than it will assist you on on code completion of foreach tag otherwise you need to remember its basic syntax as shown below:

Syntax of foreach tag in JSTL

<c:forEach var="name of scoped variable"
           items="Colleciton,List or Array"  varStatus="status">
where var and items are manadatory and varStatus, begin, end or step attributes are optional. Here is an example of foreach tag:

<c:forEach var="window" items="${pageScope.windows}">
    <c:out value="${window}"/>
</c:forEach>

above JSTL  foreach tag is equivalent to following foreach loop of Java 1.5

foreach(String window: windows){
   System.out.println(window);
}

JSTL foreach tag examples
In this section of JSTL tutorial we will see some more examples of using foreach tag in JSP page for looping purpose. Just try couple of example and you will get hold of foreach it looks more easy after trying few examples.

Iterating over collections or List using JSTL forEach loop
In order to iterate over collections e.g. List or Set you need to create those collections and store that into any scope mentioned above e.g. pageScope and than access it using expression language like ${pageScope.myList}. see the JSP page in last example for complete code example of foreach tag.

Iterating over array using JSTL  forEach loop
For iterating over an array e.g. String array or integer array in JSP page,  "items" attribute must resolved to an array. You can use expression language to get an Array stored in of scope available in JSP e.g. page scope, request scope, session or application scope. These are different than bean scope in Spring MVC and don’t confuse between Spring bean scope and JSP variable scope if you are using Spring MVC in your Java webapplication. Rest of foreach loop will be similar to foreach loop example of iterating over Collections in Java.


JSTL  foreach example using varStatus variable
varStatus attribute declare name of variable which holds current looping counter for foreach tag. It also expose several useful information which you can access using varStatus e.g. what is current row, whether you are in last row etc. Here is a code example of how to use varStatus in foreach JSTL tag on JSP:

<%-- JSTL foreach tag varStatus example to show count in JSP  --%>
<c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" >
    <c:out value="count: ${loopCounter.count}"/>
    <c:out value="${window}"/>
</c:forEach>

Output:
JSTL foreach tag example in JSP
count: 1 Windows XP
count: 2 Windows 7
count: 3 Windows 8
count: 4 Windows mobile

Some other handy properties are : first, last, step, begin, end, current, index and count

Nested foreach tag example in JSP JSTL
Another good thing of JSTL foreach tag is you can nest foreach tag loop inside another foreach tag which is quite powerful way of looping without using scriptlets in JSP. Here is an example of nesting foreach tag in JSP JSTL tag library:

<%-- JSTL foreach tag example to loop an array in JSP and nesting of foreach loop --%>
<c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" >
   <c:out value="outer loop count: ${loopCounter.count}"/>
   <c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" > 
       <c:out value="inner loop count: ${loopCounter.count}"/>
   </c:forEach>
</c:forEach>

Output:
outer loop count: 1
inner loop count: 1
inner loop count: 2
outer loop count: 2
inner loop count: 1
inner loop count: 2

Complete JSTL  foreach loop example in JSP
Here is complete JSP page which shows how to use JSTL foreach tag for looping over String array . Similarly you can loop over any Collection e.g. List or Set as well.

<%@page import="java.util.List"%>
<%@page import="java.util.Arrays"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
       <title>Welcome to JSTL foreach tag Example in JSP</title>
    </head>

    <body>
        <h2>JSTL foreach tag example in JSP</h2>

        <jsp:scriptlet>
            String[] windows = new String[]{"Windows XP", "Windows 7", "Windows 8", "Windows mobile"};
            pageContext.setAttribute("windows", windows);
        </jsp:scriptlet>

        <%-- JSTL foreach tag example to loop an array in jsp --%>
        <c:forEach var="window" items="${pageScope.windows}">
            <c:out value="${window}"/>
        </c:forEach>
    </body>
</html>

Output:
JSTL foreach tag example in JSP
Windows XP
Windows 7
Windows 8

Windows mobile


1 comment: