Sie sind auf Seite 1von 54

1

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() %>
-->

Displays in the page source:


<!-- This is a commnet sent to client on January 24, 2004 -->
TOP

Q:What is a Hidden Comment?


A:A comments that documents the JSP page but is not sent to the client. The JSP engine
ignores a hidden comment, and does not process any code within hidden comment
tags. A hidden comment is not sent to the client, either in the displayed JSP page or the
HTML page source. The hidden comment is useful when you want to hide or
"comment out" part of your JSP page.

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.

<%! somedeclarations %>


<%! int i = 0; %>
<%! int a, b, c; %>
TOP

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

Q:What are implicit objects? List them?


A: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 re listed below
• request
• response
• pageContext
• session
3

• application
• out
• config
• page

• exception
TOP

Q:Difference between forward and sendRedirect?


A: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.
TOP

Q:What are the different scope valiues for the <jsp:useBean>?


A:The different scope values for <jsp:useBean> are

1. page
2. request
3.session
4.application
TOP

Q:Explain the life-cycle mehtods in JSP?


A:THe generated servlet class for a JSP page implements the HttpJspPage interface of
the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface
which inturn extends the Servlet interface of the javax.servlet package. the generated
servlet class thus implements all the methods of the these three interfaces. The JspPage
interface declares only two mehtods - jspInit() and jspDestroy() that must be
implemented by all JSP pages regardless of the client-server protocol. However the
JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages
serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called
before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the
request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of
service. It is the last method called n the servlet instance.
Q:How do I prevent the output of my JSP or Servlet pages from being cached by the
browser?
A: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
4

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
%>

[ Received from Sumit Dhamija ] TOP

Q:How does JSP handle run-time exceptions?


A: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 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.
[ Received from Sumit Dhamija ] TOP

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

Q:How do I use a scriptlet to initialize a newly instantiated bean?


A: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.
5

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 id="foo" class="com.Bar.Foo" >

<jsp:setProperty name="foo" property="today"


value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date())
%>" / >

<%-- scriptlets calling bean setter methods go here --%>

</jsp:useBean >

[ Received from Sumit Dhamija ] TOP

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;
}
%>

then use it inside your JSP form, like

<input type="text" name="lastName" value="<%=blanknull(lastName)% >" >

[ Received from Sumit Dhamija ] TOP

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
6

and increased the size of the instance pool.

[ Received from Sumit Dhamija ] TOP

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

variable declared in scriplet part?


A:Variable declared inside declaration part is treated as a global variable.that means after
convertion jsp file into servlet that variable will be in outside of service method or it
will be declared as instance variable.And the scope is available to complete jsp and to
complete in the converted servlet class.where as if u declare a variable inside a scriplet
that variable will be declared inside a service method and the scope is with in the
service method.
[ Received from Neelam Gangadhar] TOP

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 <hs@webapp.de> & Peter Rossbach <pr@webapp.de>) 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:

<!-- (c) 2004 -->

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

yet another comment

**/

%>

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" >

15. <jsp:setProperty name="foo" property="today"

16. value="<%=java.text.DateFormat.getDateInstance().format(new
java.util.Date()) %>"/ >

17. <%-- scriptlets calling bean setter methods go here --%>

18. </jsp:useBean >

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

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.
20. hello1.jsp

21. <%@ page session="true" %>

22. <%

23. Integer num = new Integer(100);

24. session.putValue("num",num);

25. String url =response.encodeURL("hello2.jsp");

26. %>

27. <a href='<%=url%>'>hello2.jsp</a>

28. hello2.jsp

29. <%@ page session="true" %>

30. <%

31. Integer i= (Integer )session.getValue("num");

32. out.println("Num value in session is "+i.intValue());

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. <%!

35. public String whereFrom(HttpServletRequest req) {

36. HttpSession ses = req.getSession();

37. ...

38. return req.getRemoteHost();

39. }

40. %>

41. <%

42. out.print("Hi there, I see that you are coming in from ");

43. %>

44. <%= whereFrom(request) %>

45. Another Example

46. file1.jsp:

47. <%@page contentType="text/html"%>

48. <%!

49. public void test(JspWriter writer) throws IOException{

50. writer.println("Hello!");

51. }

52. %>

53. file2.jsp

54. <%@include file="file1.jsp"%>


12

55. <html>

56. <body>

57. <%test(out);% >

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. <%

66. //creating a cookie

67. Cookie mycookie = new Cookie("aName","aValue");

68. response.addCookie(mycookie);

69. //delete a cookie

70. Cookie killMyCookie = new Cookie("mycookie", null);

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 {

78. govi.FormBean f = new govi.FormBean();

79. String id = request.getParameter("id");

80. f.setName(request.getParameter("name"));

81. f.setAddr(request.getParameter("addr"));

82. f.setAge(request.getParameter("age"));

83. //use the id to compute

84. //additional bean properties like info

85. //maybe perform a db query, etc.

86. // . . .

87. f.setPersonalizationInfo(info);

88. request.setAttribute("fBean",f);

89.
getServletConfig().getServletContext().getRequestDispatcher

90. ("/jsp/Bean1.jsp").forward(request, response);

91. } catch (Exception ex) {

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

jsp:useBean id="fBean" class="govi.FormBean" scope="request"

/ jsp:getProperty name="fBean" property="name"

/ jsp:getProperty name="fBean" property="addr"

/ jsp:getProperty name="fBean" property="age"

/ jsp:getProperty name="fBean" property="personalizationInfo" /

95. How do I have the JSP-generated servlet subclass my own custom


servlet class, instead of the default? - One should be very careful when having
JSP pages extend custom servlet classes as opposed to the default one generated
by the JSP engine. In doing so, you may lose out on any advanced optimization
that may be provided by the JSP engine. In any case, your new superclass has to
fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or
implementing JspPage otherwise Ensuring that all the methods in the Servlet
interface are declared final Additionally, your servlet superclass also needs to do
the following:
 The service() method has to invoke the _jspService() method
 The init() method has to invoke the jspInit() method
 The destroy() method has to invoke jspDestroy()

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:

<%@ page extends="packageName.ServletName" %>

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. <%!

98. String blanknull(String s) {

99. return (s == null) ? "" : s;

100. }

101. %>

102. then use it inside your JSP form, like


15

103. <input type="text" name="shoesize" value="<


%=blanknull(shoesize)% >" >

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. <%

107. out.println(" ");

108. PrintWriter pw = response.getWriter();

109. exception.printStackTrace(pw);

110. out.println(" ");

111. %>

112. How do you pass an InitParameter to a JSP? - The JspPage interface


defines the jspInit() and jspDestroy() method which the page writer can use in
their pages and are invoked in much the same manner as the init() and destory()
methods of a servlet. The example page below enumerates through all the
parameters and prints them to the console.
113. <%@ page import="java.util.*" %>

114. <%!

115. ServletConfig cfg =null;

116. public void jspInit(){

117. ServletConfig cfg=getServletConfig();

118. for (Enumeration e=cfg.getInitParameterNames();


e.hasMoreElements();) {

119. String name=(String)e.nextElement();

120. String value = cfg.getInitParameter(name);


16

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. <%!

128. //declare a "global" reference to an instance of the home


interface of the session bean

129. AccountHome accHome=null;

130. public void jspInit() {

131. //obtain an instance of the home interface

132. InitialContext cntxt = new InitialContext( );

133. Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");

134. accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);

135. }

136. %>

137. <%

138. //instantiate the session bean

139. Account acct = accHome.create();

140. //invoke the remote methods

141. acct.doWhatever(...);

142. // etc etc...


17

143. %>

Set 3:

1. What is a JSP and what is it used for?


Java Server Pages (JSP) is a platform independent presentation layer technology that
comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces
embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the
background to generate a Servlet from the JSP page.

2. What is difference between custom JSP tags and beans?


Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body
are interpreted, and then group your tags into collections called tag libraries that can
be used in any number of JSP files. To use custom JSP tags, you need to define three
separate components:

1. The tag handler class that defines the tag\'s behavior


2. The tag library descriptor file that maps the XML element names to the tag
implementations
3. the JSP file that uses the tag library
When the first two components are done, you can use the tag by using taglib
directive:

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

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.

3. What are the two kinds of comments in JSP and what's the difference
between them.
<%– JSP Comment –%>
<!– HTML Comment –>

4. What is JSP technology?

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.

5. What is JSP page?

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.

6. 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

7. How many JSP scripting elements and what are they?

There are three scripting language elements:


–declarations
–scriptlets
–expressions
19

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.

9. Is JSP technology extensible?

YES. JSP technology is extensible through the development of custom actions, or


tags, which are encapsulated in tag libraries.

10. Can we use the constructor, instead of init(), to initialize servlet?

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?

You can use a client-side Refresh or Server Push.

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?

JMS provide for two messaging models, publish-and-subscribe and point-to-point


queuing.

14. What information is needed to create a TCP Socket?

The Local Systems IP Address and Port Number. And the Remote System’s IPAddress
and Port Number.

15. What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager.


When you have loaded a driver, it is available for making a connection with a DBMS.

16. How to Retrieve Warnings?


20

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

SQLWarning warning = stmt.getWarnings();


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();
}
}

17. How many JSP scripting elements are there and what are they?

There are three scripting language elements: declarations, scriptlets, expressions.

18. In the Servlet 2.4 specification SingleThreadModel has been deprecated,


why?

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.

19. What are stored procedures? How is it useful?

A stored procedure is a set of statements/commands which reside in the database.


The stored procedure is pre-compiled and saves the database the effort of parsing
and compiling sql statements everytime a query is run. Each database has its own
stored procedure language, usually a variant of C with a SQL preproceesor. Newer
versions of db’s support writing stored procedures in Java and Perl too. Before the
advent of 3-tier/n-tier architecture it was pretty common for stored procs to
implement the business logic( A lot of systems still do it). The biggest advantage is
of course speed. Also certain kind of data manipulations are not achieved in SQL.
Stored procs provide a mechanism to do these manipulations. Stored procs are also
useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the
db. The overhead of a JDBC Connection may be significant in these cases.

20. How do I include static files within a JSP page?

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?

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 SingleThreadModel interface.
This is done by adding the directive <%@ page isThreadSafe="false" % > within
your JSP page.

22. 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());

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.

2.What is the life-cycle of JSP?


When a request is mapped to a JSP page for the first time, it translates the JSP page into a
servlet class and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:

• Translation
• Compilation
• Loading the class
• Instantiating the class
• jspInit() invocation
• _jspService() invocation
• jspDestroy() invocation
More about JSP Life cycle

3.What is the jspInit() method?


The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method
of servlets. This method is invoked by the container only once when a JSP page is initialized. It
can be overridden by a page author to initialize resources such as database and network
connections, and to allow a JSP page to read persistent configuration data.

4.What is the _jspService() method?


SThe _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time
a new request comes to a JSP page. This method takes the HttpServletRequest and
HttpServletResponse objects as its arguments. A page author cannot override this method, as
its implementation is provided by the container.

5.What is the jspDestroy() method?


The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container
when a JSP page is about to be destroyed. This method is similar to the destroy() method of
servlets. It can be overridden by a page author to perform any cleanup operation such as
closing a database connection.

6.What JSP lifecycle methods can I override?


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().

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:
<%!

public void jspInit() {


23

. . .

%>

<%!

public void jspDestroy() {

. . .

%>

8.What are implicit objects in JSP?


Implicit objects in JSP are the Java objects that the JSP Container makes available to
developers in each page. These objects need not be declared or instantiated by the JSP author.
They are automatically instantiated by the container and are accessed using standard
variables; hence, they are called implicit objects.The implicit objects available in JSP are as
follows:

• 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.

Check more about implicit objects

9.What are the different types of JSP tags?


The different types of JSP tags are as follows:
24

10.What are JSP directives?

• 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.

11.What is page directive?

• 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" %>

12.What are the attributes of page directive?


25

There are thirteen attributes defined for a page directive of which the important attributes
are as follows:

• import: It specifies the packages that are to be imported.


• session: It specifies whether a session data is available to the JSP page.
• contentType: It allows a user to set the content-type for a page.
• isELIgnored: It specifies whether the EL expressions are ignored when a JSP is
translated to a servlet.

13.What is the include directive?


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.

14.What are the JSP standard actions?

• 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

15.What are the standard actions available in JSP?


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.

16.What is the <jsp:useBean> standard action?


26

The <jsp:useBean> standard action is used to locate an existing JavaBean or to create a


JavaBean if it does not exist. It has attributes to identify the object instance, to specify the
lifetime of the bean, and to specify the fully qualified classpath and type.

17.What are the scopes available in <jsp:useBean>?


The scopes available in <jsp:useBean> are as follows:

• 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.

18.What is the <jsp:forward> standard action?

• 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.

Note : Whenever we intend to use <jsp:forward> or <jsp:include> in a page, buffering should


be enabled. By default buffer is enabled.

19.What is the <jsp:include> standard action?


The <jsp:include> standard action enables the current JSP page to include a static or a dynamic
resource at runtime. In contrast to the include directive, the include action is used for
resources that change frequently. The resource to be included must be in the same
context.The syntax of the <jsp:include> standard action is as follows:
<jsp:include page="targetPage" flush="true"/>
Here, targetPage is the page to be included in the current JSP.

20.What is the difference between include directive and include action?


Include directive Include action
The include action, includes the response
The include directive, includes the content
generated by executing the specified page (a
of the specified file during the translation
JSP page or a servlet) during the request
phase–when the page is converted to a
processing phase–when the page is requested
servlet.
by a user.
The include directive is used to statically The include standard action enables the
27

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.

21.Differentiate between pageContext.include and jsp:include?


The <jsp:include> standard action and the pageContext.include() method are both used to
include resources at runtime. However, the pageContext.include() method always flushes
the output of the current page before including the other components, whereas
<jsp:include> flushes the output of the current page only if the value of flush is explicitly set
to true as follows:
<jsp:include page="/index.jsp" flush="true"/>

22.What is the jsp:setProperty action?


You use jsp:setProperty to give values to properties of beans that have been referenced
earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside
of, a jsp:useBean element, as below:
<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName" property="myProperty" ... />

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.

23.What is the jsp:getProperty action?


The <jsp:getProperty> action is used to access the properties of a bean that was set using the
<jsp:getProperty> action. The container converts the property to a String as follows:

• If it is an object, it uses the toString() method to convert it to a String.


• If it is a primitive, it converts it directly to a String using the valueOf() method of the
corresponding Wrapper class.
• The syntax of the <jsp:getProperty> method is: <jsp:getProperty name="Name"
property="Property" />
28

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.

24.What is the <jsp:param> standard action?


The <jsp:param> standard action is used with <jsp:include> or <jsp:forward> to pass parameter
names and values to the target resource. The syntax of the <jsp:param> standard action is as
follows:
<jsp:param name="paramName" value="paramValue"/>

25.What is the jsp:plugin action ?


This action lets you insert the browser-specific OBJECT or EMBED element needed to specify
that the browser run an applet using the Java plugin.

26.What are scripting elements?


JSP scripting elements let you insert Java code into the servlet that will be generated from the
current JSP page. There are three forms:

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.

28.What are JSP declarations?


As the name implies, JSP declarations are used to declare class variables and methods in a JSP
page. They are initialized when the class is initialized. Anything defined in a declaration is
available for the whole JSP page. A declaration block is enclosed between the <%! and %>
tags. A declaration is not included in the service() method when a JSP is translated to a
servlet.

29.What is a JSP expression?


A JSP expression is used to write an output without using the out.print statement. It can be
said as a shorthand representation for scriptlets. An expression is written between the <%= and
%> tags. It is not required to end the expression with a semicolon, as it implicitly adds a
semicolon to all the expressions within the expression tags.

30.How is scripting disabled?


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>
29

</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:

What is a JSP and what is it used for?


Java Server Pages (JSP) is a platform independent presentation layer technology
that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code
pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is
used in the background to generate a Servlet from the JSP page.

What is difference between custom JSP tags and beans?


Custom JSP tag is a tag you defined. You define how a tag, its attributes and its
body are interpreted, and then group your tags into collections called tag
libraries that can be used in any number of JSP files. To use custom JSP tags, you
need to define three separate components:
1. the tag handler class that defines the tag\'s behavior
2. the tag library descriptor file that maps the XML element names to the tag
implementations
3. the JSP file that uses the tag library
When the first two components are done, you can use the tag by using taglib
directive:
<%@ taglib uri="xxx.tld" prefix="..." %>
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.
33

<%=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 -->

What is JSP technology?

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.

What is JSP page?


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.

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

How many JSP scripting elements and what are they?


There are three scripting language elements:
--declarations
--scriptlets
--expressions
34

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.

Is JSP technology extensible?


YES. JSP technology is extensible through the development of custom actions, or
tags, which are encapsulated in tag libraries.

Can we use the constructor, instead of init(), to initialize servlet?


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.

How can a servlet refresh automatically if some new data has entered the
database?
You can use a client-side Refresh or Server Push.

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.

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.

What information is needed to create a TCP Socket?


The Local Systems IP Address and Port Number. And the Remote System’s
IPAddress and Port Number.

What Class.forName will do while loading drivers?


It is used to create an instance of a driver and register it with the DriverManager.
When you have loaded a driver, it is available for making a connection with a
DBMS.

How to Retrieve Warnings?


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

SQLWarning warning = stmt.getWarnings();


35

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.

In the Servlet 2.4 specification SingleThreadModel has been deprecated,


why?

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.

What are stored procedures? How is it useful?


A stored procedure is a set of statements/commands which reside in the
database. The stored procedure is pre-compiled and saves the database the
effort of parsing and compiling sql statements every time a query is run. Each
database has its own stored procedure language, usually a variant of C with a
SQL preproceesor. Newer versions of db’s support writing stored procedures in
Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty
common for stored procs to implement the business logic( A lot of systems still
do it). The biggest advantage is of course speed. Also certain kind of data
manipulations are not achieved in SQL. Stored procs provide a mechanism to do
these manipulations. Stored procs are also useful when you want to do Batch
updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC
Connection may be significant in these cases.

How do I include static files within a JSP page?


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.

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

SingleThreadModel interface. This is done by adding the directive <%@ page


isThreadSafe="false" % > within your JSP page.

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 do you restrict page errors display in the JSP page?


You first set "Errorpage" attribute of PAGE directory to the name of the error
page (ie Errorpage="error.jsp")in your jsp page .Then in the error jsp page set
"isErrorpage=TRUE". When an error occur in your jsp page it will automatically
call the error page.

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

What JSP lifecycle methods can I override?


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:

How do I perform browser redirection from a JSP page?


You can use the response implicit object to redirect the browser to a different
resource, as:
response.sendRedirect("http://www.exforsys.com/path/error.html");
You can also physically alter the Location HTTP header attribute, as shown below:
You can also use the:
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 >

How does JSP handle run-time exceptions?


You can use the errorPage attribute of the page directive to have uncaught
runtime exceptions automatically forwarded to an error processing page.
For example:
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:
the 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.

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:
--%>
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.

Is it possible to share an HttpSession between a JSP and EJB? What


happens when I change a value in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method, only if all objects
in session are serializable. This has to be consider as "passed-by-value", that
means that it's read-only in the EJB.
If anything is altered from inside the EJB, it won't be reflected back to the
HttpSession of the Servlet Container.The "pass-byreference" can be used
between EJBs Remote Interfaces, as they are remote references.
While it IS possible to pass an HttpSession as a parameter to an EJB object, it is
considered to be "bad practice" in terms of object oriented design. This is
because you are creating an unnecessary coupling between back-end objects
38

(ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for


your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with
it a bunch of http semantics), create a class that acts as a value object (or
structure) that holds all the data you need to pass back and forth between front-
end/back-end.
Consider the case where your ejb needs to support a non-http-based client. This
higher level of abstraction will be flexible enough to support it.

How can I implement a thread-safe JSP page?


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.

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 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:
Another Example:
file1.jsp:
file2.jsp
<%test(out);% >

Can I stop JSP execution while in the midst of processing a request?


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
(assuming Java is your scripting language) is to use the return statement when
you want to terminate further processing.

Can a JSP page process HTML FORM data?


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 as.

Is there a way to reference the "this" variable within a JSP page?


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.

How do you pass control from one JSP page to another?


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.
The response.sendRedirect method

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.

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.
public void doPost (HttpServletRequest request, HttpServletResponse response)
{
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));

//use the id to compute


//additional bean properties like info
//maybe perform a db query, etc.
// . . .

f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
...
}
}

The JSP page Bean1.jsp can then process fBean, a


fter first extracting it from the default request
scope via the useBean action.

jsp:useBean id="fBean" class="govi.FormBean" scope="request"/


jsp:getProperty
name="fBean" property="name" / jsp:getProperty name="fBean"
property="addr"
/ jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean"
property="personalizationInfo" /

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

How do I include static files within a JSP page?


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.
How do I have the JSP-generated servlet subclass my own custom servlet class,
instead of the default? One should be very careful when having JSP pages extend
custom servlet classes as opposed to the default one generated by the JSP
engine. In doing so, you may lose out on any advanced optimization that may be
provided by the JSPengine.
In any case, your new super class has to fulfill the contract with the JSP engine
by: Implementing the HttpJspPage interface, if the protocol used is HTTP, or
implementing JspPage otherwise Ensuring that all the methods in the Servlet
interface are declared final.
Additionally, your servlet super class also needs to do the following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a
translation error. Once the super class has been developed, you can have your
JSP extend it as follows:

Can a JSP page instantiate a serialized bean?


No problem! The use Bean action specifies the beanName attribute, which can be
used for indicating a serialized bean.
For example:
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-INFjspbeans directory for it to be located by the JSP engine.

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?


Answer 1
If you're just including raw HTML, use the #include directive as usual inside
your .jsp file.
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
The is used for including non-JSP files.
Answer 2
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.

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.

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
42

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:

How do you connect to the database from JSP?


A Connection to a database can be established from a jsp page by writing the
code to establish a connection using a jsp scriptlets.
Further then you can use the resultset object "res" to read data in the following
way.

What is the page directive is used to prevent a JSP page from automatically
creating a session?
<%@ page session="false">

How do you delete a Cookie within a JSP?


Cookie mycook = new Cookie("name","value");
response.addCookie(mycook);
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
killmycook.addCookie(killmycook);

Can we implement an interface in a JSP?


No

What is the difference between ServletContext and PageContext?


ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

What is the difference in using request.getRequestDispatcher() and


context.getRequestDispatcher()?
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.

How to pass information from JSP to included JSP?


Using <%jsp:param> tag.

How is JSP include directive different from JSP include action. ?


When a JSP include directive is used, the included file's code is added into the
added JSP page at page translation time, this happens before the JSP page is
translated into a servlet. While if any page is included using action tag, the
page's output is returned back to the added page. This happens at runtime.

Can we override the jspInit(), _jspService() and jspDestroy() methods?


We can override jspinit() and jspDestroy() methods but not _jspService().
43

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.

What happens when a page is statically included in another JSP page?


An include directive tells the JSP engine to include the contents of another file
(HTML, JSP, etc.) in the current page. This process of including a file is also called
as static include.

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.

Can you override jspInit() method? If yes, In which cases?


ye, we can. We do it usually when we need to initialize any members which are
to be available for a servlet/JSP throughout its lifetime.

What is the difference between directive include and jsp include?


<%@ include> : Used to include static resources during translation time. : Used
to include dynamic content or static content during runtime.

What is the difference between RequestDispatcher and sendRedirect?


RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.

How does JSP handle runtime exceptions?


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.

How can my application get to know when a HttpSession is removed?


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.

What Class.forName will do while loading drivers?


It is used to create an instance of a driver and register it with the DriverManager.
When you have loaded a driver, it is available for making a connection with a
DBMS.

How to Retrieve Warnings?


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
44

(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

SQLWarning warning = stmt.getWarnings();


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.

In the Servlet 2.4 specification SingleThreadModel has been deprecated,


why?
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.

Is JSP technology extensible?


YES. JSP technology is extensible through the development of custom actions, or
tags, which are encapsulated in tag libraries.

Can we use the constructor, instead of init(), to initialize servlet?


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.

How can a servlet refresh automatically if some new data has entered the
database?
You can use a client-side Refresh or Server Push.

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.

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 do you understand by JSP Actions?


Answer: 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/>

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.

Question: Identify the advantages of JSP over Servlet.

a) Embedding of Java code in HTML pages


b) Platform independence
c) Creation of database-driven Web applications
46

d) Server-side programming capabilities

Answer :- Embedding of Java code in HTML pages

Write the following code for a JSP page:


<%@ page language = "java" %>

<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%

PrintWriter print = request.getWriter();


print.println("Welcome");

%>
</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

Answer :- A page with the text Welcome is displayed

Question: What are implicit Objects available to the JSP Page?


Answer: 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:
Variable Class Description
The context for the JSP page's servlet and any Web
application javax.servlet.ServletContext
components contained in the same application.
config javax.servlet.ServletConfig Initialization information for the JSP page's servlet.
exception java.lang.Throwable Accessible only from an error page.
out javax.servlet.jsp.JspWriter The output stream.
The instance of the JSP page's servlet processing the
page java.lang.Object
current request. Not typically used by JSP page authors.
The context for the JSP page. Provides a single API to
pageContext javax.servlet.jsp.PageContext
manage the various scoped attributes.
Subtype of
request The request triggering the execution of the JSP page.
javax.servlet.ServletRequest
response Subtype of The response to be returned to the client. Not typically
47

javax.servlet.ServletResponse used by JSP page authors.


session javax.servlet.http.HttpSession The session object for the client.

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

Question: What is JSP Output Comments?


Answer: JSP Output Comments are the comments that can be viewed in the HTML
source file.
Example:
<!-- This file displays the user login screen -->
and
<!-- This page was loaded on
<%= (new java.util.Date()).toLocaleString() %> -->

Question: What is expression in JSP?


Answer: 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 following
expression tag displays time on the output:
<%=new java.util.Date()%>

Question: What types of comments are available in the JSP?


Answer: There are two types of comments are allowed in the JSP. These are hidden
and output comments. A hidden comments does not appear in the generated output in
the html, while output comments appear in the generated output.
Example of hidden comment:
<%-- This is hidden comment --%>
Example of output comment:
<!-- This is output comment -->

Question: What is JSP declaration?


Answer: JSP Decleratives are the JSP tag used to declare variables. Declaratives are
enclosed in the <%! %> tag and ends in semi-colon. You declare variables and
functions in the declaration tag and can use anywhere in the JSP. Here is the example
of declaratives:
48

<%@page contentType="text/html" %>


<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
</body>
</html>

Question: What is JSP Scriptlet?


Answer: JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages.
Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet
executes every time the JSP is invoked.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>

Question: What are the life-cycle methods of JSP?


Answer: 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.

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.

What is a JSP Page?


A JSP page is a text document that contains two types of text: static data, which can be
49

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.

Why do I need JSP technology if I already have servlets?


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.

How is a JSP page invoked and compiled?


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.

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.

What are the advantages of JSP?

• JSP pages easily combine static templates, including HTML or XML fragments, with

code that generates dynamic content.

• 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,

shielding the page author from the complexity of application logic.

• 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

What is JSP Scriptlets?


Scriptles are: .
JSP Scriptlets begins with .We can embed any amount of java code in the JSP
Scriptlets.JSP Engine places these code in the _jspService() method.

What is JSP Expressions?


SP Expressions start with .
Between these this you can put anything and that will converted to the String and that
will be displayed.
What are Decalarations?
Declarations are similar to variable declarations in Java.Variables are defined for
subsequent use in expressions or scriptlets.
Declarations are defined between <%! and %>.
< %! int a=0; %>

What are Directives?


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.io.*" % >
< %@ include file=="banner.html" % >

How to declare instance or global variables in jsp?


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 a=0; %>

What are the different types of directives available in JSP?


The following are the different types of directives:
1 .include directive : used to include a file and merges the content of the file with the
current page
2 .page directive : used to define page specific attributes like scripting language, error
page, buffer, thread safety, etc
3 .taglib : used to declare a custom tag library which is used in the page.

Can I create XML pages using JSP technology?


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. See the white paper Developing XML Solutions with JavaServer
Pages Technology (PDF) for details.

^Back to top
51

What are JSP actions?


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.

What is meant by implicit objects? And what are they?


Implicit objects are those objects which are avaiable by default. These objects are
instances of classes defined 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

How do I use JavaBeans components (beans) from a JSP page?


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.

What is the difference between jsp:include; and %@include:


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.

What is the difference between forward and sendRedirect?


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.
52

How is Java Server Pages different from Active Server Pages?


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.

^Back to top

Can't Javascript be used to generate dynamic content rather than JSP?


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.
Set 9:

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/>

What is the difference between <jsp:include page = ... > and


<%@ include file = ... >?

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.

What is the difference between <jsp:forward page = ... > and


response.sendRedirect(url) ?

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

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.

Implicit objects available to JSP:

http://www.roseindia.net/interviewquestions/jsp-interview-questions.shtml

Life-cycle methods of JSP:

1. jspInit(): Container calls jspInit() to initialize the servlet instance. It is called


bfore any other method, and is called only once for a servlet instance.
2. _jspService(): The container calls the _jspservice() for each request and it passes
the request and the response objects. This method cannot be overriden.
3. jspDestroy(): container calls this when its instance is about to be destroyed.

How will you handle runtime exception in your jsp page?

‘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.

Which is better fro threadsafe servlets and JSPs? SingleThreadModel Interface or


Synchronization? Although the SingleThreadModel technique is easy to use, and works
well for low volume sites, it does not scale well. JSps can be made thread safe by having
them implement the SingleThreadModel interface. This is done by adding the directive <
%@ page isThreadSage=”false” %> withi n 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
instance of the servlet loaded and initialized, with the service method of each instance
effectively synchronized.
54

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
%>