JSP Interview Questions and Answers part 4
JSP life cycle include
- Translation - convert the JSP source code file to servlet.
- Compilation - compile the servlet to .class file.
- Loading - servlet class is loaded into the container.
- Phase - In this the container manage one or more instances of this class in response to requests and other events.
- Initialization - jspInit() method is called.
- _jspService() execution - called for every request of this JSP during its life cycle.
- jspDestroy() execution - called when this JSP is destroyed.
JSP is meant for web-developers those who are good at HTML. In JSP you can create your custom tags but you cannot create tags in servlet. JSP are http protocol based but servlet can use any protocol.
JSP has pre-available object on which you can work. These objects are parsed by the JSP engine and inserted into the generated servlet. The some of the implicit objects are list below.
There are 3 scripting language elements
EL stands for Expression Language. It provides many objects that can be used directly like param, requestScope, applicationScope, request, session etc.
JSP directives are message to web container that how to translate a jsp to servlet.
- page directive : <%@ page attribute=" "%>
- include directive : <%@ include file=" " %>
- taglib directive : <%@ taglib uri=" " prefix=" " %>
You can only override the JSP life cycle by overriding jspInit() and jspDestroy() methods. jspInit() is useful for allocating resources like database connections, network connections etc for the JSP page. jspDestroy() method is use to free allocated resource.
|include directive, includes the content of the other file during the translation to a servlet.||include action, includes the response generated by executing the specified page during the request processing phase.|
|It is a static import.||It is a dynamic import.|
|Need to compile after changes in file.||No need to compile after changes in file as change data will show in next request.|
|Syntax : <%@ include file="import.jsp'%>||Syntax : <%@ include page="import.jsp" %>|
|Include Directive used file attribute to include a file.||Include Action used page attribute to include a file.|
include directive is use to include the content of any JSP, HTML, text file. The include directive include the original content of the included resource at page translation time.
Syntax : : <% @include file="file name"%>
There are following standard actions available in JSP
- <jsp:include> : It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
- <jsp:forward> : It forwards a response from a servlet or a JSP page to another page.
- <jsp:useBean> : It makes a JavaBean available to a page and instantiates the bean.
- <jsp:setProperty> : It sets the properties for a JavaBean.
- <jsp:getProperty> : It gets the value of a property from a JavaBean component and adds it to the response.
- <jsp:param> : It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
- <jsp:plugin> : It is used to include a Java applet or a JavaBean in the current JSP page.
There are several page directive attributes given below
A scriptlet can contain any number of JAVA code, variable or method declarations, or expressions.
Syntax : <% java code %>
Declaration is use to define one or more variables or method that you can use later in jsp file.
Syntax : <%! int i = 0; %>
It is mainly use to print values of variable or method. Instead of writing out.print() to write data expression is used.
Syntax : <%= statement %>
Use page directive to extend any java class.
<%@ page extends="your.java.class">
You can communicate with any java file in JSP, you just want to use page directive to extend any java class.
Syntax : <%@ page extends="your.java.class">
You can use the errorPage attribute of the page directive, when run-time exceptions occur page directive will automatically forwarded to an error processing page. For example:
<%@ page errorPage="error.jsp" %> redirects the browser to the error.jsp page.
Tag library in jsp is called JSTL [Java Strandard Tag Library] , it is a collection of jsp tags which encapsulate core functionality common to many jsp applications.
It is introduce in jsp to avoid the java code inside the jsp file and follow MVC pattern, as jsp meant for view in this pattern and view part should not contain java code. That why JSTL use tags which are easy for web developers to write in jsp file.
JSESSIONID is a cookie generated by servlet container. JSESSIONID is used for session management in J2EE web application for http protocol. As Http is a connectionless protocol, there is no way for the server to identify from which client the request is coming, so to identify client server maintain the JSESSIONID for each client.
There are two to define error page in jsp application
- Page wise error - It is define on each page of jsp, if any runtime unhandled exception occur it shows the error page.
- Default error page - It is shown if any unhandled exception occur the default error page will display, no page specific error.
- Using custom tag presentation logic separates from the business logic completely.
- Custom tag created by developer and used by web designer whereas web designer cannot use java bean if does not know java.
- Custom tag can manipulate jsp content whereas java bean cannot.
A tag library descriptor is an XML file that contains information about a library as a whole and about each tag contained in the library. TLDs are used by a web container to validate the tags and by JSP page development tools. TLD file name must have .tld extension and must be under WEB-INF folder.
All JSP session are enabled by default. When jsp send a request it create a HttpSession object to maintain state for each unique client and session object use the server resource and stored on server side. This increase the traffic as session id is sent from server to client and client to send for each request and response. If there is no need to maintain a session on website it's better to disable session.
You need to set the session attribute of the page directive to false.
Syntax : <%@ page session="false" %>
Jsp pages are not thread-safe by default, to make JSPs page thread-safe, you need to implement the SingleThreadModel that prevents two threads from accessing the service method at the same time.
Add the following directive in your JSP page declaration : <%@ page isThreadSafe="false" %>
- In servlet life cycle servlet object is created first. The init() method is invoked by the servlet container and the servlet is initialized by its arguments. Servlet's service() method is invoked next. And at the end, the destroy() method is invoked.
- In JSP life cycle the JSP first convert to servlet and then servlet life cycle begins.
Use implicit object of response to redirect from a jsp page. Example response.sendRedirect(http://www.tkhts.com);
Or use <jsp:forward page="/login"> <jsp:param name="username" value="xyz" /> </jsp:forward> to forward the any output to client.
MVC stands for Model View Controller. In MVC JSP is use as a view/presentation part, to display the content on client browser, JSP use JSTL and EL to eliminate the java code from the view. Controller is a servlet act as a middleware and model is a POJO class which processes the data from the database.
- The ServletContext hold the reference to the overall context of the web application.
- The PageContext is a collection of request and response references for a single JSP servlet instance, for handling errors, forwarding requests
No,you cannot implement the interface in the JSP file.
you can declare method in JSP page to use within JSP. The methods can invoke any other methods you declare, or within JSP scriptlets and expressions.
|What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation
JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(â€œâ€¦.. â€?) statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.
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 response.
|Explain the life cycle methods of a JSP?
Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls this method for each request.
Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.
|What are different type of scripting elements?
Declaration Element: 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.
Expression Element: is the embedded Java expression, which gets evaluated by the service method.
<%= new Date()>
Scriptlet Elements: are the embedded Java statements, which get executed as part of the service method.
(Note: 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).
Action Elements: A JSP element that provides information for execution phase.
<jsp:useBean id="object_name" class="class_name"/>
<jsp:include page="scripts/login.jsp" />
Directive Elements: A JSP element that provides global information for the translation phase.
<%@ page import=â€?java.util.Dateâ€? %>
<%@ include file=â€?myJSPâ€? %>
<%@ taglib uri=â€?tagliburiâ€? prefix=â€?myTagâ€?%>
|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?
|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 are declarations, and will only be evaluated once when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets have the local scope and not shared.
<% int a = 5 %>;
|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:
<jsp:useBean id="identifier" class="packageName.className"/>
|What is a 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. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression.
|Difference between forward and sendRedirect?
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
|What are implicit objects? List them?
Certain 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 listed below:
|How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
How to implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
JSPs can be thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive
<%@ page isThreadSafe="false" %>
within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .
|Why to use the HttpServlet Init method to perform expensive operations that need only be done once?
Ans) Because the servlet init() method is invoked when servlet instance is loaded, it is the
perfect location to carry out expensive operations that need only be performed during
initialization. By definition, the init() method is thread-safe. The results of operations in
the HttpServlet.init() method can be cached safely in servlet instance variables, which
become read-only in the servlet service method.
|Why is it not a good practice to create HttpSessions in JSPs by default?
Ans) By default, JSP files create HttpSessions. This is in compliance with J2EETM to facilitate
the use of JSP implicit objects, which can be referenced in JSP source and tags without
explicit declaration. HttpSession is one of those objects. If you do not use HttpSession
in your JSP files then you can save some performance overhead with the following JSP
|What are the standard actions available in JSP?
Ans) The standard actions available in JSP are as follows:
<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.