Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

The Life Cycle of A JSP Page: Server-Side Servlet Sun HTML

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 36

JSP

Short for Java Server Page. A server-side technology, Java Server Pages are an extension to
the Java servlet technology that was developed by Sun.
JSPs have dynamic scripting capability that works in tandem with HTML code, separating the
page logic from the static elements -- the actual design and display of the page -- to help
make the HTML more functional (i.e. dynamic database queries).
A JSP is translated into Java servlet before being run, and it processes HTTP requests and
generates responses like any servlet. However, JSP technology provides a more convenient
way to code a servlet. Translation occurs the first time the application is run. A JSP translator
is triggered by the .jsp file name extension in a URL. JSPs are fully interoperable with
servlets. You can include output from a servlet or forward the output to a servlet, and a servlet
can include output from a JSP or forward output to a JSP.
JSPs are not restricted to any specific platform or server. It was orignially created as an
alternative to Microsoft's ASPs (Active Server Pages). Recently, however, Microsoft has
countered JSP technology with its own ASP.NET, part of the .NET initiative.

The Life Cycle of a JSP Page


A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of
JSP pages (in particular the dynamic aspects)
When a request is mapped to a JSP page, it is handled by a special servlet that first checks
whether the JSP page's servlet is older than the JSP page. If it is, it translates the JSP page
into a servlet class and compiles the class. During development, one of the advantages of
JSP pages over servlets is that the build process is performed automatically.
Translation and Compilation
During the translation phase, each type of data in a JSP page is treated differently. Template
data is transformed into code that will emit the data into the stream that returns data to the
client. JSP elements are treated as follows:
Directives are used to control how the Web container translates and executes the
·       
JSP page.
Scripting elements are inserted into the JSP page's servlet class. See JSP
·       
Scripting Elements for details.
Elements of the form <jsp:XXX ... /> are converted into method calls to JavaBeans
·       
components or invocations of the Java Servlet API.
For a JSP page named pageName, the source for a JSP page's servlet is kept in the file
J2EE_HOME/repository/host/web/
    context_root/_0002fpageName_jsp.java
For example, the source for the index page (named index.jsp) for the date localization example
discussed at the beginning of the chapter would be named
J2EE_HOME/repository/host/web/date/_0002findex_jsp.java
Both the translation and compilation phases can yield errors that are only observed when the
page is requested for the first time. If an error occurs while the page is being translated (for
example, if the translator encounters a malformed JSP element), the server will return a
ParseException,and the servlet class source file will be empty or incomplete. The last
incomplete line will give a pointer to the incorrect JSP element.
If an error occurs while the JSP page is being compiled (for example, there is a syntax error in
a scriptlet), the server will return a JasperException and a message that includes the name of
the JSP page's servlet and the line where the error occurred.
Once the page has been translated and compiled, the JSP page's servlet for the most part
follows the servlet life cycle described in the section Servlet Life Cycle:
1.    If an instance of the JSP page's servlet does not exist, the container:
a.    Loads the JSP page's servlet class
b.    Instantiates an instance of the servlet class
c.    Initializes the servlet instance by calling the jspInit method
2.    Invokes the _jspService method, passing a request and response object.
If the container needs to remove the JSP page's servlet, it calls the jspDestroy method.
Execution
You can control various JSP page execution parameters using by page directives. The
directives that pertain to buffering output and handling errors are discussed here.
Buffering
When a JSP page is executed, output written to the response object is automatically buffered.
You can set the size of the buffer with the following page directive:
<%@ page buffer="none|xxxkb" %>
A larger buffer allows more content to be written before anything is actually sent back to the
client, thus providing the JSP page with more time to set appropriate status codes and
headers or to forward to another Web resource. A smaller buffer decreases server memory
load and allows the client to start receiving data more quickly.
Handling Errors
Any number of exceptions can arise when a JSP page is executed. To specify that the Web
container should forward control to an error page if an exception occurs, include the following
page directive at the beginning of your JSP page:
<%@ page errorPage="file_name" %>
The Duke's Bookstore application page initdestroy.jsp contains the directive
<%@ page errorPage="errorpage.jsp"%>
The beginning of errorpage.jsp indicates that it is serving as an error page with the following
page directive:
<%@ page isErrorPage="true|false" %>
This directive makes the exception object (of type javax.servlet.jsp.JspException) available to the
error page, so that you can retrieve, interpret, and possibly display information about the
cause of the exception in the error page.

Note: You can also define error pages for the WAR that contains a JSP page. If error pages
are defined for both the WAR and a JSP page, the JSP page's error page takes precedence.
 
What is JSP?
With JSP, fragments of Java code embedded into special HTML tags are presented to a JSP engine. The JSP
engine automatically creates, compiles, and executes servlets to implement the behavior of the combined HTML
and embedded Java code.
Previous lessons have explained the use of the following syntax elements:
·        Output comments
·        Hidden comments
·        Declarations
·        Expressions
This lesson will discuss scriptlets.
What is a Scriptlet?
The scriptlet is the workhorse of JSP.  It is basically some Java code contained within a special JSP tag,
embedded in an HTML page.
A scriptlet can contain any number of language statements, variable or method declarations, or expressions.
What is the syntax?
The syntax of a scriptlet is as follows:
 
<% code fragment %>
What are they good for?
According to Sun, you can do any of the following things using scriptlets:
·        Declare variables or methods to use later in the file (also see declarations in an earlier lesson).
·        Write expressions valid in the page scripting language (also see expressions in an earlier lesson).
·        Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.  (This tag
will be discussed in detail in a subsequent lesson.)
·        Write any other statement that is valid in the page scripting language (if you use the Java
programming language, the statements must conform to the Java Language Specification).
Other stuff
You must write any needed plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
When are scriptlets executed?
Scriptlets are executed 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.
Sample Scriptlets
Some unrelated samples of scriptlets follow:
 
<% c = a/b; %>
This scriptlet divides the variable a by the variable b and assigns the quotient to c.
 
<% myDate = new java.util.Date(); %>
This scriptlet instantiates a new object of the Date class and assigns the reference to that object to the variable
named myDate.
The two scriptlets shown above are very straightforward.  They consist simply of a simple Java expression
embedded inside a scriptlet tag.
Have you noticed anything odd?
Those of you who are familiar with HTML and XML may have noticed something a little odd about this syntax.  In
particular, the typical syntax of HTML and XML elements is as follows:
 
<tagName attribute=attributeValue>
  Element Content
</tagName>
In other words, a typical element in HTML or XML consists of
·        A beginning tag with optional attribute values
·        The element content
·        An ending tag
Some HTML elements don't require an end tag
Of course, in HTML, there are some elements that don't require an end tag.  In XML jargon, those elements are
not well-formed.
XML has special format for empty elements
In XML, if the element doesn't contain any content, there is a special format that can be used which, in effect,
causes the beginning tag to also serve as the end tag.
However, what we have seen so far regarding JSP doesn't match any of these.  I won't bore you with the details,
but if this is of interest to you, you might want to pursue the matter further by taking a look at some of my XML
articles.
Another sample scriptlet
That brings me to another sample scriptlet.  The following sample consists of two scriptlets.  One forms the
beginning of a Java for loop, and the other forms the end of a Java for loop.  The body of the loop consists of a
standard HTML break tag <br> and a JSP expression.
 
<% for (int i=0; i<11; i++) { %>
      <br> 
      <%= i %>
<% }//end for loop %>
More effort required
As you can see from this sample, sometimes a lot more effort is required to write scriptlets than would be
required to write the same Java code in a Java application, bean, applet, or servlet.
In addition, if you make an error in your Java code, you don't get much in the way of helpful compilation error
messages to help you correct the problem.  (At least that is true with the JSWDK from Sun that I am currently
using.)
Using beans
This will lead us later to the concept of packaging the bulk of our Java code in servlets or Java Beans, and to
use JSP to execute them.
The results produced by the beans will be embedded in the HTML-encoded text stream.  In other words, the
combined use of JSP, servlets, and Java Beans will give us the best of all three worlds.
Sample JSP Page
Is a sample JSP page that contains the three sample scriptlets discussed above, along with some JSP
declarations and JSP expressions.
I have highlighted the scriptlets in boldface to make them easier to identify.
Standard Java comments
Note that in addition to using the comment tags discussed in an earlier lesson, it is also acceptable to use
standard Java comments inside the scriptlet, as evidenced by the last scriptlet shown in
shows the output produced by loading this JSP page into my Netscape 4.7 browser while running the Sun
JSWDK-1.0.1 server.
JSP Syntax Summary
In this and previous lessons, we have learned about the following JSP syntax:
Output comments:
<!-- comment
[ <%= expression %> ] -->
Hidden comments:
<%-- hidden comment --%>
Declarations:
<%! declarations %>
Expressions:
<%= expression %>
Scriptlets:
<% code fragment %>
 
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 -->
 
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 clent in the page source --%>
</body>
</html>
 
 
 
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 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 
 
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; %>
 
 
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.
 
implicit objects
 
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
application
out
config
page
exception
 
 
 
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 completely with in the web container. When a sendRedirect 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 completely 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. 
 
The different scope values for the <jsp:useBean>
 
A: The different scope values for <jsp:useBean> are
 
1. page
2. request
3. session
4. application
 
 
The life-cycle methods in JSP
 
A: The generated servlet class for a JSP page implements the HttpJspPage interface of the
javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which in
turn extends the Servlet interface of the javax.servlet package. The generated servlet class
thus implements all the methods of 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 interface specifically for the Jsp pages serving HTTP requests. This interface
declares one method _jspService().
The 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.
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.
 
 
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 following scriptlet
at the beginning of your JSP pages to prevent them from being cached at the browser. You
need both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
 
How 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.
 
 
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 .
 
 
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.
 
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 >
 
 
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)% >" >
 
 
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 browser, 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 variable
declared in scriplet part?
 
A: Variable declared inside declaration part is treated as a global variable that means after
converting 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 declares a variable inside a scriplet that variable will
be declared inside a service method and the scope is with in the service method. 
 
 
 
Structure of a JSP
 
Similar to a HTML document.
Four basic tags:
·        Scriplet
·        Expression
·        Declaration
·        Definition
 

Why use JSP Technology?


Convenient:
We already know Java and HTML!
Provides an extensive infrastructure for:
Tracking sessions.
Managing cookies.
Reading and sending HTML headers.
Parsing and decoding HTML form data.
Efficient:
Every request for a JSP is handled by a simple Java thread. Hence, the time to execute a
JSP document is not dominated by starting a process.
Portable
JSP follow a well standardized API.
The Java VM which is used to execute a JSP file is supported on many architectures and
operating systems.
Inexpensive
There are a number of free or inexpensive Web Servers that are good for commercial-quality
websites.
Helium uses Apache Tomcat.
 

What are Java Server Pages?


The Java Server Pages technology combine Java code and HTML tags in the same

document to produce a JSP file.  


 
Using JSPs to Manage Sessions
 
Problem: HTTP is stateless. Each new request that the Web server receives starts with a
blank slate.
Solution: JSP provides an implicit object session.
Sessions store and retrieve session attributes.
Session attributes are remembered using either cookies or by passing request parameters.
The session object implements methods from the interface javax.servlet.http.HttpSession.
Managing Sessions
Relevant methods:
Request Parameters
JSP provides an implicit object request that stores attributes related to the request for the JSP
page.
For example,
http://localhost/example.jsp?param1=hello&param2=world

JSP Comments
Regular Comment
< ! -- comment -- >
Hidden Comment
< % -- comment -- % >

Structure of a JSP document


Scriptlet Tag
< % code  % >
Imbeds Java code in the JSP document that will be executed each time the JSP page is
processed.

Expression Tag
< %= expression % >
Imbeds a Java expression that will be evaluated every time the JSP is processed.
Note: no semi-colon “;” following expression.

Declaration Tag
< %! declaration % >

Imbeds Java declarations inside a JSP document.  


Directive Tag
< % @ directive % >
Directives are used to convey special processing information about the page to the JSP
container.
Directive are defined in the web.xml file.

 
 
JSP Tags
< jsp:property  / >
property is defined in Tag Library Definition files.
JSP Tag reference: http://java.sun.com/products/jsp/syntax/1.2/syntaxref12.html
Actions
1.    < jsp:usebean >
2.    < jsp:setProperty >
3.    < jsp:getProperty >
4.    < jsp:include >
5.    < jsp:forward >
6.    < jsp:param >
7.    < jsp:plugin >

Implicit Objects
1.    Application
2.    config
3.    exception
4.    out
5.    page
6.    Request
7.    response
8.    session
 

Attributes Of Page Directive


1.    language
2.    extends
3.    import
4.    session
5.    is Thread Safe
6.    info
7.    error page
8.    is error page
9.    content type

What is a output comment?


A comment that is sent to the client in the viewable page source. The JSP engine handles an
output comment as un-interpreted 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.
 

What are context initialization parameters?


Context initialization parameters are specified by the <context-param> in the web.xml file,
these are initialization parameter for the whole application and not specific to any servlet or
JSP.
 

What is a translation unit?


JSP page can include the contents of other HTML pages or other JSP files. This is done by
using the include directive. When the JSP engine is presented with such a JSP page it is
converted to one servlet class and this is called a translation unit, Things to remember in a
translation unit is that page directives affect the whole unit, one variable declaration cannot
occur in the same unit more than once, the standard action jsp:useBean cannot declare the
same bean twice in one unit.

 
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. Custom tags and beans accomplish the same goals – encapsulating
complex behavior into simple and accessible forms. There are several differences:
o    Custom tags can manipulate JSP content; beans cannot.
o    Complex operations can be reduced to a significantly simpler form with custom tags than
with beans.
o    Custom tags require quite a bit more work to set up than do beans.
o    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.
o    Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x
versions.
 

Is JSP technology extensible?


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

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.
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: , , , , ,
What is the difference between and
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.
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 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.
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.
Question: How can I enable session tracking for JSP pages if the browser has disabled
cookies?
Answer: 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());
Question: What are the implicit objects in JSP & differences between them?
Answer: There are 9 Implicit Objects defined in JSP are :
application, config, exception, out, page, pageContext, request, response and session.

The main difference between these Objects lies in their scope and the data they handles.

_________________

JSP Implicit Objects :-

S.No Implici Object Class or Interface Description


1. application interface (javax.servlet.ServletContext) Refers to the web application's enviornment
2. session interface ((javax.servlet.http.HttpSession) Refers to the User's session
3. request interface ((javax.servlet.http.HttpServlet.Request) Refers to the current request page
4. response interface ((javax.servlet.http.HttpServlet.Response) Refers to the current response to the
client
5. out Class (javax.servlet.jsp.JspWriter) Refers to the output stream for hte page
6. page Class (java.lang.Object) Refers to the page's servlet instance
7. pageContext Class (javax.servlet.jsp.PageContext) Refers to the page's enviornment
8. config Interface (javax.servlet.ServletConfig) Refers to the servlet's configuration
9. exception Class (java.lang.Throwable) Used for error handling
Question: Can one JSP or Servlet extend another Servlet or JSP?
Answer: A servlet cant extend a class or servlet a it already extends HTTpServlet.....But if you can
make the servlet work withought extending HTTpSERvlet then u can do that...but then as far as i know it
wontb a servlet and will be somple classjsp can exend a class.
Question: How do you call stored procedures from JSP?
Answer: Creating a Stored Procedure or Function in an Oracle Database
-------------------------------------------------------------

A stored procedure or function can be created with no parameters, IN parameters, OUT

parameters, or IN/OUT parameters. There can be many parameters per stored procedure
or function.

An IN parameter is a parameter whose value is passed into

a stored procedure/function module. The value of an IN parameter is a constant; it can't


be changed or reassigned within the module.

An OUT parameter is a parameter whose value is passed

out of the stored procedure/function module, back to the calling PL/SQL block. An OUT
parameter must be a variable, not a constant. It can be found only on the left-hand side of an assignment
in the module. You cannot assign a default value to an OUT parameter outside of the module's body. In

other words, an OUT parameter behaves like an uninitialized variable.

An IN/OUT parameter is a parameter that functions as an IN or an OUT

parameter or both. The value of the IN/OUT parameter is passed into the

stored procedure/function and a new value can be assigned to the parameter and

passed out of the module. An IN/OUT parameter must be a


variable, not a constant. However, it can be found on both sides of an assignment. In other words, an

IN/OUT parameter behaves like an initialized variable.

This example creates stored procedures and functions demonstrating each type of

parameter.

try {

// To create a connection to an Oracle database,

// see e235 Connecting to an Oracle Database


Statement stmt = connection.createStatement();

//**************************************************************
// Create procedure myproc with no parameters
String procedure =
"CREATE OR REPLACE PROCEDURE myproc IS "
+ "BEGIN "
+ "INSERT INTO oracle_table VALUES('string 1'); "
+ "END;";
stmt.executeUpdate(procedure);
//**************************************************************

// Create procedure myprocin with an IN parameter named x.

// IN is the default mode for parameter, so both `x VARCHAR' and `x IN VARCHAR' are
valid
procedure =
"CREATE OR REPLACE PROCEDURE myprocin(x VARCHAR) IS "
+ "BEGIN "
+ "INSERT INTO oracle_table VALUES(x); "
+ "END;";
stmt.executeUpdate(procedure);

//**************************************************************

// Create procedure myprocout with an OUT parameter named x


procedure =
"CREATE OR REPLACE PROCEDURE myprocout(x OUT VARCHAR) IS "
+ "BEGIN "
+ "INSERT INTO oracle_table VALUES('string 2'); "
+ "x := 'outvalue'; " // Assign a value to x
+ "END;";
stmt.executeUpdate(procedure);

//**************************************************************

// Create procedure myprocinout with an IN/OUT parameter named x;

// x functions as an IN parameter and also as an OUT


parameter
procedure =
"CREATE OR REPLACE PROCEDURE myprocinout(x IN OUT VARCHAR) IS "
+ "BEGIN "

+ "INSERT INTO oracle_table VALUES(x); " // Use x as IN parameter

+ "x := 'outvalue'; " // Use x as OUT parameter


+ "END;";
stmt.executeUpdate(procedure);

//**************************************************************
// Create a function named myfunc which returns a VARCHAR value;

// the function has no parameter


String function =
"CREATE OR REPLACE FUNCTION myfunc RETURN VARCHAR IS "
+ "BEGIN "
+ "RETURN 'a returned string'; "
+ "END;";
stmt.executeUpdate(function);

//**************************************************************

// Create a function named myfuncin which returns a VARCHAR value;

// the function has an IN parameter named x


function =
"CREATE OR REPLACE FUNCTION myfuncin(x VARCHAR) RETURN VARCHAR IS "
+ "BEGIN "
+ "RETURN 'a return string'||x; "
+ "END;";
stmt.executeUpdate(function);

//**************************************************************

// Create a function named myfuncout which returns a VARCHAR value;

// the function has an OUT parameter named x whose value is

// returned to the calling PL/SQL block when the execution of the function ends
function =
"CREATE OR REPLACE FUNCTION myfuncout(x OUT VARCHAR) RETURN VARCHAR IS "
+ "BEGIN "
+ "x:= 'outvalue'; "
+ "RETURN 'a returned string'; "
+ "END;";
stmt.executeUpdate(function);

//**************************************************************

// Create a function named myfuncinout that returns a VARCHAR value;

// the function has an IN/OUT parameter named x. As an IN parameter, the


value of x is

// defined in the calling PL/SQL block before it is passed in eyfuncinout

// function. As an OUT parameter, the new value of x, `x value||outvalue', is also

// returned to the calling PL/SQL block when the execution of the function ends.
function =
"CREATE OR REPLACE FUNCTION myfuncinout(x IN OUT VARCHAR) RETURN VARCHAR IS "
+ "BEGIN "
+ "x:= x||'outvalue'; "
+ "RETURN 'a returned string'; "
+ "END;";
stmt.executeUpdate(function);
//**************************************************************
} catch (SQLException e) {
}
Question: How do I prevent the output of my JSP or Servlet pages from being cached
by the browser?
Answer: 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
%>
Question: What is JSP?

Answer: 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 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.
 
 
Question: How can we move from one JSP page to another (mean using what
technique?)
Answer: A Jsp can either "redirect "or "dispatch " to another JSP.
// use this if you just want to invoke another
//JSP
response.sendRedirect("Jsp URL");

// use this if you want to pass info from one


// jsp to another jsp

RequestDispatcher dispatch = request.getRequestDispatcher("The Jsp File Name");

dispatch.forward(request, response);
Question: What is difference between scriptlet and expression?
Answer: What ever we write inside the scriptlet thats become a part of service mathod of jsp generated
serlet. and executed with in service method. and treated as html info. and what ever we write inside
expression its is wirteen out side of service methods and become part of global inside class of servlet
and expression is used for declarion of methods and variable and treated as java code exeution parts.

Submitted by Pushpendra Singh (Pushpendra.Singh@india.rsystems.com)

______________

With expression in jsp ,the results of evaluating the expression r converted to a string and directly
included within the output page.Typically expressions r used to display simple values of variables or
return values by invoking a bean's getter methods.Jsp expressions begin within tags and do not include
semicolons.

But 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 declare variables
or methods to use later in the file,write expressions valid in the page scripting language.
Scriptlet:

=> any java code embedded into a html page<% %>


=> it can have declaration,valid _expression
=> executed at the request time

Expression:
=> any valid _expression <%= %>
=> implicit object like request,response & out are used in the expression
=> evaluvated at run time
Question: What JSP lifecycle methods can I override?
Answer: You cannot override the _jspService() method within a JSP page. You can however, override
the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating
resources like database connections, network connections, and so forth for the JSP page. It is good

programming practice to free any allocated resources within jspDestroy().

The jspInit() and jspDestroy() methods are each executed just once during the lifecycle
of a JSP page and are typically declared as JSP declarations:

<%!
public void jspInit() {
...
}
%>
<%!
public void jspDestroy() {
...
}
%>
Question: How do you connect to the database from JSP?

Answer: A Connection to a database can be established from a jsp page

by writing the code to establish a connection using a jsp scriptlets.

<%@ page language="java" contentType="text/html"


import="java.sql.*,java.sql.Statement %>

<%
//load the Oracle JDBC driver or any other driver for a specific
vendor
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//open a connection to the "scott" database or other database which you

have created. You should provide the username and password as part of this connection

string. Here the username and password are scott and tiger. Connection con=
DriverManager.getConnection("jdbc:odbc:scott","scott","tiger");

//create a statement object for sending SQL queries


Statement stmt = con.createStatement();

//place query results in a ResultSet object

//To get all projects of a particular project leader.


ResultSet res = stmt.executeQuery(" select * from employee");

String ename=null;

%>
Further then you can use the resultset object "res" to read data in the following way.

<%
while(res.next())
{
ename=res.getString("ename");
%>
Question: What is the difference between include directive & jsp:include action?
Answer: Difference between include directive and <jsp:include>

1.<jsp:include> provides the benifits 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 <jsp:include> also supports the use of request time attributes valus for
dynamically specifying included page which directive does not.
3.the include directive can only incorporate contents from a static document.
4.<jsp:include> can be used to include dynamically generated output eg. 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.
Question: How are the implicit object made available in the jsp file? Where are they
defined?
Answer: There are nine implicit variables in JSP : application
,session,request,response,out,page,pageContext,config,exception

The objects that these variables refer created by servlet container and are call implicit Objects: They
are as follows:

ServletContex ,HttpSession ,HttpServletRequest, HttpServetResponse, JspWriter, ServletConfig,Object

In _jspService() method of generated servlet of JSP you can implicity find these variables
Question: Can you make use of a ServletOutputStream object from within a JSP page?

Answer: 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" %>


Question: How do you pass control from one JSP page to another?
Answer: 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

Question: What is the difference between JSP forward and servlet forward methods?
Answer: JSP forward forwards the control to another resource available in the same web application
on the same container, where as Servlet forward forwards the control to another

resource available in the same web application or different web app on the same
container....
Question: What are advantages of JSP?
Answer: We can separate the Presentation Logic from Business Logic in JSP'S where as Servlets we
can't make it.

________________

The two main uses of JSPs are:

1) Using jsp's we can separate the presentation logic from business logic very easily(we can also do the
same using the Servlets but difficult)

2) Even a web author can easily develop the code ,in the since a person who doesn’t know anything
about java can also develop the JSPs using the tags.
Question: What is difference between scriptlet and expression?
Answer: Anything that is put in the Jsp Expression tag get evaluated to a string, which, technically
becomes an argument to the println() statement in the generated servlet.( JSP eventually is converted
to a servlet ) otherwise it serves no purpose on its own.

Expression has the following syntax

NO SEMICOLON

Scriptlet:
Question: What is Declaration?

Answer: Declaration declares and defines variables and methods that can be used in
the JSP page.

Example:- <%! int count=0; %>

The variable is initialized only once when the page is first loaded by the JSP engine and retains its value
in subsequent client request.

Note:- Since the declaration contain JAVA declaration , each variable's

declaration must be terminated with a semicolon.


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:

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

<%

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);

%>

You can also use the: <jsp:forward page="/newpage.jsp" />

Also note that you can only use this before any output has been sent to the client. I beleve this is the
case with the response.sendRedirect() method as well. If you want to pass any paramateres then you
can pass using <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" />
</jsp:forward>>
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:

<%-- the scriptlet is now commented out


<%
out.println("Hello World");
%>
--%>

You can also use HTML-style comments anywhere within your JSP page. These comments are visible at
the client. For example:

<!-- (c) 2004 javagalaxy.com -->

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
/**
yet another comment
**/
%>
Where do we use hidden variables and url rewriting? and wat is the difference between
them?

Both hidden variable and URL rewriting are used for session tracking. The only

advantage in hidden variable is that the URL looks neat. In URL rewriting,

each and every variable is added to the URL (called GET parameters).Example:
profile.jsp?name=dilip+surname=iyer
What are Custom tags. Why do you need Custom tags. How do you create Custom
tag?
The most recent version of the JSP specification defines a mechanism for extending the current set of
JSP
tags. It does this by creating a custom set of tags called a tag library. That is what the taglib points to.

The taglib directive declares that the page uses custom tags, uniquely names the

tag library defining


them, and associates a tag prefix that will distinguish usage of those tags. The syntax of the taglib
directive is as follows:

<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>


What is the difference b/w PAGE, APPLICATION and SESSION implicit objects of JSP?
Page: object will be available with in page if we move another page the object will not available.

Session : object will be available with in the session (session time out will available in web.xml) after the
session time out object will not available .

Application: object will be available until we stop the server


 
What is the difference between application server and web server?

Web server is used for web applications whereas application server is used for both
web and enterprise applications.

Example of web server is Tomcat,Resin whereas example of application

server is weblogic,websphere.Webserver is protocol dependent whereas application


server is protocol independent.
How to delete cookies in JSP?
Whenever you want to delete cookies, just set the Maxtime value to 0..

example given below.

Cookie cookie = new Cookie ("myCookie", "theCookieValue");

// Expire in five minutes (5 * 60)


cookie.setMaxTime( 300 );

some... more code here.. or any other page..

// Expire after the browser is closed


// cookie.setMaxTime( -1 );

// Expire right now


// cookie.setMaxTime( 0 );

Can we implements interface or extends class in JSP?


Yes we can do that using <%@ page extend="package.className">
What is the difference between declaring the variables in the scriptlet tags and in the
declaration tags?
Declaring the variables in the scriptlet is gone into the service method when jsp converted into servlet
but in declaration tags goes into the class label variable.
A variable that is declared by using a JSP declaration element end up as an Instance variable in the
genarated servlet.All threads share the instance variable, so if one thread changes its value, it will be
seen by other threads also.

A variable which is declared in scriptlet tag ends up as a local variable in the generated servlet.Each
thread has its own copy of a local variable.In this case, if one thread changes the value of this variable, it
will not effect the other threads.
Can a single JSP page be considered as a J2EE application?
Yes, if its packed as war or if it's directory structure confirms j2ee specifications with a dd
Can a JSP page process HTML FORM data?
Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like
doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the
request implicit object within a scriptlet or expression as:

<%
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intValue();
%>

or

<%= request.getParameter("item") %>


Why should we setContentType() in servlet ?what is the use of that method?
To intimate the browser that which type of content is coming as response,Depending upon the
contentType browser treats with the response.
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
} 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;
}
%>
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:

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

Another Example:

file1.jsp:
<%@page contentType="text/html"%>
<%!
public void test(JspWriter writer) throws IOException{
writer.println("Hello!");
}
%>

file2.jsp

<%@include file="file1.jsp"%>
<html>
<body>
<%test(out);% >
</body>
</html>
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:

<%
//creating a cookie
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>
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" /
What is the Difference between sendRedirect () and Forward?
Forward Request- When we invoke a forward request it is sent to another resource on the server itself,
without the client being informed that a different resource is going to process the request.The process
occurs completly within the web container.

Send-Redirect- When this method is invoked , it causes the web container


to return to the browser indicating that a new URL is requested.Process does not occur just within

web container.

Because the browser issues completly new request any object value that are stored as request
attributes are lost in case of Send Redirect but forward retains that.

N because of the extra round trip redirect is slower than the forward.
How to compile the JSP pages manually in all applications and web servers?
Yes it can be possible,

in order to do so first set u r class path to setenv in weblogic and then

type weblogic. jsp -keep generated jsp file name

this is the procedure to precompile the jsp with out the help of container with web-logic
put all your jsp programs in to the WEB-APS folder of your tomcat directory then run the tomcat server,
then open, test the tomcat server with built-in examples of jsp pages  then change the address to your
jsp pages.
What is the difference between session and cookie?
1. Sessions are stored in the server side whereas cookies are stored in the client side

2. There is a limit to the number of cookies that can be stored with respect to session
How to overwrite the init and destroy method in a JSP page?

We can overwrite the init method in a jsp page by using declaration tag in our JSP page.
We can overwrite by
init by super.init()

and destroy by super. destroy()


What are the differences between JSP LifeCycle and Servlet LifeCycle?
In servlet we can implement init, service and destroy method but in jsp we don’t have any
implementation for that i.e. jsp container taking care of that implementation. Finally only translation
phase is different i.e. jsp converted into servlet.
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.
Suppose we have 1000 rows in the database I need to retrieve 200 rows per page, then
which approach is better either struts based or non struts based it is an interview
question.
In case if you are using MySql database just you need to keep a hidden variable of page no and put the
limit clouse in Sql query.

see as like this

PerPageRecord = 200

RecordStartfrom = (PageNo * PerPageRecord);

SqlString = "select * from table_name limit " + RecordStartfrom + " , " + PerPageRecord;

What is the differene between include directive and include action?

include directive:

<% @ page include="header.jsp" %>

this is content

<% @ page include="footer.jsp" %>

in this case first merge three files then jsp comiler create only one servlet.whenever send the request by
client the wedcontainer execute that file only.this also called as satatic include.it will takes less time.

include tag:
<jsp:include page="/header.jsp" />

this content

<jsp:include page="/footer.jsp"/>

in this case jsp compiler generates the javacode for three servlets.whenever send the request by

server ,the webcontainer executs three servlets and send the response.this is also called
as dynamic include.it will takes more time.
What is jsp:use bean. What are the scope attributes & difference between these
attributes?
What is the difference between a static and dynamic include?
Static incude means files are included at compile time.After inclusion if there is change in source file it
will not reflect that jsp.
Dynamic include means files are included at run time.
If there is any change in source file it will reflected in Jsp
Can a JSP page instantiate a serialized bean?
No problem! The useBean action specifies the beanName attribute, which can be used
for indicating a serialized bean.

For example:

<jsp:useBean id="shop" type="shopping.CD" beanName="CD" />


<jsp:getProperty name="shop" property="album" />

A couple of important points to note. Although you would have to name your serialized file
"filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will
have to place your serialized file within the WEB-INFjspbeans directory for it to be located by the JSP
engine.
What is jsp:use bean. What are the scope attributes & difference between these
attributes?
The <![CDATA[ <jsp:useBean> element locates or
instantiates a JavaBeans component. <![CDATA[ <jsp:useBean> first attempts to

locate an instance of the bean. If the bean does not exist, <![CDATA[ <jsp:useBean>
instantiates it from a class or serialized template. The body of a
<![CDATA[ <jsp:useBean>
element often contains a <![CDATA[ <jsp:setProperty> element that sets property values in

the bean. The body tags are only processed if <![CDATA[ <jsp:useBean>

instantiates the bean. If the bean already exists, the body


tags have no effect.
In Internet explorer if we give a jsp , How the server will know it has to execute? 
After querying the Registery of Server/Machine, In result it is executed with the associated program.

For example whenever we click on any file with .DOC extension it opens with Microsoft Word the same
funda applied on every extension whether it is Desktop application or Web Application/Services.
Where can we find the compiled file of jsp in the directory structure?
Better i know which webserver u r using? i hope u know that any webserver would convert your jsp file
into a java file first compile it into a .class file and then load it in the memory. In a sense, instead of you
doing the work of compiling and loading the file, the webserver does it. Somewhat similar to that of
Servlet concepts. if you are using Apache Tomcat 4.1, the webserver creates the .java file in the classes
directory in c:Tomcat4.1.
How we abort jsp page from a servlet? 
By using the following statement.

RequestDispatcher dispatcher=getServletContext().getServletDispatcher("

packagenamejspfilename.jsp");

What is difference between getAttribute() and getParameter()?


GetAttribute() returns an object so when ever we use a getAttribute() we have to cast the return type that
is we have to convert it to the required type like string or int.getParameter always returns a string.

one more difference is where this 2 methods are used...getAttribute is used to get the values from the
session and getParameter is used to get the values from the form.(html or a jsp file)
What is use of implicit Objects? Why the container is given those one?
Implicit object is a predefine object which is provide by jsp engine. Is machinegun is easy for processing
all basic work.
What is the widely used web programming technology? what is the advantages of JSP
among other technologies?

(a) JSP used in Struts is the most widely used technology to design web applications.
The most important advantage is the platform independency of the java.
Jsp provides a flexible mechanism to produce dynamic content.

Jsp provides following things because of what it is more preferable over other
technologies:

1) Implicit objects.
2) directives
2) actions
3) tag library directives
4) expression language

(b) If you use the jsp technology other than Servlets it improves the performance of the

application why because of in Servlets we implementing business logic and presentation

logic in Servlets only.

Jsp follows the MVC architecture. In jsp we are implementing business logic separately

and presentation logic separately.


How the jsp changes will be effected in servlet file after converting?
Here jsp engine check whether jsp page is older than its servlet page or not and on the basis of this it
it's decide whether changes are needed or not.
What is the need of tag libraries?
Custom tag Libraries allow the java programmer to write code that provides data access and other
services.
TagLibraries cab have access to all the objects available to jsp pages including
request,response,IN,OUT.

Communicate with each other,you can create and initialize a bean(javabean).Create a variable that refers
to that bean in one tag,and then use the bean in other tag.

can be nested with one another,allowing complex interactions with in a jsppage.


When to use struts technology? What type of applications are developed using struts
frame work?
Struts forces us to use MVC architecture. It helps in code maitainability. It also eliminates most of the
repetitive code which is common to most of the web applications.
How do you implement interface in JSP?
U can use the and the Bean that is been referred can implement the Interface.
How can initialize interface in JSP?
We can not initialize the interface in a JSP.
How do u maintain a Session?
we can specify in the function module bdc_open_group

parameter name group.... 'session'

You can maintain session in four ways:

1. Session
2. URL Rewriting
3. Cookies
4. Hidden fields
Can I call an interface in a JSP?

Calling a JSP from a Servlet, or vice-versa, can be done using the RequestDispatcher

interface.

The trick to understanding JSPs is keeping in mind that every JSP is ultimately compiled into a Servlet.

The main thing then becomes understanding the way a servlet


communicates with a JSP and vice-versa. This becomes even more important when sending the output

of a calculation in a servlet to a JSP, or when redirecting a user to a


servlet from a JSP.
What is difference between JSP 1.0 model and JSP 2.0 model?
The main difference between the jsp 1.0 and jsp 2.0 is that jsp 2.0 has feature in that by which we can
generate more syntax errors due to TLD.
How do you prevent the Creation of a Session in a JSP Page and why?
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.
What is the page directive is used to prevent a JSP page from automatically creating a
session?
<%@ page session="false">
<%@ page session="false">
it prevents HttpSession handling in that jsp

and again if we make it session attribute true then we can store client specific information.

What is the architecture of JSP?


Java Server Pages (JSP) are normally used for developing Enterprise Applications and this is called as
JEE - Java Enterprise Edition. JEE is an open standard based platform for developing, deploying and

managing n-tier, web enabled, component based enterprise applications.

1.    MVC(Model-View-Container) / Model 2 Architecture: The most commonly used


architecture for web applications is the Model 2 Architecture-Model is a component that holds the
data (JavaBean)-View is a component that takes care of the presentation (JSP)-Controller is a
component that controls and co-ordinates all the activities (Servlet)

2.    Advantages of MVC architecture:-MaintainabilityThe business logic and

presentation logic are separated The architecture is well known-Reusability-


SecurityAs all the requests are routed through a single point, the Controller can take care of
security instead of each page taking care of the security

What is the difference between, page directive include, action tag include?
One difference is while using the include page directive, in translation time it is creating two Servlets.

But, while using the include action tag, in translation time it is creating only one servlet.
In include directive the contents of included jsp files are copied in current jsp to produce the compiled
servlet but in include action the response of included jsp file is inserted in the response of current jsp
file.
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 >
What are the default objects provided by JSP container? Other than page, request,
session and context objects?
Total default object provided by jsp are
1. request
2. response
3. session
4. application
5. page
6. config
7. pageContext
8. out
9. exception
What is the default scope of jsp tags? 
Page scope is the default scope for jsp tags.
When many Users are browsing the same application at the same time and they click
the "Submit" button will many objects are created for each and every User?
When we implement SingleThread Model one object will be created for every request, otherwise only one
object will be created irrespective of the number of requests.
How do we perform redirect action without using response.sendRedirect (" ");
By using Hyper Link Tag In

HttpServletResponse.getWriter().println("<a href = "Destination url"/>");

Destination url = "<earname><resoursename>"


 

You might also like