You are on page 1of 30

JSP FAQ

1. 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. 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.
2. 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 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" %> 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.
3. 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().
4. 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() { . .
.} %>
<%! public void jspDestroy() { . . . }%>
5. 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.
6. 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.foo.com/path/error.html"); You can also
physically alter the Location HTTP header attribute, as shown below: <%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";

1
response.setHeader("Location",newLocn); %>
7. 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, after 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" />
8. Show me an example of POST request chaining using JSPs and servlets.
The following code example demonstrates how request chaining can be implemented
using a combination of JSPs and servlets. Consider the following JSP page, say
Bean1.jsp, which essentially instantiates the bean fBean, places it in the request, and
forwards the call to the servlet JSP2Servlet. Observe the way the bean is instantiated -
here we automatically call the bean's setter methods for properties which match the
names of the posted form elements, while passing the corrosponding values to the
methods.
<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>
<jsp:setProperty name="fBean" property="*" />
<jsp:forward page="/servlet/JSP2Servlet" />
The servlet JSP2Servlet now extracts the bean passed to it from the request, makes
changes using the appropriate setters, and forwards the call to another JSP page
Bean2.jsp using a request dispatcher. Note that this servlet, acting as a controller, can also
place additional beans if necessary, within the request.
public void doPost (HttpServletRequest request, HttpServletResponse response) {
try { FormBean f = (FormBean) request.getAttribute ("fBean");
f.setName("Mogambo");

2
// do whatever else necessary
getServletConfig().getServletContext().
getRequestDispatcher("/jsp/Bean2.jsp").
forward(request, response);
} catch (Exception ex) { . . . }
}
The JSP page Bean2.jsp can now extract the bean fBean (and whatever other beans that
may have been passed by the controller servlet) from the request and extract its
properties.
<html>
<body>
Within JSP2
<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>
<jsp:getProperty name="fBean" property="name" />
</body>
</html>
9. 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.
10. How do I set a cookie within a JSP page?
Setting cookies from within a JSP page is similar to the way they are done within
servlets. Forexample, the following scriptlet sets a cookie "mycookie" at the client: <%
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);%>
Typically, cookies are set at the beginning of a JSP page, as they are sent out as part of
the HTTP headers.
11. How can I delete a cookie from within a JSP page?
A cookie, mycookie, can be deleted using the following scriptlet:
<% Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);%>
12. 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: <%
session.setMaxInactiveInterval(300);%>would reset the inactivity period for this session
to 5 minutes. The inactivity interval is set in seconds.
13. 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 (asuming Java is your
scripting language) is to use the return statement when you want to terminate further
processing. For example, consider: <% if (request.getParameter("foo") != null) {
// generate some html or update bean property

3
} else { /* output some error message or provide redirection back to the input
form after creating a memento bean updated with the 'valid' form elements that
were input. this bean can now be used by the previous form to initialize
the input elements that were valid then, return from the body of the _jspService() method
to terminate further processing */
return;
} %>
14. 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, and 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:
<%! public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost(); } %>
<% out.print("Hi there, I see that you are coming in from "); %>
<%= whereFrom(request) %>
15. What's a better approach for enabling thread-safe 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. If you anticipate your users to increase in the future,
you may be better off implementing explicit synchronization for your shared data. The
key however, is to effectively minimize the amount of code that is synchronzied so that
you take maximum advantage of
multithreading. Also, note that SingleThreadModel is pretty resource intensive from the
server's perspective. The most serious issue however is when the number of concurrent
requests exhaust the servlet instance pool. In that case, all the unserviced requests are
queued until something becomes free -which results in poor performance. Since the usage
is non-deterministic, it may not help much even if you did add more memory and
increased the size of the instance pool.
16. 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

4
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());
%>
17. 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: <%@ page buffer="none" %>

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

5
19. How does the performance of JSP pages compare with that of servlets? How
does it compare with Perl
scripts?
The performance of JSP pages is very close to that of servlets. However, users may
experience a perceptible delay when a JSP page is accessed for the very first time. This is
because the JSP page undergoes a "translation phase" wherein it is converted into a
servlet by the JSP engine. Once this servlet is dynamically compiled and loaded into
memory, it follows the servlet life cycle for request processing. Here, the jspInit() method
is automatically invoked by the JSP engine upon loading the
servlet, followed by the _jspService() method, which is responsible for request
processing and replying to the client. Do note that the lifetime of this servlet is non-
deterministic - it may be removed from memory at any time by the JSP engine for
resource-related reasons. When this happens, the JSP engine automatically invokes the
jspDestroy() method allowing the servlet to free any previously allocated resources.
Subsequent client requests to the JSP page do not result in a repeat of the translation
phase as long as the servlet is cached in memory, and are directly handled by the Servlets
service() method in a concurrent fashion (i.e. the service() method handles each client
request within a separate thread concurrently.) There have been some recent studies
contrasting the performance of servlets with Perl scripts running in a "real-life"
environment. The results are favorable to servlets, especially when they are running in a
clustered environment. For details, see:
http://www.objexcel.com/workingjava.htm#Web Server Benchmarks
20. 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:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
<%! //declare a "global" reference to an instance of the home interface of the session
bean
AccountHome accHome=null;
public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<% //instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>
21. How can I maintain "application scope data" in Servlets or JSPs as ASPs
do?

6
In the Servlets 2.1 spec, you can set a Servlet Context Attribute. For example,
getServletContext().setAttribute("counter", new foo.Counter()); . You can also access
(or initialize) these Attributes as Application Scope Beans in a JSP, using
<jsp:useBean scope="application">.
22. 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" %>
23. How do I instantiate a bean whose constructor accepts parameters using the
useBean tag?
Consider the following bean:
package bar;
public class FooBean {
public FooBean(SomeObj arg) { ... }
//getters and setters here
}
The only way you can instantiate this bean within your JSP page is to use a scriptlet.
For example, the following snippet creates the bean with session scope:
< % SomeObj x = new SomeObj(...);
bar.FooBean foobar = new FooBean(x);
session.putValue("foobar",foobar);
%>
You can now access this bean within any other page that is part of the same session as:
<% bar.FooBean foobar = session.getValue("foobar");%>
To give the bean "application scope", you will have to place it within the
ServletContext as:
<% application.setAttribute("foobar",foobar); %>
To give the bean "request scope", you will have to place it within the request object
as:
<% request.setAttribute("foobar",foobar); %>
If you do not place the bean within the request, session or application scope, the bean can
be accessed only within the current JSP page (page scope). Once the bean is instantiated,
it can be accessed in the usual way:
<jsp:getProperty name="foobar" property="someProperty"/>
<jsp:setProperty name="foobar" property="someProperty" value="someValue"/>

7
How can my application get to know when a HttpSession is removed (when it time-
outs)?
Define a class, say SessionTimeoutNotifier, that implements
javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutNotifier object
and add it to the user session. When the session is removed,
SessionTimeoutNotifier.valueUnbound() will be called by the servlet engine. You can
implement valueUnbound() to do whatever you want. [Source code example anyone? -
Alex]
24. Can I call a JSP, then have it return control to the original JSP, like a
subroutine or method call?
Yes. That is exactly the purpose served by the <jsp:include> action. The syntax of the
include action is:
<jsp:include page="relativeURL" flush="true" />
You can have the include action anywhere within your JSP page, and the relative URL
specified for the page attribute may point to either a static (.html) or dynamic resource
like a servlet or JSP. Since the include action is handled during the request processing
phase, it makes sense to include only resources which generate some dynamic content.
The included resource is also automatically forwarded the request and response objects of
the invoking JSP page. For example, the action:
<jsp:include page="/examples/jsp/copyright.jsp"flush="true"/>
results in the output of copyright.jsp being included inline within the response of
invoking JSP page. There is however a limitation. The included JSP or servlet resource
cannot change the HTTP headers. For example, they cannot set cookies, since they are
sent to the browser via the HTTP headers.
25. What is the difference between <%@ include file="abc.jsp" %> and
<jsp:include page="abc.jsp" %> ?
The <%@include file="abc.jsp"%> directive acts like C "#include", pulling in the text of
the included file and compiling it as if it were part of the including file. The included file
can be any type (including HTML or text).The <jsp:include page="abc.jsp"> tag
compiles the file as a separate JSP file, and embeds a call to it in the compiled JSP. Some
JSP engines support the non-standard tags <!--#include file="data.inc"--> (NCSA-,
or.shtml-style) and <%@ vinclude="data.inc" %> (JRun-style), but these are not defined
in the JSP spec and thus cannot be relied on. See also this question in the JSP FAQ.
26. It is a basic concept that JSPs compile into servlets. What happens to JSP
scriptlets? How are they compiled and excuted?
Scriptlets are included within the body of your JSP servlet's service() method. JSP
Scriptlets are thus executed at request time, when the JSP engine processes the client
request. If the scriptlet produces output, the output is buffered in the out JSPWriter's)
object, which is then ultimately sent to the client.
27. I want to use url rewriting as the default mechanism for maintaining the
session ID rather than make use
of a cookie. How do I enable this when creating a new session with JSP or servlets?
This cannot be done automatically. There are no properties (in the web servers that I have
used) or APIs that would make a servlet or JSP use url rewriting instead of cookies. URL
rewriting needs to be done manually. That is, you need to create a session and then send
that session id through URL rewriting in the servlet response. Subsequently, you need to

8
retrieve the session id from the form field in the request and retrieve the session object
using that id.
28. Should I use the SingleThreadModel interface or provide explicit
synchronization to make my JSP pages and servlets thread safe?
You can have a any servlet implement the SingleThreadModel interface. JSP pages
implement this in the background when you specify <%@ page isThreadSafe="false" %>
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 synchronization for your variables. The key
however, is to effectively minimize the amount of code that is synchronzied so that you
take maximum advantage of multithreading. Also, note that SingleThreadModel is pretty
resource intensive from the server's perspective. The most serious issue however is when
the number of concurrent requests exhaust the servlet instance pool. In that case, all the
unserviced requests are queued until something becomes free - which results in poor
performance. Since the usage is non-deterministic, it may not help much even if you did
add more memory and increased the size of the instance pool.
29. What are the disadvantages of JSP?
1. As things stand, I believe that JSP can be effectively used only by someone with
some degree of Java knowledge. Currently, Java programmers are a fairly expensive
commodity.
2. Debugging JSP programs is still a major challenge.You have to remember that a
jsp page will be first converted to a .java file and then compiled. Thus, any errors will be
pointing to line numbers in the converted .java file and not the .jsp page.For example an
error in the first line of .jsp page may be shown on the 20th line of the .java file. Tracing
back can be somewhat tricky. (However, with the servlet engine Resin, the errors refer to
the line within the .jsp page.) You can debug JSP pages using IDEs like VA Java and
JDeveloper; but I think debugging JSP using an high-powered IDE would go against one
of the basic tenets of JSP - simplicity.
3. Database connectivity is not as easy as it should be. Most of the servlet engine
vendors do not support connection pooling natively, as of this day. Consequently, one has
to write a lot of custom code to do the job.
4. It is not an easy task to choose the appropriate servlet engine. There isn't a single
organization which conducts independent benchmark testing on servlet engines.
Individual vendors do provide benchmarks for their own products, but the figures usually
refer to numbers and does not provide any indication on the stability of the engine.
5. There are numerous syntax related issues with JSP programming. Jason Hunter,
author of 'Java servlet programming' has written an interesting article comparing JSP
with other scripting alternatives. You can read the article at
http://www.servlets.com/soapbox/problems-jsp.html.
30. How can you define methods in a JSP file?
You declare methods by using the JSP Declaration syntax, as specified at
http://java.sun.com/products/jsp/tags/11/syntaxref11.fm3.html:
<%! declaration; [ declaration; ]+ ... %> The declaration could be variables or
methods, or both.
31. How can I include a non-relative page (an .html page which is situated on
another server) within my JSP

9
pages?
Personally, I would NOT include the actual Java code within the JSP page, but instead
use a JavaBean (or Servlet) for this. See
http://www.jguru.com/jguru/faq/view.jsp?EID=13198 for the actual code to do this. I
would use a Reader stream though, instead of an InputStream, as you will be working
with text data, versus binary data.
32. How do you share session objects between servlets and JSP?
Sharing sessions between a servlet and a JSP page is straight forward. JSP makes it a
little easy by creating a session object and making it availabe already. In a servlet you
would have to do it yourself. This is how:
//create a session if one is not created already now
HttpSession session = request.getSession(true);
//assign the session variable to a value.
session.putValue("variable","value");
in the jsp page this is how you get the session value:
<% session.getValue("varible");%>
33. How can I access the same JavaBean instance from different JSP files?
Assuming the JSP files are on the same server and using the same ServletContext, just
use application scope for the bean component. <jsp:useBean id="localName"
class="Counter" scope="application" />
34. For brand new JSP page, if several clients make request to the same page at
the same time: is it possible that due to concurrent nature of request
handling several requests handlers will compile same JSP more then once?
How does the server resolve concurrent compiles (you ideas)? Does JSP
specification say anything about it?
No, the JSP spec does not say anything about this particular scenario. I believe the
translation phase is synchronized by the JSP engine. Consequently, only one request
thread gets to compile the JSP; all other pending requests are put into a wait queue until
the resulting servlet is loaded by the JSP engine's class loader and its init method is
executed. Then, all the waiting requests are allowed to execute the servlet's service
method concurrently.
35. What are the advantages of using beanName in the jsp:useBean syntax?
The beanName tag uses Beans.instantiate() method to instantiate a bean. This method can
instantiate a bean from either a class or a serialized template. The value of beanName can
be either a fully qualified class name or an expression that evaluates to a fully qualified
class name. This value is passed to Beans.instantiate() method which checks whether this
is a class or a serialized template. In case of a serialized template, a class loader is called.
The instantiated bean is then cast to the type specified by type attribute.
36. What exactly happens behind the scenes when a JSP page is compiled? Is it
converted to a servlet? If it
is, then does each request to a JSP page result in the creation of a new servlet?
The first time a request is made for a JSP file, either directly from a client browser or
from a servlet, the JSP file is translated into a servlet by the "JSP engine" (which is itself
a servlet -in the JSWDK, it is known as JspServlet). If there are any syntax errors within
the JSP file, the translation phase fails, triggering an error message to the client. If it was
successful, the generated servlet code is compiled, the servlet is loaded into memory by

10
the JSP engine. At this point, the JSP engine also invokes the jspInit() method, and
initializes the servlet. The jspInit() method is invoked just once during the lifetime of the
servlet. Then the
jspService() method is invoked to process the request and reply to the client. For all
subsequent requests to the JSP page, the server checks to see whether the .jsp file has
changed since it was last accessed. If there is no change, the request is handled by the
jspService() method of the servlet stored in memory in a concurrent manner. Note that
since the servlet is always stored in memory, the response is very fast. If the .jsp file has
changed, the server automatically recompiles the page file, replaces the servlet in
memory, and handles the request as described above. Although JSPs are efficient, there is
a slight delay on the first request for a .jsp page since the JSP file has to be compiled into
a servlet. Also, the JSP engine may remove the servlet from memory in a non-
deterministic way at any time owing to resource constraints. When this happpens, it first
invokes the jspDestroy() method, before flagging the servlet instance for garbage
collection.
37. What is the use of param tag in setProperty, include , forward commands?
In include and forward, params will be appended to query string, i.e.
newQueryString =
requestURI+"?paramName1=paramValue1&paramName2=parmValue2"
In setProperty every param name corresponds to property name and every parameter
value corresponds to property value, so that <param name="user" value="Administrator"
> will set property user to value "Administrator"
38. What is the best way to do database connection pooling using JSPs?
You have at least three choices:
A) Use the database pooling services built into JDBC 2.0-compliant drivers.
B) Use an application server such as WebLogic or WebSphere, which provides these
services.
C) Write your own database pooling classes (it's really not that complicated).
39. Let's assume I use a JavaBean as a go-between a JSP and an EJB, and have,
say, 50 concurrent clients that need to access the EJB functionality. Will the
JSP container actually instantiate 50 instances of the bean, or can it reuse a
single instance to access the EJB?
It depends on the scope you associate with the JavaBean. If you assign the bean with
page (which is the default) scope or request scope, a new bean will be instantiated for
each incoming request. If you assign the bean with session scope, you will still have 50
instances loaded in memory (assuming each incoming request is triggered by a distinct
client), although some may have been instantiated from an earlier request from the same
client. However, you may not want to use the session scope for a high-volume site as
these beans will continue to reside in memory, long after the request has been serviced,
consuming valuable resources until they are invalidated either explicitly or due to a
session timeout. You can also assign the bean with application scope, in which case it is
instantiated just once before being placed into the servlet context of the container. It can
then be accessed at a later time, as long as the server is up and running. Although this
may sound like an attractive proposition, do note that you will have to contend with
significant multithreading issues. For instance, you'll have to ensure that the bean is
accessed in a thread-safe manner from each of the JSP files. While you can do this using

11
explicit synchronization from within the JSP file, do note that your application may take
a significant performance hit because of this - especially if you expect tens or hundreds of
concurrent clients accessing your pages. So, in short, your best bet may be to assign the
bean with request scope.
40. What are all the implicit objects available within a JSP page?
The eight implicit variables available within JSP pages are:
· request: This represents the request triggering the service invocation and
encapsulates the HttpRequest object; has request scope.
· response: Represents the response to the request and encapsulates the
HttpResponse object. Not used often by page authors; has page scope.
· pagecontext: Encapsulates implementation-dependent features as a
PageContext; has page scope.
· application: Represents the ServletContext obtained from servlet
configuration object; has application scope.
· out: This is an instance of JspWriter that writes into the output stream; has
page scope.
· config: Represents the ServletConfig object for the JSP; has page scope.
· page: This acts as a synonym for the “this” operator. Not used often by page
authors and has page scope.
· exception: This represents the uncaught Throwable object that resulted in the
error page being invoked. By default, has page scope.
41. Can I use WML (wireless markup language) from a Java Server Page?
Follow these steps for using WML instead of HTML from within JSP.
1) Make sure that the following is added to your MIME types file of your web server
and restart it:
File Extension = .wml MIME Type = text/vnd.wap.wml
2) (From this point forward, you would do the following inside your servlets just as
you would inside
your JSP files.) In your JSP file set your response type to text/wml (normally it's
text/html or
text/plain for HTML).
3) Instead of outputting HTML code inside your JSP file, you just output WML code.
You can do this
different ways: you can just use the
out.println("<wml>");
...
out.println("<card>");
...
or you could create WML classes in Java and just have a class for each WML tag (WML
is a small set of HTML, so you will have around 30 classes). Each WML class would
appropriately handle the syntax specific to itself and handle you placing data into this
syntax. Each class would also have a toString() method. From here, in your JSP file,
wherever you want your WML code, just write Java (you have the WML classes), then to
output the WML code, you would write out.println(wml.toString()); The
wml.toString() method would call all of the other classes' (Card, Select, etc.) toString()
method to output all of the WML syntax. This design works well because if the WML

12
syntax changes and you have 100 JSP files with WML syntax inside, you would have to
change every one on them; using the WML classes, if the WML syntax changes, you just
have to change that particular class associated to whatever tag changed, and then
recompile your class. Now, keep in mind that there is one problem with outputting WML
through JSP - if your web phone is trying to call a JSP file (not through a servlet), and
there is a problem in which the JSP file outputs an error, whatever is handling your JSP
files will probably output an error in HTML format, not WML, and therefore your phone
browser will not be able to interpret this and will give you an
error page built into the phone browser. For example, if you are using JRun to run your
JSP files and it is not up and running, you will receive an error in HTML. You could
develop an error handling system for capturing JSP errors and if you are expecting WML,
you could return an error page in WML.
42. Can a JSP be multi-threaded?
By default, the service() methods of all JSP pages execute in a multithreaded fashion.
Each client request is dispatched in a concurrent manner within a separate thread by the
servlet engine. Thus, it is important to synchronize access to any page shared state in the
default scenario. You can make a page "thread-safe" and have it serve client requests in a
single-threaded fashion by setting the page tag's isThreadSafe attribute to false: <%@
page isThreadSafe="false" %>
This causes the generated servlet to implement the SingleThreadModel interface.
How do you stop all futher processing in a JSP page?
You could always just stuff a return in a scriptlet. ...
<% String action = (String)request.getParameter("action");
if(s.equals("stop!"))
return; %> ...
This should work with all JSP implementations. Keep in mind that what you are doing in
essence is returning from the middle of a Servlet service() method. I always recommend
use of "if" and "else" statements control the flow of the JSP page, rather than
bluntly returning.
43. What is the difference between Java Servlets and Java ServerPages (JSP)?
Short answer: a JSP is a Servlet that thinks it's a Web page. Medium answer: Both use
server-side Java to dynamically generate web pages. The source code to a JSP looks like
HTML, with Java embedded inside funny tags (*); the source code to a servlet looks like
Java, with HTML embedded in out.print(...) statements. Both use the Servlet API to
communicate with the web server and the client. In fact, a JSP gets compiled into a
servlet, so they're almost identical in terms of expressive power. The choice is, whether
you're more comfortable coding your pages in Java or in JSP-style HTML; and since you
can call a JSP from a Servlet and vice versa, you don't have to make an either-or decision.
Long answer: See the Servlet FAQ and the JSP FAQ for all the information you need
about both technologies.
(*) "Funny tags:" JSP can contain (a) normal HTML tags, (b) JSP tags like
<jsp:include>, (c)
custom tags, (d) scriptlets (Java code surrounded with <% and %>).
44. Can I pass GET parameters specified within the ACTION clause of a FORM
in a JSP page as:

13
ACTION="xyz.jsp?userid=<%=userid%>" to another JSP page?: Are there any
other ways to pass GET parameters from a FORM to a JSP page?
You can do this if the FORM itself is submitted using POST. So the example would be:
<FORM ACTION="xyz.jsp?userid=<%=userid%>" METHOD="POST">
This way you can read the userid from xyz.jsp along with the fields from the form you
are submitting. An alternative would be to use a hidden field as in:
<input type="hidden" name="userid" value="<%=userid%>">
If you include a hidden field like this in your form you can use GET or POST to submit it
and the userid is passed to the xyz.jsp just like any other field.
45. When I reference 'session' or 'request' from within a method contained in a
declaration, I get an
'Undefined variable' compile error. Why?
The implicit objects session, request, etc. are defined in the JSP service method
_jspService(). The are not instance level variables of the created JSP class. Hence, they
are not immediately available to methods outside the service method. You would need to
pass them in as parameters.
46. How does the "session" scope work with the useBean tag? What is the
difference between "session" and
"application" for the useBean tag?
When you request a bean from the session scope or the application scope, and such a
bean already exists, the reference to the existing bean is returned, and a new bean is not
instantiated; otherwise, the bean is newly instantiated, placed into the specified scope,
and the reference is returned. The session scope is different then the application scope in
that an application bean is kept around until the servlet/jsp container is restarted, while
session beans time out after a specified amount of inactivity or if the session is
invalidated for any reason. Also, beans with session scope are available only to a single
client which participates in the session; beans with application scope have "global"
visibility and are available to all JSPs and servlets which are part of the application.
47. What is the most efficient approach for integrating EJB with JSP? Should
the EJBs be invoked directly
from within JSP scriptlets? Should the access take place from within Java
beans? Or is it best to use
custom tags for this purpose?
JSP scriptlet code should be minimal. Invoking EJB code directly on a JSP page results in
many lines of code on your JSP page, including try...catch blocks to catch naming and
finding exceptions. Using a standard JavaBean as an intermediary between the JSP page
and EJB server cuts down on the amount of code needed to add to a JSP page, and
promotes reuse. The JavaBean should be a simple wrapper around the EJB you are
accessing. If you use a standard JavaBean you could also use the jsp:useBean tag to setup
EJB parameters, such as the server URL and server security parameters. Custom tags are
also an option. However, they require a lot more coding than a simple JavaBean wrapper.
The point should be to rewrite as little code as possible while at the same time keeping
the JSP scriptlet content as light as possible.
48. What is the recommended, "best" architecture for JSP applications?
There really is no "best" architecture. It depends on:
1. The size and scope of the application.

14
2. The amount of resources (human and monetary) available to develop the
application.
3. Time available to develop the application.
For a relatively small application which requires simple database access, a three-tier
model using JSP, JavaBeans, and JDBC is all that you need. The JavaBeans would
contain methods to access the data via JDBC. The JSP pages would embed the JavaBeans
in the page using the <jsp:useBean> tag. If the use of the application grows, you can
always add database pooling and other optimizations to scale the architecture without
redesigning everything. If your application is going to going to be large scale - an online
e-commerce site for instance, you would want to invest in a more scalable solution. I
would recommend a "n-tier" solution using JSP,(standard) JavaBeans, and Enterprise
JavaBeans. JSP would provide the client interface. One or more JavaBeans would sit
between the JSP pages and the EJB container. The JavaBeans would be embedded in
your JSP pages using the <jsp:useBean> tag. The JavaBeans would utilize session beans
to perform transactions and access data on entity beans. This architecture is both
distributed and scaleable. It supports transactions and all the benefits an application
server has to offer (database pooling, clustering, etc). Never throw JDBC code or EJB
code directly on your JSP page. This leads to clutter which most web designers (the
people who have to work with on the page) would probably not understand and
would rather not look at. Not to mention it quickly becomes a maintenance nightmare.
49. How do I include a file in my JSP file where I don't know the filename to
include until runtime?
This question describes the basic difference between the <%@include file="abc.jsp"%>
directive and the <jsp:include page="abc.jsp"> tag. Basically, the first is done at compile
time and the latter is done at runtime. If the filename itself isn't known until runtime, you
need to include another directive in the use of <jsp:include> like:
<% String filename = "foo.jsp"; %>
<jsp:include page="<%= filename %>" flush="true"/>
50. How do I pass session information from a JSP to a Applet. Can I pass them
as parameters or can I talk back from an Applet to the JSP page?
The easiest way to pass session info is through the applet parameters. The following
example code uses some scriptlet tags to set the parameters of the applet.
<applet code="foo.class" width="100" height="100">
<% for (x = 0; x < session.fooData.getCount(); x++) { %>
<param name="<%= session.fooData.getName(x) %>"
value="<%= session.fooData.getValue(x) %>">
<% } %>
</applet>
If you want to have the applet be able to talk back to the server as it runs you can do that
too. In this case the applet should not communicate with the JSP that hosted it but rather
with a servlet running in the same web application. Both the JSP and the servlet would
share the same session info so you have access to the same data. The following example
uses serialized object to pass the information back and forth but you could form the
requests and responses with plain text or xml or whatever. The applet needs to open a
connection to the web application, post a request and listen for the response.
public MyResponse postRequest(MyRequest myRequest) {

15
try { // Open the connection
URL url = new URL(getCodeBase(), "myServlet");
URLConnection uc = url.openConnection();
// Post the request
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);
uc.setRequestProperty("Content-type", "java-internal/" +
myRequest.getClass().getName());
ObjectOutputStream out = new ObjectOutputStream(uc.getOutputStream());
out.writeObject(myRequest);
out.flush();
// Read the response
ObjectInputStream in = new ObjectInputStream(uc.getInputStream());
return (MyResponse) in.readObject();
} catch (Exception e) { e.printStackTrace(); }
return null; }
The servlet that handles the post would be pretty simple too. It just needs to read the
request, figure out what the request was and return the correct data.
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try { // Read the resquest
ObjectInputStream ois = new ObjectInputStream(req.getInputStream());
MyRequest myRequest = (MyRequest) ois.readObject();
// Format the response from the session data
HttpSession session = req.getSession(true);
MyResponse myResponse = new MyResponse(session.fooData);
// Send the response
ObjectOutputStream oos = new ObjectOutputStream(res.getOutputStream());
oos.writeObject(myResponse);
} catch (Exception e) { e.printStackTrace(); }
}
51. What is the best way of implementing a web application that uses JSP,
servlet and EJB technologies all
together following a Model View Controller (MVC) architecture?
[See the Sun J2EE Blueprints for "an integrated set of documentation and examples that
describe and illustrate 'best practices' for developing and deploying component-based
enterprise applications using the J2EE platform" including some good architecture
whitepapers and source code. -Alex] Hmm, 'Best Way' is a bit rough - there are several
'good' ways, and the usual set of trade-offs between them. (I'm a consultant - I have to
start any answer with "It depends...", otherwise they
revoke my whiteboard privileges) The main thing you need to keep in mind as you design
this sort of a system is that you want the interface into the EJB's to be rather narrow: in
any flow, the ideal is to call one EJB method (hopefully on a stateless session bean), and
let it make calls to entities on your behalf, then hand back the data you need to display.
How you display it depends: you can either embed beans on your JSPs and let the beans

16
make that hopefully-one EJB call, or you can post to a servlet, let that make the call, then
forward to the JSP for display. The second of these is more flexible and gives you more
leverage to hide, change, and enforce your site's structure. The first, however, will be
easier for developers new to this web thing to follow. Essentially, I'm saying that Entity
beans are your model, your controller is Session beans (maybe with a bit of help from
servlets or beans), and your JSPs, beans and servlets are your View. One thing to note
here: this discussion strongly implies that your EJBs are capable of externalizing their
state as some number of very simple 'value objects' (not EJBs themselves, just something
we can pass back and forth). These value objects are probably tuned tightly to a
workflow, and will be produced by that session bean. This way the traffic between the
EJB (server) and the JSP/Servlet (client) is tuned to what the client needs, while the
transaction load on the server is minimized.
I am working on a large project using model view a...
Vibhu Srinivasan, May 31, 2000 I am working on a large project using model view
architecture. Here goes my two cents worth of an architecture that has produced good
results for us
The architecure involves a MVC with the controllers being entity and session beans. We
are moving away from using entity beans unless there are many transactions involved.
These ejbs pass back value objects as specified in the blueprints by sun.
We also use bulk accessor session beans which go directly to the database and also call
some other session or entity beans.
This is the model. Now about the controller and the view: All the JSP's talk to servlets
which are the controllers. The servlets control creation and setting various properties on
the java beans.
The java beans are broken to two kinds.
1.Data access beans
2.Presentation beans
The servlets create the presentation beans which are tied to some screens . The JSPs
only read information from the java beans. Check out the blueprints from sun for some
good analysis!
52. Why should I use the <jsp:useBean> tag, instead of just instantiating beans
directly inside scriptlets?
The arguments in favor of using the useBean tag are:
· The tag syntax is arguably less intimidating to HTML designers.
· useBean has a "scope" parameter that automatically determines whether the
bean should be stored as a local variable, a request variable, a session variable, or an
application attribute. If you were to create beans explicitly you'd have to do it 4 different
ways for the 4 different scopes.
· If the variable is persistent (session or application), useBean initializes it if
necessary, but fetches the variable if it already exists.
· The tags are potentially more portable to future versions of the JSP spec, or
alternate implementations (for example, a hypothetical JSP engine that stores variables in
a database, or shares them across server processes).
The above is excerpted from my article at JavaWorld, Using XML and JSP together
(March 2000).

17
53. Is it an acceptable practice to use response.sendRedirect() in a JSP page? Or
should you just throw an
exception and use the error page directive?
The response.sendRedirect() will direct the browser to go to a new page/url. The new url
will appear in the 'location' at the top of the browser page. You must specifiy a full URL
like http://www.bob.com/start.html. Using this requires a round trip to the server with all
the attendant delays. A pageContext.forward() will "jump" to the url specified which may
be a relative url like "other.jsp" to indicate it is in the same base location as the current
page. The browser location box will show the URL of the original page, not the one you
redirected to. There is no additional trip back to the browser and then back to the server
so time is kept to a minimum. When using pageContext.forward(), this forwards the
original request and response objects. If you need to change one of the attributes in the
original request object, there is no function to do this but this can be reset by passing new
querystrings in the URL given to forward. An errorpage directive just puts a big "try {.. }
catch (Throwable x) {..}" around the Java for the whole jsp page (including each of the
out.print() lines that handle the HTML portion of the jsp page) If an exception is
"caught", things are redirected (as in pageContext.redirect() above) to the error page. If
you put the "isError" directive on the error page you get a few predefined jsp variables
that tell you what the exception is that triggered the jump to the page. So the answer to
your question, in no uncertain terms, is "maybe". It just depends on what you want to do.
54. How do I use the taglib directive to add custom tags to JSP?
Custom tags are pretty straightforward to build, and a useful tutorial can be found at
orionserver.com.
However, this is (of course) geared up to using their own server, so here's an example of
how to build a custom tag using the reference implementation of the Servlet/JSP
specifications - Tomcat. For simplicity, this example will make use of the example web
application that comes with Tomcat (TOMCAT_HOME/webapps/examples). Step 1 :
Build a class that implements the javax.servlet.jsp.tagext.Tag interface as follows.
Compile it and place it under the web-inf/classes directory (in the appropriate package
structure).
package examples;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class ShowDateTag implements Tag {
private PageContext pageContext;
private Tag parent;
public int doStartTag() throws JspException { return SKIP_BODY; }
public int doEndTag() throws JspException {
try { pageContext.getOut().write("" + new java.util.Date());
} catch (IOException ioe) { throw new JspException(ioe.getMessage()); }
return EVAL_PAGE;
}
public void release() { }
public void setPageContext(PageContext page) { this.pageContext = page; }
public void setParent(Tag tag) { this.parent = tag;}

18
public Tag getParent() { return this.parent;}
}
Step 2 : Now we need to describe the tag, so create a file called taglib.tld and place it
under the web-inf directory.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>myTag</shortname>
<uri>http://www.mycompany.com/taglib</uri>
<info>My own tag library</info>
<tag>
<name>showDate</name>
<tagclass>examples.ShowDateTag</tagclass>
<info>Show the current date</info>
</tag>
</taglib>
Step 3 : Now we need to tell the web application where to find the custom tags, and
how they will be referenced from JSP pages. Edit the web.xml file under the web-inf
directory and insert the following XML fragement.
<taglib>
<taglib-uri>
http://www.mycompany.com/taglib
<taglib-uri>
<taglib-location>
/WEB-INF/taglib.tld
<taglib-location>
</taglib>
Step 4 : And finally, create a JSP page that uses the custom tag.
<html>
<head><title>Date tag example</title></head>
<body>
<%@ taglib uri="http://www.mycompany.com/taglib" prefix="myTag" %>
<myTag:showDate/>
</body>
</html>
Now restart the server and call up the JSP page! You should notice that every time the
page is requested, the current date is displayed in the browser. Whilst this doesn't explain
what all the various parts of the tag are for (e.g. the tag description,
page context, etc) it should get you going. If you use the tutorial (above) and this
example, you should be able to grasp what's going on!
55. What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?

19
The jsp:useBean tag is very powerful. It allows you to declare a variable using a single
syntax, but produces code that (a) either initializes the variable, or locates it if it's already
been initialized, and (b) stores it in one of a number of locations, depending on its scope.
In order to share variables between JSPs and Servlets, you need to know how to create
and to
access variables from inside your servlet code. Following are examples which should
help you understand how to do this.
<jsp:useBean class="foo.Counter" scope="application" />
In this example, when the Counter bean is instantiated, it is placed within the servlet
context, and can be accessed by any JSP or servlet that belongs to the application (i.e.
belongs to the same servlet context). The servlet equivalent of the above useBean action
is: foo.Counter counter = (foo.Counter)getServletContext().getAttribute("counter");
if (counter == null) {
counter = new foo.Counter();
getServletContext().setAttribute("counter", counter); }
<jsp:useBean id="counter" class="foo.Counter" scope="session" />
In this example, when the Counter bean is instantiated, it is placed within the current
session, and can be accessed by any JSP or servlet during a subsequent request by the
current user. The servlet equivalent of the above useBean action is: HttpSession
session = request.getSession(true);
foo.Counter counter = (foo.Counter)session.getValue("counter");
if (counter == null) {
counter = new foo.Counter();
session.putValue("counter", counter);
}
<jsp:useBean id="counter" class="foo.Counter" scope="request" />
In this example, when the Counter bean is instantiated, it is placed within the current
request object, and can be accessed by any JSP or servlet during a the same request; e.g.,
if a RequestDispatcher is used, or if <jsp:include> or <jsp:forward> sends the request to
another servlet or JSP. The servlet equivalent of the above useBean action is:
foo.Counter counter = (foo.Counter)request.getAttribute("counter");
if (counter == null) {
counter = new foo.Counter();
request.setAttribute("counter", counter);
}
<jsp:useBean id="counter" class="foo.Counter" scope="page" />
In this example the Counter bean is instantiated as a local variable inside the JSP method.
It is impossible to share a page scope variable with another JSP or Servlet. The servlet
equivalent of the above useBean action is:
foo.Counter counter = new foo.Counter();
56. What is the difference between ServletContext and PageContext?
The ServletContext gives information about the container in which the servlet (or JSP) is
running in. Parameters for this can be setup in the web application deployment descriptor
and there is one ServletContext per web application. The PageContext gives the servlet
(or JSP) information about the request that it is currently handling and contains
information about the request and any parameters, the session, the response object, a

20
reference to the output stream and also a reference to the web application's
ServletContext.
57. If "yy.jsp" includes "xx.jsp" and then I modify "xx.jsp" and try to execute
"yy.jsp", does the JSP enginerecognize "xx.jsp" as being modified? If it
detects modification, does it automatically recompile xx.jsp ?
Yes...if you are using the <jsp:include> tag and not the include directive <%@ include
%>, xx.jsp will be recompiled automatically if it changes. You may also want to generate
the appropriate META tags within yy.jsp so that it is not cached by
either your browser or the proxy server.
58. Is there any difference between the attributes class=com.myco.MyClass and
the
beanName=com.myco.MyClass attributes in the <jsp:useBean> tag?
Yes, there is some difference. class=com.myco.MyClass instantaites a bean from a class
using the new keyword, thus invoking the class' public no-arg constructor as: new
com.myco.MyClass()
beanName=com.myco.MyClass
When you use beanName, the bean is instantiated via the java.beans.Beans.instantiate
method. This method can also instatiate serialized forms of a class which may or may not
have a public no-arg constructor.
59. What does the attribute flush=true in <jsp:include page="abc.jsp"
flush="true"/> mean? Where is it
essential to use?
From the JSP 1.1 Specs:
"flush: Mandatory boolean attribute. If the value is 'true', the buffer is flushed. A 'false'
value is not valid in JSP 1.1." [Emphasis added] Unluckily there's no statement about the
"why".
60. What happens to the compiled servlet class files when we shutdown the JSP
engine? Will they will be
erased from memory as well as from disk?
This depends on the JSP engine implementation. Under normal circumstances, the server
will leave .class files on the disk until the .jsp file changes, ignoring server restarts. Some
engines can be configured to recompile after each restart of the engine, never recompile,
or recompile only if the .jsp is newer then the .class file.
61. What is the best way to do session and application initialization in a JSP
page?
You can initialize the session and application using the HttpSession.putValue() and
ServletContext.setAttribute() methods in a JSP page. The current HttpSession (session)
and ServletContext (application) objects are made available implicitely to a JSP page as
"session" and "application" objects. As a best practise you should initialize these objects
as part of post-processing in your JSP page or Servlet.
62. How can I pass data retrieved from a database by a servlet to a JSP page?
One of the better approaches for passing data retrieved from a servlet to a JSP is to use
the Model 2 architecture as shown below: Basically, you need to first design a bean
which can act as a wrapper for storing the resultset returned by the database query within
the servlet. Once the bean has been instantiated and initialized by invoking its setter

21
methods by the servlet, it can be placed within the request object and forwarded to a
display JSP page as follows:
com.foo.dbBean bean = new com.foo.dbBean();
//call setters to initialize bean
req.setAttribute("dbBean", bean);
url="..."; //relative url for display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
The bean can then be accessed within the JSP page via the useBean tag as:
<jsp:useBean id="dbBean" class="com.foo.dbBean" scope="request"/>
...
<% //iterate through the rows within dbBean and access the values using a
scriptlet%>
Also, it is best to design your application such that you avoid placing beans into the
session unless absolutely necessary. Placing large objects within the session imposes a
heavy burden on the performance of the servlet engine. Of course, there may be
additional design considerations to take care of - especially if your servlets are running
under a clustered or fault-tolerant architecture.
63. What is meant by the term "business logic"?
"Business logic" is just a fancy way of saying "code." :-) More precisely, in a three-tier
architecture, business logic is any code that is not specifically related to storing and
retrieving data (that's "data storage code"), or to formatting data for display to the user
(that's "presentation logic"). It makes sense, for many reasons, to store this business logic
in separate objects; the middle tier comprises these objects. However, the divisions
between the three layers are often blurry, and business logic is more of an ideal than a
reality in most programs. The main point of the term is, you want somewhere to store the
logic and "business
rules" (another buzzword) of your application, while keeping the division between tiers
clear and clean.
64. How can I use a database connection pool within a servlet or JSP page?
If you are using a J2EE Server, you should be able to access a connection pool via JNDI
and retreive the a connection. If you are not using a J2EE Server, you can download (or
write) a connection pool, and install it into your JSP/Servlet application, and share it via
the application space.
65. What is the exact difference between request.getRequestURI() and
request.getServletPath()?
request.getRequestURI() contains the context path defined in your server.xml, on the
other hand, request.getServletPath() does not contain this path.For example, in your
server.xml, you define:
<Context path="/mywebapp" docBase="D:\work\mywebapp" debug="0"
reloadable="true" /> ;
under the directory d:\work\mywebapp, you have sub directory WEB-INF and jsps, under
the directory work\mywebapp\jsps, you save your jsp file, say mytest.jsp. So when you
use request.getRequestURI(), the result will be: /mywebapp/jsps/mytest.jsp, the other
result using request.getServletPath() will be /jsps/mytest.jsp.

22
66. What is a three-tier architecture?
A three-tier architecture is any system which enforces a general separation between the
following three parts:
1. Client Tier or user interface
2. Middle Tier or business logic
3. Data Storage Tier
Applied to web applications and distributed programming, the three logical tiers usually
correspond to the physical separation between three types of devices or hosts:
1. Browser or GUI Application
2. Web Server or Application Server
3. Database Server (often an RDBMS or Relational Database)
However, inside of the application server, there is a further division of program code into
three logical tiers. This is kind of fractal: the part (app server object design) resembles the
whole (physical system architecture). In a classic JSP/Servlet system, these objects are
usually implemented as:
1. JSPs or Servlets responsible for creating HTML or WML user interface pages
2. Servlets or JavaBeans responsible for business logic
3. Servlets, JavaBeans, or Java classes responsible for data access. These objects
usually use JDBC to query the database. In an EJB system, the three logical tiers are
usually implemented somewhat differently:
1. JSPs, Servlets, or Java client applications responsible for user interface
2. Session Beans or Entity Beans whose methods implement business logic and
business rules
3. Entity Beans whose fields represent data; these fields are "persisted" (stored
and retrieved) either by the EJB server (for container-managed persistence) or by the
Entity Beans themselves (for bean-managed persistence)
As you can see, the precise definition of "tiers" can vary widely depending on the
particular needs and choices of an application designer. However, they all maintain the
general division of client-logic-storage. If the architecture contains more than three
logical tiers -- for instance, multiple data feeds,multiple transactional data sources,
multiple client applications -- then it is typically called an "N-tier" or "Distributed"
architecture. See also:
· What seperates one tier from another in the context of n-tiered architecture?
· In distributed architecture (typical three tier consisting of thin client,
middleware & database) which type of JDBC driver should be used and why?
· What is meant by the term "business logic"?
· Are the following schemes 3 tiered architecture?
· What is the recommended, "best" architecture for JSP applications?
67. How can I call a servlet from a JSP page? How can I pass variables from the
JSP that the servlet can
access?
You can use <jsp:forward page="/relativepath/YourServlet" /> or
response.sendRedirect("http://path/YourServlet").
Variables can be sent as:
<jsp:forward page=/relativepath/YourServlet>
<jsp:param name="name1" value="value1" />

23
<jsp:param name="name2" value="value2" />
</jsp:forward>
You may also pass parameters to your servlet by specifying
response.sendRedirect("http://path/YourServlet?param1=val1").
See also:
· What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?
68. How can I improve the performance of a JSP Page which contains many
session variables?
There's nothing special about session variables that should slow your code down. Try
using a performance analyzer such as OptimizeIt (others probably listed elsewhere on
jGuru) to find out what the bottlenecks are in your code. If your servlet engine is
handling sessions too slow, you can always switch to a different vendor... that's the
benefit of the standard specification.
69. What is the difference between response.sendRedirect(),
RequestDispatcher.forward(), and
PageContext.forward()?
In a nutshell, RequestDispatcher.forward() works on the server and
response.sendRedirect() works on the browser. When you invoke
RequestDispatcher.forward(), the servlet engine transfers control of this HTTP request
internally from your current servlet or JSP to another servlet or JSP or static file. When
you invoke response.sendRedirect(), this sends an HTTP response to the browser to make
another request at a different URL. RequestDispatcher.forward() and
PageContext.forward() are effectively the same. PageContext.forward is a helper method
that calls the RequestDispatcher method.
Well basically both method calls redirect you to new resource/page/servlet.
The difference between the two is that sendRedirect always sends a header back to the
client/browser. this header then contains the resource(page/servlet) which you wanted to
be redirected. the browser uses this header to make another fresh request. thus
sendRedirect has a overhead as to the extra remort trip being incurred. it's like any other
Http request being generated by your browser. the advantage is that you can point to any
resource(whether on the same domain or some other domain). for eg if sendRedirect was
called at www.mydomain.com then it can also be used to redirect a call to a resource on
www.theserverside.com. In the case of forward() call, the above is not true. resources
from the server, where the fwd. call was made, can only be requested for. But the major
diff between the two is that forward just routes the request to the new resources which
you specify in your forward call. that means this route is made by the servlet engine at
the server level only. no headers are sent to the browser which makes this very efficient.
also the request and response objects remain the same both from where the forward call
was made and the resource which was called. I don't know about
PageContext.forward().
70. What is the best way to pass objects between servlets and JSP - when do I use
getAttribute and when do
I use getParameter?
request.getAttribute() is a server-side only mechanism of passing parameters between
servlets and JSPs. request.getParameter() is normally a browser-side mechanism of

24
passing parameters between servlets and JSPs. You can also use request.getParameter to
pass parameters on a dynamic include within a servlet or JSP. To pass parameters using
request.getParameter(), construct a new URL that points to the target servlet or JSP and
append a querystring with your parameters and embed this in an a href tag., e.g.,
http://myserver.com/target.jsp?param1=valu1&param2=value2. Then when the browser
clicks the link, it invokes target.jsp, and target.jsp can retrieve the parameter values using
request.getParameter("name1") and request.getParameter("name2"). You can also do a
dynamic servlet include on another servlet or JSP, and pass a query string. This allows
you to pass parameters server-side using request.getParameter(). Note that you can only
pass Strings using request.getParameter(). To pass parameters using
request.getAttribute(), you call request.setAttribute() with the appropriate parameter
name and object, and then include or forward the request and response
(using the RequestDispatcher or PageContext's convenience methods) to another
servlet or JSP.
You can pass objects using this method. The best method really depends on how your
architecture. Most parameters get passed via form-like parameters (the querystring) as the
browser makes different requests. If you are using multiple pages to generate different
pieces of a page and using includes and forward within the server, you should probably
use request.getAttribute(). You can also use the HttpSession to pass objects between
servlets and JSPs as the user moves around your site.
71. How do <jsp:setProperty> and <jsp:getProperty> work internally? How
does it identify the variable that
needs to have its value set or retrieved?
This is done by using reflection. For example, the following code excerpt finds a getter
method using the bean class and property name as parameters (under Tomcat 3.2):
public static java.lang.reflect.Method getReadMethod(Class beanClass, String prop)
throws JasperException {
java.lang.reflect.Method method = null;
Class type = null;
try {
java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(beanClass);
if ( info != null ) {
java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors();
for (int i = 0 ; i < pd.length ; i++) {
if ( pd[i].getName().equals(prop) ) {
method = pd[i].getReadMethod();
type = pd[i].getPropertyType();
break;
}
}
} else {
// just in case introspection silently fails.
throw new JasperException(Constants.getString(
"jsp.error.beans.nobeaninfo", new Object[] beanClass.getName()}));
}
} catch (Exception ex) {

25
throw new JasperException (ex);
}
if (method == null) {
if (type == null) {
throw new JasperException(Constants.getString(
"jsp.error.beans.noproperty",
new Object[] {prop, beanClass.getName()}));
} else {
throw new JasperException(Constants.getString(
"jsp.error.beans.nomethod",
new Object[] {prop, beanClass.getName()}));
}
}
return method;
}
72. How can I have a different httpSession object for:
1. Each browser window(s) of same instance of browser
2. Each browser instance
Most session management is done through cookies. If there are two seperate windows
running the same browser (e.g. Netscape), they will use the session. That is because both
windows will look in the same directory for the cookie they are using to maintain state. If
each window was to have their own session, there would be know way to determine
which session belongs to which window. However, if there are two windows with two
different browser applications (e.g. Netscape and IE),
they will each use different sessions because they will use different cookies.
73. What's the difference between just binding objects to a session as session
variables and creating a Bean
and associating it to the session?
There is no differce other than syntax. The <jsp:useBean> tag and its corresponding
accessor tags were created more as another level of programming abstraction than
anything else. If you look at the underlying servlet code that is generated from the JSP,
<jsp:useBean ... scope="session" /> translates into retrieving the object from the session.
And if the that object does not exist in the session, it is created (through the default
contructor) and placed in the session. The only difference between binding the object
directly and creating a Bean is that the<jsp:useBean> tag must use classes that meet the
minimum Bean requirements - Serializable and has a default contructor.
Can a JavaBean access methods/implicit objects of the JSP page which created it?
Yes, they can, but not by virtue of the fact that they are being used in a JSP page. In order
for a JavaBean to access the methods/implicit objects of a JSP page, it has to be
initialized with a handle or reference to the page itself. For instance, your JavaBean could
have the following code:
private JspPage jspPage;
public JspPage getJspPage(){ return jspPage; }
public void setJspPage(JspPage jspPage){ this.jspPage = jspPage;}
Then, from within your JSP page, you could invoke:
<jsp:useBean id="yourBean" class="your.package.YourBean" />

26
<% yourBean.setJspPage(this); %>
74. Now, your bean can access the implicit objects and methods of the calling
JSP page.The <jsp:forward> only works within a single servlet context. Is
there any way to forward the request to a page across the web server?
No. You have to use response.sendRedirect(), which is not a forward. It sends a message
to the client's browser (via a HTTP header) to issue a request to the target.
75. Is there a simple way to share a single Session object across multiple
ServletContexts?
No, servlet sessions are purposefully designed to not be shared across servlet contexts as
this is viewed as a security risk. The Servlet 2.3 spec supports listening for events such as
session creation and destruction, so you could handle sharing session information across
different contexts this way.
76. Can I avoid problems with concurrent access to bean variables by
implementing the SingleThreadModel?
Or can the scope attribute be used to ensure that the same bean cannot be
concurrently used by more
than one thread?
First, let me address the SingleThreadModel question. This interface really does not
address the issue of concurrent access to JavaBeans is a JSP application. To cite the
documentation of this interface directly: If a servlet implements this interface, the servlet
will be thread safe. However, this interface does not prevent synchronization problems
that result from servlets accessing shared resources such as static class variables or
classes outside the scope of the servlet. In other words, access to a servlet's instance
variables is thread safe, but that is it. Now, in response to your other question about
scope... Most times your scope will be page, request or session. In each of these, you will
probably only have one thread handling the
JavaBean - the thread handling the HttpServletRequest. However, if a Bean has
application scope (acessible from multiple servlets in the application) you need to
synchronize access to this Bean.
77. Does JSP/HTML need to be reconfigured to allow URL rewriting?
No. URL rewriting is a server stategy for session tracking to maintain a user's state across
multiple pages/requests.
Usually, a server will first attempt to use cookies to track a user's session. If the user has
cookies turned off on their browser, URL rewriting is typically implemented as an
alternative for session tracking. Either way, no changes would need to be made to
JSPs/HTML pages. Both session tracking strategies are done "behind the scenes" and are
independent of the HTML that is being served.
78. What is the lifecycle of a JSP page? Please include details of the internal
mechanisms of JSP engine.
First, the internal workings of the JSP engines can vary between servers. There is a
general lifecycle that applies to all servers, but a few implementation differences may
exist. That said, the lifecycle of JSPs is actually pretty simple:
1. A user makes an HTTP request (usually a GET or POST) to the server
2. If the request matches a registered pattern, the server calls the JSP page
compilation servlet. Note that this registered pattern can usually be changed. Most often

27
it's "*.jsp", but you could create other patterns or restrict the page compilation to certain
directories on the server.
3. The Page Compilation servelet checks if the page actually exists. If not, it
returns a 404 (not found) error
4. The Page Compilation servlet checks to see if it needs to regenerate/recompile
the page.This determination is usually based on some server settings. In general, if a
certain "timeout" setting has passed since the page was last accessed, it checks to see if
the page source is newer than the last-generated servlet for it. If so, we need to
regenerate.
5. If we need to regenerate the servlet for the JSP, the Page Compilation servlet
translates the JSP code to Java servlet source. Then the Page Compilation servlet
compiles the generated servlet. Compilation errors result in an error page being sent to
the user.
6. If the servlet isn't currently loaded in the server (or has changed), the server
loads it and calls its init() method, passing a ServletConfig object to describe the server
and pass initialization parameters.
7. The server calls the servlet's service() method, passing an HttpServletRequest
and HttpServletResponse. The generated servlet calls the code contained within the JSP,
passing these parameters as request and response.
8. The server returns the resulting stream of (usually HTML) to the browser that
asked for it.
Finally, if the server decides to discard the generated servlet (usually when noone has
requested it for longer than a preset timeout period), it calls the servlet's destroy()
method, then drops the reference to that servlet (making it a candidate for garbage
collection.) Keep in mind that JSPs are nothing but servlets in nicer clothing. They can do
the exact same things as a servlet, but are generally easier to write.
79. What is "Session Migration" ?
In the context of JSPs, this would be the mechanism of moving sessions from on server to
another in case of server failure. The two most common ways of implementing this are:
· Persisting the sessions, typically to a database
· Storing the sessions in-memory on multiple servers, typically a primary
server and a backup server
In the first case, as session information is changed, the session data is persisted to a
database accessible by all servers. If on server fails, all other servers can access the
session data the failed server was managing. In the latter case, all session data is
redundantly stored in-memory on multiple servers within a cluster. The session state is
replicated in-memory between servers within a cluster using IP multicasting. In this case,
if one server crashes, its backup server now becomes the primary server
for all sessions the failed server was maintaining. In either situation, this type of session
management allows for server failure without losing users' state.
80. Please explain the lifecycle of a JSP page in detail.
This is the typical life cycle for a JSP page:
· Before a JSP is accessed for the first time, it exists as it was originally
created, as a .jsp file.

28
· When a request is first made for the JSP, it it translated into .java file. This
file represents a servlet class with all the JSP tags and scriplets converted to
corresponding Java code.
· This .java is then compiled into a .class file for the servlet container to use.
· From this point on, it enters the life cycle of a servlet.
The one thing to note is that some servet/JSP containers provide the capability to auto-
reload newer versions of JSPs. That is, each time a request for a JSP is made, the servlet
container checks the time stamp of the .jsp file and its corresponding .class file. If the
.jsp is newer, the JSP starts over at step one in its life cycle.
81. If a user has their cookies disabled, are there any other techniques, in
addition to URL rewriting, that
enable the maintenance of state information using JSP?
The only other reliable way you can track a user's state is to place some sort of state
information in the HTML you send to the user. The two clearest ways of implementing
this are: 1. Place a user identifier as a parameter in the HTML you are sending. For
example, if the HTML you are sending to the user submits a form, you include
something like this:
2. <form method="post"....>
3. ...
4. <input type="hidden" name="userID" value="12345">
5.
6. ...
7. </form>
If the user's request is a GET instead of a POST (like above), you would need to append
this parameter to the URL, like:
<a href="http://www.somesite.com?userID=12345> Click HERE!</a>
Of course, this ID would map to state information you have on the server side where it
can be retrieved. How this isimplemented doesn't matter. It can map to a key in a Hash, a
primary key in a database, a EJB PK, whatever. Just as long as this parameter can let the
server retreive the user's state.
8. You could always place all the state information in the HTML as hidden fields.
This would be the same as above, but instead of using a key, you would put the
actual data. Not a very flexible idea, especially if there is a lot of data regarding
user state. Another note: be sure that if you use a key, you encrypt the key so
that the ID you are using cannot be easily guessed to map back to a real key in
the server. This will help prevent fraudulant access to user data. Once you try
either of these techniques a bit, you will appreciate the Servlet API's abstraction
of tracking user state!
83. Can I remove a bean from a session in JSP when the bean was set up using
the <jsp:useBean ...
scope="session"/> tag?
Yes. <jsp:useBean id="bean" class="com.mypackage.MyBean" scope="session" />
basically translates into:
<% MyBean bean = (MyBean)session.getAttribute("bean");
if (bean == null) {
bean = new MyBean();

29
session.setAttribute("bean",bean); }
%>
So, you can remove it using the same sort of semantics:
<% session.removeAttribute("bean"); %>
Actually, you can remove an object stored in the session this way no matter how it was
placed there. Remember, the JSP XML actions have no "magic" about them. They are
just a way to remove Java code from JSP pages and replace it with more user-friendly
XML tags. This is the same priciple behind Custom Tags - it's another layer of
abstraction. However, when all is said and done, the JSP will be translated in a Servlet
and, therefore, Java code. So, anything that can be done with JSP XML action tags
must be able to be "backed" by Java code.
84. Do you have to clear out and set it to null first before you use the
ServletOutputStream object? If so, why?
Is there anything which a servlet can perform but a JSP cannot and vice versa ?
A JSP is generated into a servlet, so there is very little that one can do, but not the other.
JSPs are generally considered a "convenient" way to write servlets. However, there are
the following differences:
· JSP cannot return binary data. This is because a JSP always calls
response.getWriter(), and returns a JspWriter.
· Servlets cannot readily use JSP Tags. This is somewhat obviously, but
custom tags can sometime include business logic or other functionality that a page
developer would want to call. It technically is possible for a servlet to call a custom tag,
but it is lengthy process.
85. How do I implement synchronization in JSP if I don't want to use
SingleThreadModel interface?
The easiest way of making JSP pages thread safe is to ensure that the server side
variables in your JSP page are defined within the jsp-service method, when it is translated
into a servlet. This is possible if you define variablese within <% %>. Make sure that
you dont use <%! %> , as this is used for defining class level variables of the servlet,
which will obviously not be thread safe.
86. If the output stream was not buffered at the time of transferring the control,
the jsp:forward action will
throw java.lang.IllegalStateException. Why?
The server has already had written out some text or header information to client and thus
cannot send the second HTTP response after the forward action. Make sure you do not set
cookies or write a message to the client before you invoke the forward action within the
JSP page.

30

You might also like