JSP Interview Questions

Q) What is the difference between ServletContext and PageContext?
A)
ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

Q) What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
A)
request.getRequestDispatcher(path): In order to create it we need to give the relative path of   the  resource.
context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

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

Q) What is the difference between directive include and jsp include?
A)
<%@ include> : Used to include static resources during translation time.
: Used to include dynamic content or static content during runtime.

Q) What is the difference between RequestDispatcher and sendRedirect?
A)
RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.

Q) How does JSP handle runtime exceptions?
A)
Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

Q) How do you delete a Cookie within a JSP?
A)
Cookie mycook = new Cookie(“name”,”value”);
response.addCookie(mycook);

Cookie killmycook = new Cookie(“mycook”,”value”);
killmycook.setMaxAge(0);
killmycook.setPath(“/”);
killmycook.addCookie(killmycook);

Q) How do I mix JSP and SSI #include?
A)
If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.            <!–#include file=”data.inc”–>
But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. Ronel Sumibcay (ronel@LIVESOFTWARE.COM) says:
If your data.inc  file contains jsp code you will have to use
<%@ vinclude=”data.inc” %>
The <!–#include file=”data.inc”–>  is used for including non-JSP files.

Q) What is the difference between Model 1 and Model 2 architecture?
A)
In Model 1 there is no Controller and in Model 2 there is a Controller.

Q) How can my application get to know when a HttpSession is removed?
A)
Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.
Create an instance of that class and put that instance in HttpSession.

Q) How can I implement a thread-safe JSP page?
A)
You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe=”false” % > within your JSP page.

Q) How many JSP scripting elements are there and what are they?
A)
There are three scripting language elements:
declarations
scriptlets
expressions

Q) In the Servlet 2.4 specification SingleThreadModel has been deprecates, why?
A)
Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

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. The following example shows the syntax: 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) How do I mix JSP and SSI #include?
A)
If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.
<!–#include file=”data.inc”–>
But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. If your data.inc file contains jsp code you will have to use
<%@ vinclude=”data.inc” %>
The <!–#include file=”data.inc”–> is used for including non-JSP files.

Q) Can a JSP page process HTML FORM data?
A)
Yes. However, unlike servlets, 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 as:
<%
String item = request.getParameter(“item”);
int howMany = new Integer(request.getParameter(“units”)).intValue();
%>
or
<%= request.getParameter(“item”) %>

Q) What JSP lifecycle methods can I override?
A)
You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy(). The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
<%!
public void jspInit() {
. . .
}
%>
<%!
public void jspDestroy() {
. . .
}
%>

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. The following example shows the syntax:

<%@ include file=”copyright.html” %>

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) How do I perform browser redirection from a JSP page?
A)
You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect(“http://www.foo.com/path/error.html”);
You can also physically alter the Location HTTP header attribute, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = “/newpath/index.html”;
response.setHeader(“Location”,newLocn);
%>
You can also use the:
<jsp:forward page=”/newpage.jsp” /> Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well.
If you want to pass any paramateres then you can pass using <jsp:forward page=”/servlet/login”> <jsp:param name=”username” value=”jsmith” /> </jsp:forward>>

Q) Can a JSP page instantiate a serialized bean?
A) No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:

<jsp:useBean id=”shop” type=”shopping.CD” beanName=”CD” />
<jsp:getProperty name=”shop” property=”album” />

A couple of important points to note. Although you would have to name your serialized file “filename.ser”, you only indicate “filename” as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine.

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. A page author can always disable the default buffering for any page using a page directive as:
<%@ page buffer=”none” %>

Q) What’s a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
A)
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server’s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free – which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

Q) Can I stop JSP execution while in the midst of processing a request?
A)
Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use the return statement when you want to terminate further processing. For example, consider:

<% if (request.getParameter(“foo”) != null)
{
// generate some html or update bean property
}
else {

/* output some error message or provide redirection back to the input form after creating a memento bean updated with the ‘valid’ form elements that were input. this bean can now be used by the previous form to initialize the input elements that were valid then, return from the body of the _jspService() method to terminate further processing */

return;
}

Q) How can I get to view any compilation/parsing errors at the client while developing JSP pages?
A)
With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:
jsp.initparams=sendErrToClient=true
This will cause any compilation/parsing errors to be sent as part of the response to the client.

Q) Is there a way to reference the “this” variable within a JSP page?
A) Yes, there is. Under JSP 1.0, the page implicit object is equivalent to “this”, and returns a reference to the servlet generated by the JSP page.

Q) How do I instantiate a bean whose constructor accepts parameters using the useBean tag?
A)
Consider the following bean: package bar;
public class FooBean
{
public FooBean(SomeObj arg)
{

}
//getters and setters here
}
The only way you can instantiate this bean within your JSP page is to use a scriptlet. For example, the following snippet creates the bean with session scope:

&l;% SomeObj x = new SomeObj(…);
bar.FooBean foobar = new FooBean(x);
session.putValue(“foobar”,foobar);
%>
You can now access this bean within any other page that is part of the same session as:

&l;%
bar.FooBean foobar = session.getValue(“foobar”);
%>
To give the bean “application scope”, you will have to place it within the ServletContext as:
&l;%
application.setAttribute(“foobar”,foobar);
%>
To give the bean “request scope”, you will have to place it within the request object as:
&l;%
request.setAttribute(“foobar”,foobar);
%>

If you do not place the bean within the request, session or application scope, the bean can be accessed only within the current JSP page (page scope).
Once the bean is instantiated, it can be accessed in the usual way:
jsp:getProperty name=”foobar” property=”someProperty”/ jsp:setProperty name=”foobar” property=”someProperty” value=”someValue”/

JSP Interview Questions

JSP INTERVIEW QUESTIONS AND ANSWERS

Q) Briefly explain about Java Server Pages technology?
A)
JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

Q) What is a JSP Page?
A)
A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML,WML,XML,etc), and JSP elements, which construct dynamic content.JSP is a technology that lets you mix static content with dynamically-generated content.

Q) Why do I need JSP technology if I already have servlets?
A)
JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

Q) How are the JSP requests handled?
A)
The following sequence of events happens on arrival of jsp request:
a. Browser requests a page with .jsp file extension in webserver.
b. Webserver reads the request.
c. Using jsp compiler,webserver converts the jsp into a servlet class that implement the javax.servletjsp.jsp page interface.the jsp file compiles only when the page is first requested or when the jsp file has been changed.
d. The generated jsp page servlet class is invoked to handle the browser request.
e. The response is sent to the client by the generated servlet.

Q) What are the advantages of JSP?
A)
The following are the advantages of using JSP:
a. JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content.
b. JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired.
c. JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the complexity of application logic.
d. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.
e. Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly, developers can make logic changes at the component level without editing the individual pages that use the logic.

Q) How is a JSP page invoked and compiled?
A)
Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

Q) What are Directives?
A)
Directives are instructions that are processed by the JSP engine when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined between < %@ and % >.
< %@ page language==”java” imports==”java.util.*” % >
< %@ include file==”banner.html” % >

Q) What are the different types of directives available in JSP?
A)
The following are the different types of directives:
a. include directive : used to include a file and merges the content of the file with the current page
b. page directive : used to define page specific attributes like scripting language, error page, buffer, thread safety, etc
c. taglib : used to declare a custom tag library which is used in the page.

Q) What are JSP actions?
A)
JSP actions are executed when a JSP page is requested. Action are inserted in the jsp page using XML syntax to control the behavior of the servlet engine. Using action, we can dynamically insert a file, reuse bean components, forward the user to another page, or generate HTML for the Java plugin. Some of the available actions are as follows:
<jsp:include> – include a file at the time the page is requested.
<jsp:useBean> – find or instantiate a JavaBean.
<jsp:setProperty> – set the property of a JavaBean.
<jsp:getProperty> – insert the property of a JavaBean into the output.
<jsp:forward> – forward the requester to a new page.
<jsp:plugin> – generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.

Q) What are Scriptlets?
A)
Scriptlets are blocks of programming language code (usually java) embedded within a JSP page. Scriptlet code is inserted into the servlet generated from the page. Scriptlet code is defined between <% and %>

Q) What are Decalarations?
A)
Declarations are similar to variable declarations in Java.Variables are defined for subsequent use in expressions or scriptlets. Declarations are defined between <%! and %>.
< %! int i=0; %>

Q) How to declare instance or global variables in jsp?
A)
Instance variables should be declared inside the declaration part. The variables declared with JSP declaration element will be shared by all requests to the jsp page.
< %@ page language==”java” contentType=”text/html”% >
< %! int i=0; %>

Q) What are Expressions?
A)
Expressions are variables or constants that are inserted into the data returned by the web server. Expressions are defined between <% = and % >
< %= scorer.getScore() %>

Q) What is meant by implicit objects? And what are they?
A)
Implicit objects are those objects which are avaiable by default. These objects are instances of classesdefined by the JSP specification. These objects could be used within the jsp page without being declared.
The following are the implicit jsp objects:
1. application
2. page
3. request
4. response
5. session
6. exception
7. out
8. config
9. pageContext

Q) How do I use JavaBeans components (beans) from a JSP page?
A)
The JSP specification includes standard tags for bean use and manipulation. The <jsp:useBean> tag creates an instance of a specific JavaBean class. If the instance already exists, it is retrieved. Otherwise, a new instance of the bean is created. The <jsp:setProperty> and <jsp:getProperty> tags let you manipulate properties of a specific bean.

Q) What is the difference between <jsp:include> and <%@include:>
A)
Both are used to insert files into a JSP page.
<%@include:> is a directive which statically inserts the file at the time the JSP page is translated into a servlet.
<jsp:include> is an action which dynamically inserts the file at the time the page is requested.

Q) What is the difference between forward and sendRedirect?
A)
Both requestDispatcher.forward() and response.sendRedirect() is used to redirect to new url.
forward is an internal redirection of user request within the web container to a new URL without the knowledge of the user(browser). The request object and the http headers remain intact.
sendRedirect is normally an external redirection of user request outside the web container. sendRedirect sends response header back to the browser with the new URL. The browser send the request to the new URL with fresh http headers. sendRedirect is slower than forward because it involves extra server call.

Q) Can I create XML pages using JSP technology?
A)
Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output.

Q) How is Java Server Pages different from Active Server Pages?
A)
JSP is a community driven specification whereas ASP is a similar proprietary technology from Microsoft. In JSP, the dynamic part is written in Java, not Visual Basic or other MS-specific language. JSP is portable to other operating systems and non-Microsoft Web servers whereas it is not possible with ASP

Q) Can’t Javascript be used to generate dynamic content rather than JSP?
A)
JavaScript can be used to generate dynamic content on the client browser. But it can handle only handles situations where the dynamic information is based on the client’s environment. It will not able to harness server side information directly.