JSP Interview Questions
JSP Interview Questions
Set 1:
Q:What is a output comment?
A:A comment that is sent to the client in the viewable page source.The JSP engine
handles an output comment as uninterpreted HTML text, returning the comment in the
HTML output sent to the client. You can see the comment by viewing the page source
from your Web browser.
JSP Syntax
<!-- comment [ <%= expression %> ] -->
Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->
You can use any characters in the body of the comment except the closing --%>
combination. If you need to use --%> in your comment, you can escape it by typing --
%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>
TOP
Q:What is a Expression?
A: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
2
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
TOP
Q:What is a Declaration?
A:A declaration declares one or more variables or methods for use later in the JSP source
file.
A declaration must contain at least one complete declarative statement. You can
declare any number of variables or methods within one declaration tag, as long as they
are separated by semicolons. The declaration must be valid in the scripting language
used in the JSP file.
Q:What is a Scriptlet?
A:A scriptlet can contain any number of language statements, variable or method
declarations, or expressions that are valid in the page scripting language.Within
scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client
request. If the scriptlet produces output, the output is stored in the out object, from
which you can display it.
TOP
• application
• out
• config
• page
• exception
TOP
1. page
2. request
3.session
4.application
TOP
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
%>
Q:How can I implement a thread-safe JSP page? What are the advantages and
Disadvantages of using it?
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. 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 .
[ Received from Sumit Dhamija ] TOP
The following example shows the “today” property of the Foo bean initialized to the
current date when it is instantiated. Note that here, we make use of a JSP expression
within the jsp:setProperty action.
</jsp:useBean >
Q:How can I prevent the word "null" from appearing in my HTML input text fields
when I populate them with a resultset that has null values?
A:You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? \"\" : s;
}
%>
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
6
Q:How can I enable session tracking for JSP pages if the browser has disabled
cookies?
A:We know that session tracking uses cookies by default to associate a session identifier
with a unique user. If the browser does not support cookies, or if cookies are disabled,
you can still enable session tracking using URL rewriting. URL rewriting essentially
includes the session ID within the link itself as a name/value pair. However, for this to
be effective, you need to append the session ID for each and every link that is part of
your servlet response. Adding the session ID to a link is greatly simplified by means of
of a couple of methods: response.encodeURL() associates a session ID with a given
URL, and if you are using redirection, response.encodeRedirectURL() can be used by
giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL()
first determine whether cookies are supported by the browser; if so, the input URL is
returned unchanged since the session ID will be persisted as a cookie.
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp,
interact with each other. Basically, we create a new session within hello1.jsp and place
an object within this session. The user can then traverse to hello2.jsp by clicking on
the link present within the page. Within hello2.jsp, we simply extract the object that
was earlier placed in the session and display its contents. Notice that we invoke the
encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are
disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to
still retrieve the session object. Try this example first with cookies enabled. Then
disable cookie support, restart the brower, and try again. Each time you should see the
maintenance of the session across pages. Do note that to get this example to work with
cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session=\"true\" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href=\'<%=url%>\'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%>
Q:What is the difference b/w variable declared inside a declaration part and
7
Q:Is there a way to execute a JSP from the comandline or from my own
application?
A:There is a little tool called JSPExecutor that allows you to do just that. The developers
(Hendrik Schreiber <[email protected]> & Peter Rossbach <[email protected]>) aim was
not to write a full blown servlet engine, but to provide means to use JSP for generating
source code or reports. Therefore most HTTP-specific features (headers, sessions, etc)
are not implemented, i.e. no reponseline or header is generated. Nevertheless you can
use it to precompile JSP for your website.
Set 2:
1. What are the implicit objects? - Implicit objects are objects that are
created by the web container and contain information related to a particular
request, page, or application. They are: request, response, pageContext, session,
application, out, config, page, exception.
2. Is JSP technology extensible? - Yes. JSP technology is extensible
through the development of custom actions, or tags, which are encapsulated in
tag libraries.
3. How can I implement a thread-safe JSP page? What are the
advantages and Disadvantages of using it? - 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. 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
4. How does JSP handle run-time exceptions? - You can use the errorPage
attribute of the page directive to have uncaught run-time exceptions
automatically forwarded to an error processing page. For example: <%@ page
8
errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is
encountered during request processing. Within error.jsp, if you indicate that it is
an error-processing page, via the directive: <%@ page isErrorPage="true" %>
Throwable object describing the exception may be accessed within the error
page via the exception implicit object. Note: You must always use a relative
URL as the value for the errorPage attribute.
5. 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
%>
6. How do I use comments within a JSP page? - You can use “JSP-style”
comments to selectively block out code while debugging or simply to comment
your scriptlets. JSP comments are not visible at the client. For example:
7. <%-- the scriptlet is now commented out
8. <%
9. out.println("Hello World");
10. %>
11. --%>
You can also use HTML-style comments anywhere within your JSP page. These
comments are visible at the client. For example:
Of course, you can also use comments supported by your JSP scripting language
within your scriptlets. For example, assuming Java is the scripting language, you
can have:
<%
//some comment
/**
9
**/
%>
12. Response has already been commited error. What does it mean? - This
error show only when you try to redirect a page after you already have written
something in your page. This happens because HTTP specification force the
header to be set up before the lay out of the page can be shown (to make sure of
how it should be displayed, content-type=”text/html” or “text/xml” or “plain-
text” or “image/jpg”, etc.) When you try to send a redirect status (Number is
line_status_402), your HTTP server cannot send it right now if it hasn’t finished
to set up the header. If not starter to set up the header, there are no problems, but
if it ’s already begin to set up the header, then your HTTP server expects these
headers to be finished setting up and it cannot be the case if the stream of the
page is not over… In this last case it’s like you have a file started with <HTML
Tag><Some Headers><Body>some output (like testing your variables.) Before
you indicate that the file is over (and before the size of the page can be setted up
in the header), you try to send a redirect status. It s simply impossible due to the
specification of HTTP 1.0 and 1.1
13. How do I use a scriptlet to initialize a newly instantiated bean? - A
jsp:useBean action may optionally have a body. If the body is specified, its
contents will be automatically invoked when the specified bean is instantiated.
Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the
newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to
the current date when it is instantiated. Note that here, we make use of a JSP
expression within the jsp:setProperty action.
14. <jsp:useBean id="foo" class="com.Bar.Foo" >
16. value="<%=java.text.DateFormat.getDateInstance().format(new
java.util.Date()) %>"/ >
19. How can I enable session tracking for JSP pages if the browser has
disabled cookies? - We know that session tracking uses cookies by default to
associate a session identifier with a unique user. If the browser does not support
cookies, or if cookies are disabled, you can still enable session tracking using
URL rewriting. URL rewriting essentially includes the session ID within the
link itself as a name/value pair. However, for this to be effective, you need to
append the session ID for each and every link that is part of your servlet
10
22. <%
24. session.putValue("num",num);
26. %>
28. hello2.jsp
30. <%
33. How can I declare methods within my JSP page? - You can declare
methods for use within your JSP page as declarations. The methods can then be
11
invoked within any other methods you declare, or within JSP scriptlets and
expressions. Do note that you do not have direct access to any of the JSP
implicit objects like request, response, session and so forth from within JSP
methods. However, you should be able to pass any of the implicit JSP variables
as parameters to the methods you declare. For example:
34. <%!
37. ...
39. }
40. %>
41. <%
42. out.print("Hi there, I see that you are coming in from ");
43. %>
46. file1.jsp:
48. <%!
50. writer.println("Hello!");
51. }
52. %>
53. file2.jsp
55. <html>
56. <body>
58. </body>
59. </html>
60. Is there a way I can set the inactivity lease period on a per-session basis? -
Typically, a default inactivity lease period for all sessions is set within your JSP
engine admin screen or associated properties file. However, if your JSP engine
supports the Servlet 2.1 API, you can manage the inactivity lease period on a
per-session basis. This is done by invoking the
HttpSession.setMaxInactiveInterval() method, right after the session has been
created. For example:
61. <%
62. session.setMaxInactiveInterval(300);
63. %>
would reset the inactivity period for this session to 5 minutes. The inactivity
interval is set in seconds.
64. How can I set a cookie and delete a cookie from within a JSP page? -
A cookie, mycookie, can be deleted using the following scriptlet:
65. <%
68. response.addCookie(mycookie);
71. killMyCookie.setMaxAge(0);
72. killMyCookie.setPath("/");
73. response.addCookie(killMyCookie);
74. %>
13
75. How does a servlet communicate with a JSP page? - The following
code snippet shows how a servlet instantiates a bean and initializes it with
FORM data posted by a browser. The bean is then placed into the request, and
the call is then forwarded to the JSP page, Bean1.jsp, by means of a request
dispatcher for downstream processing.
76. public void doPost (HttpServletRequest request,
HttpServletResponse response) {
77. try {
80. f.setName(request.getParameter("name"));
81. f.setAddr(request.getParameter("addr"));
82. f.setAge(request.getParameter("age"));
86. // . . .
87. f.setPersonalizationInfo(info);
88. request.setAttribute("fBean",f);
89.
getServletConfig().getServletContext().getRequestDispatcher
92. ...
93. }
94. }
The JSP page Bean1.jsp can then process fBean, after first extracting it from the
default request scope via the useBean action.
14
If any of the above conditions are not satisfied, the JSP engine may throw a
translation error.
Once the superclass has been developed, you can have your JSP extend it as
follows:
96. How can I prevent the word "null" from appearing in my HTML
input text fields when I populate them with a resultset that has null values?
- You could make a simple wrapper function, like
97. <%!
100. }
101. %>
104. How can I get to print the stacktrace for an exception occuring within
my JSP page? - By printing out the exception’s stack trace, you can usually
diagonse a problem better when debugging JSP pages. By looking at a stack
trace, a programmer should be able to discern which method threw the exception
and which method called that method. However, you cannot print the stacktrace
using the JSP out implicit variable, which is of type JspWriter. You will have to
use a PrintWriter object instead. The following snippet demonstrates how you
can print a stacktrace from within a JSP error page:
105. <%@ page isErrorPage="true" %>
106. <%
109. exception.printStackTrace(pw);
111. %>
114. <%!
121. System.out.println(name+"="+value);
122. }
123. }
124. %>
125. How can my JSP page communicate with an EJB Session Bean? - The
following is a code snippet that demonstrates how a JSP page can interact with
an EJB session bean:
126. <%@ page import="javax.naming.*,
javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
127. <%!
134. accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
135. }
136. %>
137. <%
141. acct.doWhatever(...);
143. %>
Set 3:
Then you are ready to use the tags you defined. Let's say the tag prefix is test:
MyJSPTag or
JavaBeans are Java utility classes you defined. Beans have a standard format for
Java classes. You use tags
to declare a bean and use
to set value of the bean class and use
to get value of the bean class.
Custom tags and beans accomplish the same goals — encapsulating complex
behavior into simple and accessible forms. There are several differences:
18
3. What are the two kinds of comments in JSP and what's the difference
between them.
<%– JSP Comment –%>
<!– HTML Comment –>
Java Server Page is a standard Java extension that is defined on top of the servlet
Extensions. The goal of JSP is the simplified creation and management of dynamic
Web pages. JSPs are secure, platform-independent, and best of all, make use of Java
as a server-side scripting language.
A JSP page is a text-based document that contains two types of text: static template
data, which can be expressed in any text-based format such as HTML, SVG, WML,
and XML, and JSP elements, which construct dynamic content.
Implicit objects are objects that are created by the web container and contain
information related to a particular request, page, or application. They are:
–request
–response
–pageContext
–session
–application
–out
–config
–page
–exception
8. Why are JSP pages the preferred API for creating a web-based client
program?
Because no plug-ins or security policy files are needed on the client systems(applet
does). Also, JSP pages enable cleaner and more module application design because
they provide a way to separate applications programming from web page design.
This means personnel involved in web page design do not need to understand Java
programming language syntax to do their jobs.
Yes , of course you can use the constructor instead of init(). There’s nothing to stop
you. But you shouldn’t. The original reason for init() was that ancient versions of
Java couldn’t dynamically invoke constructors with arguments, so there was no way
to give the constructur a ServletConfig. That no longer applies, but servlet containers
still will only call your no-arg constructor. So you won’t have access to a
ServletConfig or ServletContext.
11. How can a servlet refresh automatically if some new data has entered
the database?
12. The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.
13. How many messaging models do JMS provide for and what are they?
The Local Systems IP Address and Port Number. And the Remote System’s IPAddress
and Port Number.
SQLWarning objects are a subclass of SQLException that deal with database access
warnings. Warnings do not stop the execution of an application, as exceptions do;
they simply alert the user that something did not happen as planned. A warning can
be reported on a Connection object, a Statement object (including
PreparedStatement and CallableStatement objects), or a ResultSet object. Each of
these classes has a getWarnings method, which you must invoke in order to see the
first warning reported on the calling object
17. How many JSP scripting elements are there and what are they?
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.
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.
21
21. Why does JComponent have add() and remove() methods but
Component does not?
22. How can I enable session tracking for JSP pages if the browser has
disabled cookies?
Basically, we create a new session within hello1.jsp and place an object within this
session. The user can then traverse to hello2.jsp by clicking on the link present
within the page.Within hello2.jsp, we simply extract the object that was earlier
placed in the session and display its contents. Notice that we invoke the encodeURL()
within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the
session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve
the session object. Try this example first with cookies enabled. Then disable cookie
support, restart the brower, and try again. Each time you should see the
maintenance of the session across pages.
Do note that to get this example to work with cookies disabled at the browser, your
JSP engine has to support URL rewriting.
hello1.jsp
hello2.jsp
hello2.jsp
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());
Set 4:
1.What are the advantages of JSP over Servlet?
JSP is a serverside technology to make content generation a simple appear.The advantage of
JSP is that they are document-centric. Servlets, on the other hand, look and act like programs.
A Java Server Page can contain Java program fragments that instantiate and execute Java
classes, but these occur inside an HTML template file and are primarily used to generate
22
dynamic content. Some of the JSP functionality can be achieved on the client, using
JavaScript. The power of JSP is that it is server-based and provides a framework for Web
application development.
• Translation
• Compilation
• Loading the class
• Instantiating the class
• jspInit() invocation
• _jspService() invocation
• jspDestroy() invocation
More about JSP Life cycle
7.How can I override the jspInit() and jspDestroy() methods within a JSP page?
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a
JSP page and are typically declared as JSP declarations:
<%!
. . .
%>
<%!
. . .
%>
• request
• response
• pageContext
• session
• application
• out
• config
• page
• exception
The implicit objects are parsed by the container and inserted into the generated servlet code.
They are available only within the jspService method and not in any declaration.
• JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message
from a JSP page to the JSP container and control the processing of the entire page
• They are used to set global values such as a class declaration, method implementation,
output content type, etc.
• They do not produce any output to the client.
• Directives are always enclosed within <%@ ….. %> tag.
• Ex: page directive, include directive, etc.
• A page directive is to inform the JSP engine about the headers or facilities that page
should get from the environment.
• Typically, the page directive is found at the top of almost all of our JSP pages.
• There can be any number of page directives within a JSP page (although the attribute –
value pair must be unique).
• The syntax of the include directive is: <%@ page attribute="value">
• Example:<%@ include file="header.jsp" %>
There are thirteen attributes defined for a page directive of which the important attributes
are as follows:
• The include directive is used to statically insert the contents of a resource into the
current JSP.
• This enables a user to reuse the code without duplicating it, and includes the contents
of the specified file at the translation time.
• The syntax of the include directive is as follows:
<%@ include file = "FileName" %>
• This directive has only one attribute called file that specifies the name of the file to
be included.
• The JSP standard actions affect the overall runtime behavior of a JSP page and also the
response sent back to the client.
• They can be used to include a file at the request time, to find or instantiate a
JavaBean, to forward a request to a new page, to generate a browser-specific code,
etc.
• Ex: include, forward, useBean,etc. object
• <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.
• page scope:: It specifies that the object will be available for the entire JSP page but
not outside the page.
• request scope: It specifies that the object will be associated with a particular request
and exist as long as the request exists.
• application scope: It specifies that the object will be available throughout the entire
Web application but not outside the application.
• session scope: It specifies that the object will be available throughout the session with
a particular client.
• The <jsp:forward> standard action forwards a response from a servlet or a JSP page
to another page.
• The execution of the current page is stopped and control is transferred to the
forwarded page.
• The syntax of the <jsp:forward> standard action is :
<jsp:forward page="/targetPage" />
Here, targetPage can be a JSP page, an HTML page, or a servlet within the same
context.
• If anything is written to the output stream that is not buffered before <jsp:forward>,
an IllegalStateException will be thrown.
insert the contents of a resource into the current JSP page to include a static or a
current JSP. dynamic resource at runtime.
Use the include action only for content that
Use the include directive if the file changes changes often, and if which page to include
rarely. It’s the fastest mechanism. cannot be decided until the main page is
requested.
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated
or an existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean
element, as below:
<jsp:useBean id="myName" ... >
...
<jsp:setProperty name="myName"
property="someProperty" ... />
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing
one was found.
Here, name is the id of the bean from which the property was set. The property attribute is
the property to get. A user must create or locate a bean using the <jsp:useBean> action before
using the <jsp:getProperty> action.
1. Expressions of the form <%= expression %> that are evaluated and inserted into the
output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method,
3. Declarations of the form <%! code %> that are inserted into the body of the servlet
class, outside of any existing methods.
27.What is a scriptlet?
A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is
translated to a servlet, the scriptlet code goes into the service() method. Hence, methods
and variables written in scriptlets are local to the service() method. A scriptlet is written
between the <% and %> tags and is executed by the container at request processing time.
</jsp-property-group>
Set 5:
#1. What is JSP?
Ans:- JSP Stands for Java server pages. JSP is Java technology which is used by
developers across the world to create dynamically generated websites with the easy use of
other documents like HTML, XML. This technology of java allows developers to include java
code and some pre defined actions into static content. Java server pages are compiled into
java servlet by the java compiler or the java compiler may directly generate the byte code for
the servlet.
>
#2. How servlet differ from JSP?
Ans:- Both Servlet and Java Server Pages are API which generate dynamic web content. A
servlet is nothing but a java class which implements the interface to run within a web and on
the other hand Java server pages is a bit complicated thing which contain a mixture of Java
scripts, Java directives, Java elements and HTML. The main difference among both servlet
and Java server pages is that JSP is document oriented and servlet on the other hand act
likes a program.
>
#3. What are the advantages of JSP?
Ans:- There are many advantages of JSP and JSP is very much preferred by every coder.
The main advantage of JSP over anything is its auto compilation and the length of code is
reduced by using custom tags and tag library. Secondly, it is portable that is it works on all
operating system and non – Microsoft web servers. Java components can be easily
embedded into the dynamic pages. JSP have all the features of java and can easily separate
dynamic part from the static part of the page.
>
#4. What are the implicit objects in JSP?
Ans:- There are all total 9 implicit objects in JSP. Application interface refers to the web
application’s interface whereas Session interface refers to the user’s session. Request
interface refers to the page which is currently requested whereas Response interface refers
to the response which is currently made by the user. Config interface refers to the servlet
30
configuration. Class like out, page, page Context and exception refers to the output stream
of the page, servlet instance of the page, environment of the page, error handling
respectively.
>
#5. How JSP calls a stored procedure?
Ans:- Java Server Pages possess all the characteristics of java and to call and have similar
syntax to call a function. Functions and stored procedures of a database can be called by
using the statement callable. Another way to call the stored procedure is by writing the JDBC
code in between the tag of scriptlet tab.write.
>
#6. How to override the lifecycle methods of JSP?
Ans:- Lifecycle method jspService() cannot be overridden within a JSP page however
methods like jspInit() and jspDestroy() can be overridden within a JSP page. Method jspInit()
is used for allocating resource while method jspDestroy() is used to free allocated resource.
But it should be kept in mind that during the lifecycle of a Java Server Page both the method
jsplnit() and jspDestroy() is executed once and are declared as JSP declarations.
>
#7. What is declaration in JSP?
Ans:- In Java Server pages Declaration is used to declare and define variables and methods
that can be used in the Java Server Pages. The variable which is declared is initialized once
and it retain its value for every subsequent client request.
>
#8. How a run - time application is handled in JSP?
Ans:- In JSP the errorpage attribute of the page is used as a directive to have uncaught run –
time exceptions and which is automatically forwarded to an page which processes the
error. If an uncaught exception is encountered while processing the request, then the
browser redirects to the JSP error page.
31
>
#9. State the difference between the expression and scriptlet?
Ans:- JSP, Expressions is used to display the values of variable or to return the values by
invoking the getter methods. However, JSP expressions begins with <> and does not have
semicolon at the end of the expression. Scriptlet can contain variable, method or
expressions that are valid within the page scripting language. Within the scripting tags and
page scripting language any valid operations can be performed.
>
#10. Outline the difference between Java server page forward and servlet forward
method?
The only minor difference between both the methods is that Java Server page forward
method can’t forward to another JSP page in another web application or container whereas
servlet forward method can do so.
>
#11. What are custom tags and why it is needed?
JSP tags are extended by creating a custom set of tags which is called as tag library (taglib).
The page which uses custom tags declares taglib and uniquely names, defines and
associates a tag prefix to differentiate the usage of those tags.
>
#12. How cookies is deleted in JSP?
There are two ways by which the cookies can be deleted in JSP. Firstly, by setting the
setMaxAge() of the cookie class to zero. And secondly by setting a timer in the header file
that is response. setHeader(expires {Mention the time} attribute), which will delete the
cookies after that prescribed time.
>
#13. Is it possible by a JSP page to process HTML form data?
32
Yes it is possible by simply obtaining the data from the FORM input via the request implicit
object which lies with a scriptlet or expression but it doesn't require to implement any HTTP –
Protocol methods like goGet() or doPost() within the JSP page.
>
#14. How method is declared within JSP page?
Methods can be declared for use within JSP page as declaration and this method can be
invoked within any other method which is declared or within JSP scriptlets or expressions.
Direct access to the JSP implicit objects like request, response, session etc is forbidden
within JSP methods but implicit Java server page variable is allowed to pass as parameters
to the method which is declared.
>
#15. Outline the major difference between the session and cookie?
Sessions are always stored in the server side whereas cookies are always stored in the
client side.
Set 6:
<%=identifier.getclassField() %>
Custom tags and beans accomplish the same goals -- encapsulating complex
behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot.
Complex operations can be reduced to a significantly simpler form with custom
tags than with beans. Custom tags require quite a bit more work to set up than
do beans.
Custom tags usually define relatively self-contained behavior, whereas beans are
often defined in one servlet and used in a different servlet or JSP page.
Custom tags are available only in JSP 1.1 and later, but beans can be used in all
JSP 1.x versions.
What are the two kinds of comments in JSP and what's the difference
between them ?
<%-- JSP Comment --%>
<!-- HTML Comment -->
Java Server Page is a standard Java extension that is defined on top of the servlet
Extensions. The goal of JSP is the simplified creation and management of
dynamic Web pages. JSPs are secure, platform-independent, and best of all,
make use of Java as a server-side scripting language.
Why are JSP pages the preferred API for creating a web-based client
program?
Because no plug-ins or security policy files are needed on the client
systems(applet does). Also, JSP pages enable cleaner and more module
application design because they provide a way to separate applications
programming from web page design. This means personnel involved in web page
design do not need to understand Java programming language syntax to do their
jobs.
How can a servlet refresh automatically if some new data has entered the
database?
You can use a client-side Refresh or Server Push.
How many messaging models do JMS provide for and what are they?
JMS provide for two messaging models, publish-and-subscribe and point-to-point
queuing.
if (warning != null)
{
while (warning != null)
{
System.out.println(\"Message: \" + warning.getMessage());
System.out.println(\"SQLState: \" + warning.getSQLState());
System.out.print(\"Vendor error code: \");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
How many JSP scripting elements are there and what are they?
There are three scripting language elements: declarations, scriptlets,
expressions.
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.
Why does JComponent have add() and remove() methods but Component
does not?
because JComponent is a subclass of Container, and can contain other
components and jcomponents. How can I implement a thread-safe JSP page? -
You can make your JSPs thread-safe by having them implement the
36
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.
How can I enable session tracking for JSP pages if the browser has disabled
cookies?
We know that session tracking uses cookies by default to associate a session
identifier with a unique user. If the browser does not support cookies, or if
cookies are disabled, you can still enable session tracking using URL rewriting.
URL rewriting essentially includes the session ID within the link itself as a
name/value pair.
However, for this to be effective, you need to append the session ID for each and
every link that is part of your servlet response. Adding the session ID to a link is
greatly simplified by means of of a couple of methods: response.encodeURL()
associates a session ID with a given URL, and if you are using redirection,
response.encodeRedirectURL() can be used by giving the redirected URL as
input.
Both encodeURL() and encodeRedirectedURL() first determine whether cookies
are supported by the browser; if so, the input URL is returned unchanged since
the session ID will be persisted as a cookie. Consider the following example, in
which two JSP files, say hello1.jsp and hello2.jsp, interact with each other.
Basically, we create a new session within hello1.jsp and place an object within
this session. The user can then traverse to hello2.jsp by clicking on the link
present within the page.Within hello2.jsp, we simply extract the object that was
earlier placed in the session and display its contents. Notice that we invoke the
encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are
disabled, the session ID is automatically appended to the URL, allowing hello2.jsp
to still retrieve the session object. Try this example first with cookies enabled.
Then disable cookie support, restart the brower, and try again. Each time you
should see the maintenance of the session across pages.
Do note that to get this example to work with cookies disabled at the browser,
your JSP engine has to support URL rewriting.
hello1.jsp
hello2.jsp
hello2.jsp
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());
37
Is there a way I can set the inactivity lease period on a per-session basis?
Typically, a default inactivity lease period for all sessions is set within your
39
JSPengine admin screen or associated properties file. However, if your JSP engine
supports the Servlet 2.1 API, you can manage the inactivity lease period on a
per-session basis.
This is done by invoking the HttpSession.setMaxInactiveInterval() method, right
after the session has been created.
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
...
}
}
Can you make use of a ServletOutputStream object from within a JSP page?
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:
40
What is JSP?
Let's consider the answer to that from two different perspectives: that of an
HTML designer and that of a Java programmer.
If you are an HTML designer, you can look at JSP technology as extending HTML
to provide you with the ability to seamlessly embed snippets of Java code within
your HTML pages. These bits of Java code generate dynamic content, which is
embedded within the other HTML/XML content you author. Even better, JSP
technology provides the means by which programmers can create new
HTML/XML tags and JavaBeans components, which provide new features for
HTML designers without those designers needing to learn how to program.
Note: A common misconception is that Java code embedded in a JSP page is
transmitted with the HTML and executed by the user agent (such as a browser).
This is not the case. A JSP page is translated into a Java servlet and executed on
the server. JSP statements embedded in the JSP page become part of the servlet
generated from the JSP page. The resulting servlet is executed on the server. It is
never visible to the user agent.
If you are a Java programmer, you can look at JSP technology as a new, higher-
level means to writing servlets. Instead of directly writing servlet classes and
41
then emitting HTML from your servlets, you write HTML pages with Java code
embedded in them. The JSP environment takes your page and dynamically
compiles it. Whenever a user agent requests that page from the Web server, the
servlet that was generated from your JSP code is executed, and the results are
returned to the user.
How do I mix JSP and SSI #include? What is the difference between include
directive & jsp:include action?
Difference between include directive and
1. provides the benefits of automatic recompliation,smaller class size ,since the
code corresponding to the included page is not present in the servlet for every
included jsp page and option of specifying the additional request parameter.
2.The also supports the use of request time attributes values for dynamically
specifying included page which directive does not.
3.the include directive can only incorporate contents from a static document.
4. can be used to include dynamically generated output e.g.. from servlets.
5.include directive offers the option of sharing local variables, better run time
efficiency.
6.Because the include directive is processed during translation and compilation,
it does not impose any restrictions on output buffering.
How do you prevent the Creation of a Session in a JSP Page and why? What
is the difference between include directive & jsp:include action?
By default, a JSP page will automatically create a session for the request if one
does not exist.
However, sessions consume resources and if it is not necessary to maintain a
session, one should not be created. For example, a marketing campaign may
suggest the reader visit a web page for more information. If it is anticipated that
a lot of traffic will hit that page, you may want to optimize the load on the
machine by not creating useless sessions.
newly instantiated bean, although you are not restricted to using those alone.
The following example shows the "today" property of the Foo bean initialized to
the current date when it is instantiated. Note that here, we make use of a JSP
expression within the jsp:setProperty action.
value=""/ >
How can I set a cookie and delete a cookie from within a JSP page?
A cookie, mycookie, can be deleted using the following scriptlet:
What is the page directive is used to prevent a JSP page from automatically
creating a session?
<%@ page session="false">
Why is _jspService() method starting with an '_' while other life cycle
methods do not?
_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.
A JSP page, include.jsp, has a instance variable "int a", now this page is
statically included in another JSP page, index.jsp, which has a instance
variable "int a" declared. What happens when the index.jsp page is
requested by the client?
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.
How many JSP scripting elements are there and what are they?
There are three scripting language elements: declarations, scriptlets,
expressions.
How can a servlet refresh automatically if some new data has entered the
database?
You can use a client-side Refresh or Server Push.
How many messaging models do JMS provide for and what are they?
JMS provide for two messaging models, publish-and-subscribe and point-to-point
queuing.
Set 7:
45
Question: What is the difference between <jsp:include page = ... > and
<%@ include file = ... >?.
Answer: Both the tag includes the information from one page in another. The differences
are as follows:
<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
to for modularizing the web application. If the included file changed
then the new content will be included in the output.
<%@ 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 in the included file changes, the changed
content will not included in the output. This approach is used when the
code from one jsp file required to include in multiple jsp files.
Question: What is the difference between <jsp:forward page = ... > and
response.sendRedirect(url),?.
Answer: 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. The response.sendRedirect kills the
session variables.
<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%
%>
</BODY>
</HTML>
Suppose you access this JSP file, Find out your answer.
a) A blank page will be displayed.
b) A page with the text Welcome is displayed
c) An exception will be thrown because the implicit out object is not used
d) An exception will be thrown because PrintWriter can be used in servlets only
Question: What are all the different scope values for the <jsp:useBean> tag?
Answer:<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
Set 8:
What is Java Server Pages technology?
JavaServer Pages (JSP) technology offers a simple way to create dynamic web pages that
are both platform-independent and server-independent, giving you more freedom through
Java technology's "Write Once, Run Anywhere" capability.
expressed in any text-based format (such as HTML,XML,etc), and JSP elements, which
construct dynamic content.JSP is a technology that lets you mix static content with
dynamically generated content.
Does JSP technology require the use of other Java platform APIs?
JSP pages are typically compiled into Java platform servlet classes. As a result, JSP pages
require a Java virtual machine that supports the Java platform servlet specification.
• JSP pages easily combine static templates, including HTML or XML fragments, with
• 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.
• JSP tags for invoking JavaBeans components manage these components completely,
• Developers can offer customized JSP tag libraries that page authors access using an
XML-like syntax.
• 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.
50
^Back to top
51
^Back to top
JSP Action:
• JSP actions are XML tags that direct the server to use existing components or
control the behavior of the JSP engine.
• Consist of typical (XML-base) prefix of ‘jsp’ followed by a colon, followed by
the action name followed by one or more attribute parameters. For example:
There are six JSP Actions: <jsp:include/>, <jsp:forward/>,
<jsp:plugin/>, <jsp:usebean/>, <jsp:setProperty/>,
<jsp:getProperty/>
Both the tag includes the information from one page in another. The differences are as
follows: <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 to for modularizing the web application. If the included file
changed then the new content will be included in the output.
<%@ 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 in the
included file changes, the changed content will not included in the output. This approach
is used when the code from one jsp file required to include in multiple jsp files.
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
53
http://www.roseindia.net/interviewquestions/jsp-interview-questions.shtml
‘errorPage’ attribute of the page directive can be used to catch runtime exceptions
automatically and then forwarded to an error processing page. For example: <%@ page
errorPae=”dbaccessError.jsp” %> forwards request to dbaccessError.jsp pge if an
uncaught exception is encountered during request processing. Within
“dbaccessError.jsp”, you must indicate that it is an error processing page, via the
directive: <%@ page isErrorPage=”true” %>.
How can you enable session tracking for JSP pages if the browser has disabled
cookies: We can enable session tracking using URL rewriting. URL rewriting includes
the sessionID within the link itself as a name/value pair. However, for this to be effective,
you need to append the session Id for each and every link that is part of your servlet
response. adding sessionId to a link is greatly simplified by means of a couple of
methods: response.ecnodeURL() associates a session ID with a giver UIRl, and if you are
using redirection, response.encodeRedirectURL() can be used by giving the redirected
URL as input. Both encodeURL() and encodeRedirectURL() first determine whether
cookies are supported by the browser; is so, the input URL is returned unchanged since
the session ID wil lbe persisted as cookie.
How do I prevent the output of my JSP or servlet pages from being caches by the
browser?
Set the appropriate HTTP header attributes to prevent the dynamic content output by the
JSP page from being cached by the browser. Execute the following scriptlet at the
beginning of JSP pages to prevent them from being caches at the browser.
<%
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
%>