You are on page 1of 73

JSP -2

JAVA Server Pages


Designed By:

www.interviewDuniya.com
Agenda
„ Reading url parameters in jsp
„ Reading parameters from form elemets
„ What is a template text
„ JSP predefined objects(out,request,response…)
„ Jsp declarations
„ Jsp elements
„ Directives
„ Action
„ scripting
„ JSP and Tags
„ Jsp and beans
www.interviewDuniya.com
How it works?
„ Unlike javaScript which is interpreted in the web
browser, JSP pages are translated into java
servlets and execute in the servlet engine..
„ All the work is done on the server and all the
browser see is ordinary HTML.

www.interviewDuniya.com
Steps..
„ A JSP page is written and stored in the
document tree of a Web server, usually as a file
with name ending in .jsp
„ The web server receives a request for the
document. Since the name ends in .jsp, it
forwards the request to the servlet engine
„ The servlet engine passes the request on to the
JSP engine, which is typically a servlet itself.

www.interviewDuniya.com
The last step…
„ The JSP engine determines whether the .jsp file
is newer than the servlet class that implements
if.
„ If this is the case, it parses the .jsp file and creates
java source code for the equivalent servlet.
„ It then compiles the servlet and causes the servlet
engine to load and execute it.

www.interviewDuniya.com
Remember…
„ When a .jsp file is first requested from a web
browser, the JSP engine compares its timestamp
with the timestamp on the generated servlet
class.
„ If the class is older(or non existent), the JSP
engine creates the java source code for the
servlet and compiles it.
„ The generated class is then loaded as any other
servlet would be.

www.interviewDuniya.com
The JSP Syntax
„ Inline Java code delimited by <% and %>.
„ Also printing of expressions as text by using <%= %>.
„ Special tags to declare class wide variables and methods.
„ Special tags to use with JavaBeans.
„ Special tags to expose JSP services.
„ JSP directives to specify.
„ Interfaces implemented by the Servlet, classes it extends,
packages to import etc.

www.interviewDuniya.com
JSP Directives and Scripting
Elements
„ Directives <%@ directive %>
„ Declarations <%! declaration %>
„ Expressions <%= expression %>
„ Code Fragment/Scriptlet <% code fragment %>
„ Comments <%-- comment --%>

www.interviewDuniya.com
Servlets and JSP

„ Servlets
„ simple "HelloWorld" servlet, that also prints the
current date.

www.interviewDuniya.com
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>HelloWorld</TITLE></HEAD>");
out.println("<BODY>"); out.println("<H1>Hello World</H1>");
out.println("Today is: " + (new java.util.Date().toString()) );
out.println("</BODY></HTML>");
} // doGet }
// HelloWorld www.interviewDuniya.com
JSP
The same page as above using JSP looks as
shown below:
<HTML>
<HEAD>
<TITLE>Hello World</TITLE>
</HEAD> <BODY>
<H1>Hello World</H1>
Today is: <%= new java.util.Date().toString() %>
</BODY>
</HTML>

www.interviewDuniya.com
Elements of JSP

„ Whenever a .jsp is requested for the first time,


the server does the following:
„ 1. Translates the .jsp page into a servlet
2. Compiles the servlet into a class file
3. Executes the servlet (response is sent to the
client)
„ Subsequent requests (as long as the .jsp page is
unchanged) use the same loaded class file.

www.interviewDuniya.com
Anatomy of a JSP Page

„ A JSP page is a mixture of standard HTML tags,


web page content, and some dynamic content
that is specified using JSP constructs.
„ Everything except the JSP constructs is called
Template Text.

www.interviewDuniya.com
Template text and JSP elements

www.interviewDuniya.com
Template text(html/wml/xml)
„ Everything in the page that isn't a JSP element is
called template text.
„ Template text can be any text: HTML, WML,
XML, or even plain text.
„ but JSP has no dependency on HTML; it can be
used with any markup language. Template text is
always passed straight through to the browser.
„ When a JSP page request is processed, the
template text and dynamic content generated by
the JSP elements are merged, and the result is
sent as the response to the browser.
www.interviewDuniya.com
JSP Processing

Refer the JSP_DAY_1 SLIDE

www.interviewDuniya.com
JSP Constructs
1. JSP Comments: Different from HTML comments
„ <!-- an HTML comment -->
„ <%-- a JSP comment --%>
„ JSP comments are used for documenting JSP code and are
not visible client-side (using browser's View Source option)
where as HTML comments are visible.

2. (JAVA) Expressions
„ <%= some_java_expression %>
„ Example:
<%= new java.util.Date().toString() %>
„ Output of the expression is placed in the HTML
template at the same location.
www.interviewDuniya.com
JSP Elements
scriplets

www.interviewDuniya.com
Jsp scripting elements
„ There are three types of scripting elements in JSP:
„ Scriptlets—Scriptlets can contain Java code. This is the
most general of all the scripting elements.
„ Declarations—Declares a variable or a method for use
in your code.
„ Expressions—Contains a Java expression that the
server evaluates. The result of the expression is inserted
into the Web page.

www.interviewDuniya.com
Scriptlets

„ Scriptlets let the developer place inline Java code


inside the HTML
„ General syntax: <% Java code %>
„ <% i++; %>

„ Expression placement lets the developer place a


Java expression (converted to a String) inline
with the HTML
„ General syntax <%= expression %>
„ <%= new Date() %>

www.interviewDuniya.com
Scriptlets and Conditional HTML
„ Scriptlets can be used to implement conditional
HTML
<% if(variable ) { %>
<h1> variable is true </h1>
<% } else { %>
<h1> variable is false </h1>
<% } %>

www.interviewDuniya.com
Scriptlets and Looping

„ Scriptlets can be used to implement loops


inside the HTML.

<% for(int k = 0 ; k < 10 ; k++ ) { %>


<h1> variable’s value is <%= k %> </h1>
<% } %>

"out" variable can be used to generate HTML


output from within a scriptlet

www.interviewDuniya.com
Scriplets examples

„ JSPscriptlet.jsp
„ http://localhost:8080/examples/jsp/JSPscriptle
t.jsp?bgColor=black

„ JSPExpressions.jsp

www.interviewDuniya.com
Example of mixing scriptlets and HTML

<%
if ( hello ) {
%>
<P>Hello, world
<%
} else {
%>
<P>Goodbye, world
<%
}
%>

www.interviewDuniya.com
Scriplets examples
3. Scriptlets
„ Scriptlets are arbitrary pieces of Java code inserted in the
page using the format:
„ <% some_java_code %>
„ Examples
„ ScripletsEg.jsp
„ Enter the code above in a file called, bgcolor.jsp and run it
using the following URLs:
„ http://server.address/youraccount/bgcolor.jsp?COLOR=FF
0000
http://server.address/youraccount/bgcolor.jsp?COLOR=00
FF00
http://server.address/youraccount/bgcolor.jsp
www.interviewDuniya.com
Scriplets example 2
„ ScripletsEg1.jsp
„ http://server.address/youraccount/bgcolor2.jsp?COLOR=FF
0000
http://server.address/youraccount/bgcolor2.jsp?COLOR=00
FF00
http://server.address/youraccount/bgcolor2.jsp

www.interviewDuniya.com
3. Scriptlets, contd.

„ Using Arrays
„ One can easily use scriptlets to loop over arrays.
In this example, the user is presented with
choice boxes. When s/he presses the submit
button, the choices are displayed.
„ Example: choices.jsp

www.interviewDuniya.com
4. Declarations

„ <%! some JAVA declarations %>


„ You can define variables and/or methods.
„ Example1-declare.jsp
„ The following JSP page illustrates the use of a
counter variable as well as a method (that sets
the color of text to a random color) using the
JSP declaration construct.

www.interviewDuniya.com
Jsp declarations contd…
„ Example 2-declare1.jsp
„ Here we are declaring a Date variable
theDate, and the method getDate.

www.interviewDuniya.com
Comments in JSP
„ There are two types of comments in JSP.
„ HTML comments that should arrive to the client's
browser.
„ These comments can contain JSP code and Scriptlets that are
executed.
„ <!-- <% out.print("My comment"); %> -->
„ Comments to the JSP page itself.
„ These comments and their content are not interpreted and
will not arrive to the client.
„ <%-- anything but a closing --%> ... --%>

www.interviewDuniya.com
Expression

ƒ <%= 1+2 %> or <%= mystring %>


ƒ must be complete valid java expression that results in
or can be converted to a string.
ƒ all JSP implicit variables are visible in an expression
element

www.interviewDuniya.com
JSP Objects and
Scopes

www.interviewDuniya.com
JSP Objects and Scopes

„ JSP objects can be either:


explicit--Explicit objects are declared and created within
the code of your JSP page, accessible to that page and
other pages according to the scope setting you choose.
„ or:

implicit--Implicit objects are created by the underlying JSP


mechanism and accessible to Java scriptlets or
expressions in JSP pages according to the inherent
scope setting of the particular object type.

www.interviewDuniya.com
Explicit Objects
„ Explicit objects are typically JavaBean instances that are
declared and created in jsp:useBean action
statements. The jsp:useBean statement and other
action statements are described in "JSP Actions and the
<jsp: > Tag Set", but here is an example:
<jsp:useBean id="pageBean" class="mybeans.NameBean"
scope="page" />
„ This statement defines an instance, pageBean, of the
NameBean class that is in the mybeans package.
The scope parameter is discussed in "Object Scopes".

www.interviewDuniya.com
Explicit Objects
„ You can also create objects within Java scriptlets
or declarations, just as you would create Java
class instances in any Java program.

www.interviewDuniya.com
Predefined Objects /Implicit
Objects
„ There are some pre-defined Java
variables/objects available for use in expressions
(provide access to important servlet
functionality):

www.interviewDuniya.com
Predefined /implicit objects..
„ out: The output stream to collect dynamic data
to be mixed into the final Web document.
„ this: The instance of the special Servlet class.
„ request: An HttpServletRequest object
representing the request received from the Web
browser.
„ response: An HttpServletResponse object
representing the response to be delivered back
to the Web browser.

www.interviewDuniya.com
Predefined objects..
„ session: An HttpSession object representing the
concept of linking multiple trips of requests and
response into a single process unit.
„ application: A ServletContext object
representing the concept of grouping Servlets
into a single application.
„ config: A ServletConfig object.
„ pageContext: A PageContext object.

www.interviewDuniya.com
Some examples of predefined
objects
„ PredefinedObejcts1.jsp
„ http://localhost:8080/examples/jsp/PredefinedObj
ects1.jsp?INFO=helloThere

„ PredefinedObjects.jsp

www.interviewDuniya.com
The "session" Object
„ session: A object provided by the JSP
server to hold information and methods
common to all JSP pages running under
one session.
„ The session object must be an instance of a
class that implements the
javax.servlet.http.HttpSession interface

www.interviewDuniya.com
Some session objects methods
„ getAttribute(): Returns the object that is associated to
the specified key string. defined in the session.
„ getAttributeNames(): Returns an Enumeration object
that contains all the key strings defined in the session.
„ getCreationTime(): Returns the time when this
session was created, measured in milliseconds since
midnight January 1, 1970 GMT.
„ getId(): Returns the session ID as a string.
„ setAttribute(): Associate an object with the specified
key string and store them to this session.

www.interviewDuniya.com
Summary of JSP Constructs

1. Expressions
2. Scriptlets
3. Declarations
4. Availability of implicit and explicit objects

www.interviewDuniya.com
JSP Elements

„ There are three types of JSP elements you can


use:
„ Directive(page,include and taglib)
„ action

„ and scripting.(Adding Java to a plain HTML page)

www.interviewDuniya.com
JSP Elements
directive

www.interviewDuniya.com
Jsp Directives
„ JSP Directives

„ <%@ directive attribute="value" %>


„ <%@ directive attr1="value" attr2="value"
... attrN="value" %>
„ Directives are used to specify the structure of
the resulting servlet.

www.interviewDuniya.com
Directives …
„ Directives are used during the translation phase
„ all other elements are used during request
processing phase

www.interviewDuniya.com
Types of directives
„ There are three directives:
„ page
„ include
„ <%@ include file="filename.jsp" %>
„ taglib

www.interviewDuniya.com
Page directive
„ The page Directive
„ There are 11 specifiable attributes for this
directive: import, contentType, isThreadSafe,
session, buffer, autoflush, extends, info,
errorPage, and language

www.interviewDuniya.com
Directives…
„ language= “java”
„ contentType= “text/html”
„ import=“java.util.Date, java.util.DateFormat” {may have
more than one importassignments via multiple page
directives}
„ session=“true” (if set to false, the implicit session variable
is not available to scripting elements)
„ isErrorPage= “false” (set to true if this page is used as
anerror page, and it will have the implicit exception variable
available to scripting elements)
„ errorPage=“…” (no default; page-relative or context-
relative URI to redirect toin case exception thrown)

www.interviewDuniya.com
Directives..
„ autoFlush=“true” (if false, throws exception when buffer is
full)
„ buffer=“8kb” (defines size of buffer; “none” to disable
buffering)
„ info=“…” (no default; used by server administrative tool as
a description ofthe jsp page)
„ isThreadSafe= “true” (if set to false, then will
useSingleThreadModel)
„ extends=“…” (no default; fully qualified classname to
extend; class must implement JspPage or HttpJspPage
interface)
„ uri=“…” (mandatory; no default; either a symbolic name for
the tag library in the web.xml file or a page- or context-
relative uri for the library’sTLD or JAR file)

www.interviewDuniya.com
Examples page directive
„ //example import
„ <%@ page import="java.util.*" %>
„ //example contentType
„ <%@ page contentType="text/html" %>
„ //example for non error page
„ <%@ page isErrorPage=false %>
„ //example for a thread safe JSP
„ <%@ page isThreadSafe=true %>

www.interviewDuniya.com
Examples of directives
„ Error pages: callDivison.jsp, ErrorPageD.jsp
„ ThrowException.jsp , ErrorPage.jsp

www.interviewDuniya.com
Examples page directive
„ <%@ page language="java" contentType="text/html" %>
<%@ page contentType="application/vnd.ms-excel" %>

„ <%@ page import="java.util.*" %> <%@ page


import="java.util.*,java.io.*" %>

www.interviewDuniya.com
Examples page directive
<%@ page language="java" contentType="text/html
import="java.util.*" %>
<HTML> <HEAD>
<TITLE>Hello World</TITLE>
</HEAD> <BODY> <H1>Hello World</H1>
Today is: <%= new Date().toString() %>
</BODY> </HTML>

www.interviewDuniya.com
Examples include directive
„ The include directive is used to physically
include the contents of another file.
„ The included file can be HTML or JSP or
anything else -- the result is as if the original JSP
file actually contained the included text. To see
this directive in action, create a new JSP

www.interviewDuniya.com
Example Include directive
<HTML>
<BODY>
Going to include hello.jsp...<BR>
<%@ include file="hello.jsp" %>
</BODY>
</HTML>
Examples
: page1.jsp,page2.jsp,page3.jsp
Header.html,footer.html

www.interviewDuniya.com
JSP Elements
Action

www.interviewDuniya.com
Difference between directives and
actions
„ JSP also includes actions. As their name implies, actions
let you perform some action. Unlike directives,
actions are re-evaluated each time the page is
accessed.
„ There are two types of actions: custom and standard.
Custom actions are actions you create yourself, and
standard actions come built into JSP. Here are the
standard actions in overview:

www.interviewDuniya.com
Standard Actions
„ JSP standard actions
„ Provide access to common tasks performed in a
JSP
„ Including content from other resources

„ Forwarding requests to other resources

„ Interacting with JavaBeans

„ JSP containers process actions at request time


„ Delimited by <jsp:action> and </jsp:action>

www.interviewDuniya.com
Standard Actions
Action Description
<jsp:include> Dynamically includes another resource in a JSP. As the JSP
executes, the referenced resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static
page. This action terminates the current JSP’s execution.
<jsp:plugin> Allows a plug-in component to be added to a page in the
form of a browser-specific object or embed HTML
element. In the case of a Java applet, this action enables the
downloading and installation of the Java Plug-in, if it is not
already installed on the client computer.
<jsp:param> Used with the include, forward and plugin actions
to specify additional name/value pairs of information for use
by these actions.
Fig. 10.5 JSP standard actions (part 1 of 2).

www.interviewDuniya.com
Standard Actions (cont.)
Action Description
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action
specifies the scope of the bean and assigns it an ID that
scripting components can use to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special
feature of this action is automatic matching of request
parameters to bean properties of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and
converts the result to a string for output in the response.
Fig. 10.5 JSP standard actions (part 2 of 2).

www.interviewDuniya.com
„ <jsp:forward>—Forwards the browser request
for a new Web page to an HTML file, JSP page,
or servlet. In this way, you can delegate how
your Web applications respond to the browser.
„ <jsp:include>— Includes a file or Web
component. Note that <jsp:include> is different
than the include directive because it re-evaluates
the included file every time the page is accessed,
whereas the include directive does not.

www.interviewDuniya.com
„ <jsp:plugin>— Lets you execute applets or
JavaBeans with a plug-in. If the browser doesn't
have the required plug-in module, it will display
a dialog box asking you to download it.
„ <jsp:getProperty>, <jsp:setProperty>, and
<jsp:useBean>—You use these actions with
JavaBean components, as you'll see in the next
slides.

www.interviewDuniya.com
<jsp:forward>
„ The <jsp.forward> tag can be used to cause a
client request to be forwarded to an HTML file,
another JSP file, or a servlet for processing.
„ Whenever the <jsp.forward> tag is encountered
by the JSP engine, the engine forwards the
request that was sent to the JSP file to another
file. The JSP engine doesn't process the
remainder of the current JSP file.

www.interviewDuniya.com
„ When a request is received by a JSP, it can
be forwarded directly onto another relative
URL from the same Web application to be
processed.
„ This must be a resource within the same
Web application. To do this, you can use
the <jsp:forward> standard action.

www.interviewDuniya.com
Forward is not as redirecting..
„ Forwarding is not the same as redirecting.
Redirecting involves the browser being
sent elsewhere for a resource, effectively
resulting in the browser issuing two
requests.
„ Forwarding is the browser requesting a
resource, and the response coming from
the resource that has been forwarded to

www.interviewDuniya.com
<jsp:forward> contd…
„ This action lets you forward the request to
another page. It has a single attribute, page,
which should consist of a relative URL. This
could be a static value, or could be computed at
request time, as in the two examples below.
„ <jsp:forward page="/utils/errorReporter.jsp" />
„ <jsp:forward page="<%= someJavaExpression %>" />
„ <jsp:forward page="gotForwardedRequest.jsp"/>
„ <jsp:forward page="/servlet/login" />

www.interviewDuniya.com
Examples <jsp:forward>

„ <jsp:forward> :
„ forward1.jsp
„ forward2.jsp

www.interviewDuniya.com
<jsp:include page>
„ <jsp:include> action
„ Enables dynamic content to be included in a JSP
„ More flexible than include directive
„ Requires more overhead when page contents change
frequently
„ Unlike the include directive, which inserts the
file at the time the JSP page is translated into a
servlet, this action inserts the file at the time the
page is requested.
www.interviewDuniya.com
„ This pays a small penalty in efficiency, and
precludes the included page from containing
general JSP code (it cannot set HTTP headers,
for example), but it gains significantly in
flexibility.
Attribute Description
page Specifies the relative URI path of the resource to include. The
resource must be part of the same Web application.
flush Specifies whether the buffer should be flushed after the
include is performed. In JSP 1.1, this attribute is required to be
true.
Fig. 10.6 Action <jsp:include> attributes.

www.interviewDuniya.com
<HTML>
<HEAD>
<TITLE>What's New</TITLE>
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
What's New at JspNews.com</TABLE>
</CENTER>
<P>
Here is a summary of our four most recent news stories:
<OL>
<LI><jsp:include page="news/Item1.html" flush="true"/>
<LI><jsp:include page="news/Item2.html" flush="true"/>
<LI><jsp:include page="news/Item3.html" flush="true"/>
<LI><jsp:include page="news/Item4.html" flush="true"/>
</OL>
www.interviewDuniya.com
</HTML>
The jsp:plugin Action

<jsp:plugin type=applet code="Molecule.class"


codebase="/html">
<jsp:params>
<jsp:param name="molecule"
value="molecules/benzene.mol" />
</jsp:params>
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
</jsp:plugin>
www.interviewDuniya.com
„ Example
„ PluginJsp.jsp
„ HelloWorld.class

www.interviewDuniya.com

You might also like