KEMBAR78
10 Lecture JSP | PDF | Java (Programming Language) | Software
0% found this document useful (0 votes)
19 views37 pages

10 Lecture JSP

Java Server Pages (JSP) enable the embedding of Java code in HTML to create dynamic web pages, separating application logic from presentation. JSP was developed in response to Microsoft's ASP, featuring user-defined tags and a structure that allows for easy integration with JavaBeans. Key elements of JSP include scriptlets, expressions, directives, and standard actions, which facilitate the generation of dynamic content and interaction with Java components.

Uploaded by

Priyanshu Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views37 pages

10 Lecture JSP

Java Server Pages (JSP) enable the embedding of Java code in HTML to create dynamic web pages, separating application logic from presentation. JSP was developed in response to Microsoft's ASP, featuring user-defined tags and a structure that allows for easy integration with JavaBeans. Key elements of JSP include scriptlets, expressions, directives, and standard actions, which facilitate the generation of dynamic content and interaction with Java components.

Uploaded by

Priyanshu Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Course : WEB ENGINEERING

Paper Code: ETCS-308


Faculty : Dr. Prabhjot Kaur
Associate Professor
Dept. of IT
MSIT
prabhjot.kaur@msit.in

TOPIC: Java Server Pages

UNIT-II Java Server Pages dbc@csit.fsu.edu


Introduction
Java Server Pages allow special tags and Java code to be embedded in
HTML files. These tags and code are processed by the Web server to
dynamically produce a standard HTML page for the browser.

Produce dynamic Web pages on the server side (like Servlets), but separate application
logic from the appearance of the page.

The tags allow previously compiled Java code, in the form of JavaBeans, to be used.

Allows fast development and testing.

May also produce XML documents, instead of HTML.

UNIT-II Java Server Pages dbc@csit.fsu.edu


Development of JSP
Java Server Pages were developed as a response to Microsoft’s Active Server
Pages (ASP). The main differences are that ASP only runs on Microsoft IIS and
Personal Web Servers, and JSP has user-defined tags.

Development dates: (Note that JSP is built on top of Servlets)


Servlet 2.1 Jan. 99
JSP 1.0 June 99
Source code released to Apache to develop Tomcat server November 99
Servlet 2.2 and JSP 1.1 (J2EE1.2) December 99
Latest version: 2.2.

UNIT-II Java Server Pages dbc@csit.fsu.edu


JSP Elements
• A JSP page looks like a standard HTML or XML page with additional elements
processed by the JSP container.
• Typically, these elements create text that is inserted into the resulting
document.
• JSP elements include:
• Scriptlet: enclosed in <% and %> markers: a small script in Java to perform arbitrary
functions. Executed in the underlying servlet context.
• Expression: anything between <%= and %> markers is evaluated by the JSP engine as a
Java expression in the servlet context.
• JSP directive enclosed in <%@ and %> markers—passes information to the JSP engine
(guides “compilation”).
• JSP actions or tags are a set of customizable XML-style tags for particular actions, e.g.
predefine jsp:useBean instantiates a Java Bean class on the server.

UNIT-II Java Server Pages dbc@csit.fsu.edu


Architecture

URL
JSP page
request
HTTP request
JSP container properties, JavaBean
compiles to call methods Library
a servlet

HTTP response response

HTTP page DB

Browser Web server

UNIT-II Java Server Pages dbc@csit.fsu.edu


“Hello User” Servlet, Revisited
import java.io.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType(“text/html”) ;
PrintWriter out = response.getWriter() ;
out.println(“<html><body>”) ;
out.println(“<h1>Hello ” +
request.getParameter(“who”) + “!</h1>”) ;
out.println(“</html></body>”) ;
}
}

UNIT-II Java Server Pages dbc@csit.fsu.edu


An Equivalent JSP Page

<html> <body>
<h1>Hello <%= request.getParameter(“who”) %>
</h1>
</body> </html>

UNIT-II Java Server Pages dbc@csit.fsu.edu


Remarks
This text may be saved in a file hellouser.jsp in the dbc/ application directory.
A suitable form element to front-end this page might be:
<form action=“hellouser.jsp”>
Name: <input type=text name=who size=32> <p>
<input type=submit>
</form>

The JSP version is much more compact and easier to understand!


We can expect this to be generally the case when the logic behind a dynamic
page is relatively simple, and the bulk of the content is static HTML.

UNIT-II Java Server Pages dbc@csit.fsu.edu


What is a JSP Page?
According to the JavaServer Pages Specification:
“A JSP page is a text-based document that describes how to
process a request to create a response. The description
intermixes template data with some dynamic actions [. . .].”

JSP deliberately supports multiple paradigms for authoring


dynamic content.
Notably, scriptlets, JavaBeans and Tag Libraries.

UNIT-II Java Server Pages dbc@csit.fsu.edu


Translating and Executing JSP Pages
A JSP page is executed in a JSP container, generally installed in a
Web server.
Think of a “JSP container” as a JVM with suitable software installed.
The underlying semantic model is that of a servlet.
A typical JSP container will translate the JSP page to a Java servlet.
By default translation and compilation of a JSP page is likely to
occur the first time it is accessed.
With Tomcat 3.1, you can find the generated Java and the class files in a
subdirectory under jakarta-tomcat/work.

UNIT-II Java Server Pages dbc@csit.fsu.edu


JSP Features
Standard directives guiding translation of a JSP page to a
servlet.
Standard actions in the form of predefined JSP tags.
Script language declarations, scriptlets, and expressions
for including Java (or in principle other language)
fragments that embed dynamic content.
A portable tag extension mechanism, for building tag
libraries—effectively extending the JSP language.

UNIT-II Java Server Pages dbc@csit.fsu.edu


JSP Directives
• page directives communicate page-specific information to the JSP engine,
such as buffer or thread information or specify an error page.
• include directives includes an external document in the page. These are
often company information files or copyright files, but can also be jsp files.
• taglib directive indicates a library of custom tags that the page can include.
• language directives specify script language + possible extensions. The only
standard language is Java.
• All are delimited by <%@ and %> markers, e.g.:
<%@ include file=“copyright.html” %>

UNIT-II Java Server Pages dbc@csit.fsu.edu


Standard Actions
Predefined action tags include:
• jsp:useBean - declares the usage of an instance of a JavaBeans component. If
it does not already exist, then the instance is created and registered in the
servlet environment.
• jsp:setProperty - this tag can be used to set all the properties of a Bean from
the request parameter stream with parameters of the same name, or can be
used to set individual properties.
• jsp:getProperty - gets the property of the Bean, converts it to a String, and
puts it into the implicit object “out”.
• jsp:forward - forwards the request to another jsp page or servlet.
• jsp:include - include another JSP page
• jsp:plugin - load into the specified plug-in of the browser
UNIT-II Java Server Pages dbc@csit.fsu.edu
Scripting Elements
There are three kinds of scripting element:
• Scriptlets: arbitrary fragments of Java that are executed in the request
handling method. Syntax is e.g.:
<% out.println(“Your number is ” + Math.random()) ; %>
• Expressions: any Java expression, cast to a String. Evaluated in the context of
the request handling method. Syntax is e.g.:
<%= Math.sqrt(2) %>
• Declarations: any Java declaration that can appear at the class body level,
such as an instance variable or method declaration. Syntax is e.g.:
<%! Color c = new Color (0, 128, 255) ; %>

UNIT-II Java Server Pages dbc@csit.fsu.edu


Predefined Variables
request
The HttpServletRequest object passed to the servlet’s request
handling method.
response
The HttpServletResponse object passed to the servlet’s request
handling method.
out
The PrintWriter object associated with response.
session
The HttpSession object associated with the request.
UNIT-II Java Server Pages dbc@csit.fsu.edu
“Compound” Scriptlets
A compound statement in the generated code does not have to be limited to a
single scriptlet element.
Instead can be assembled from several scriptlet elements, surrounding blocks of
template text.
Here is an example using a conditional around blocks of template data (taken from
the book by Hall):
<html><head></head><body>
<% if (Math.random() < 0.5) { %>
Have a nice day!
<% } else { %>
Have a lousy day!
<% } %>
</body></html>

UNIT-II Java Server Pages dbc@csit.fsu.edu


Expressions
A JSP expression is very similar to a scriplet, except that the
enclosing Java code is required to be an expression.
The expression is evaluated, then converted to a String.
The string is effectively interpolated into the template text—
wherever the element appears—and sent to the browser as part of
the generated HTML.
The syntax of a expression element is:
<%= Java expression in here %>
Distinguished from a scriptlet by the = sign attached to <% .

UNIT-II Java Server Pages dbc@csit.fsu.edu


Avoiding out.println()
We can use an expression to replace the first scriplet:
<html><head></head><body>
<% out.println(“Now is” + new java.util.Date()) ; %>
</body></html>
with:
<html><head></head><body>
Now is <%= new java.util.Date() %>
</body></html>
In general, expression elements save us writing many scriplets that just
include calls to out.println().

UNIT-II Java Server Pages dbc@csit.fsu.edu


Showing Pets
<html><head></head><body>
Your pets:<p>
<table border cellspacing=0 cellpadding=5>
<%
String [] pets = request.getParameterValues(“pets”) ;
for (int i = 0 ; i < pets.length ; i++) {
%>
<tr><td> <%= pets [i] %> </td></tr>
<%
}
%>
</table>
</body></html>

UNIT-II Java Server Pages dbc@csit.fsu.edu


Declarations
The last kind of JSP scripting element is the declaration.
In contrast to expressions, JSP declarations give us a
fundamentally new functionality, which cannot be achieved with
scriptlets alone.
They allow code to be inserted at the top level of the Servlet class
definition, outside the body of the request-handling method.
The syntax of a declaration element is:
<%! Java declaration in here %>
• Distinguished from a scriptlet by the ! sign attached to <% .

UNIT-II Java Server Pages dbc@csit.fsu.edu


The Counter Servlet Revisited
import java.io.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
public class Counter extends HttpServlet {
int count = 0 ;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setContentType(“text/html”) ;
PrintWriter out = resp.getWriter() ;
out.println(“<html><head></head><body>”) ;
out.println(“This servlet instance has been accessed ” +
(count++) + “ times”) ;
out.println(“ </body></html>”) ;
}
}

UNIT-II Java Server Pages dbc@csit.fsu.edu


A JSP Counter
<%! int count = 0 ; %>
<html><head></head><body>
This JSP page has been accessed <%= count++ %> times
</body></html>

• As usual, this is the complete JSP page.


• Note that actually it doesn’t matter where the declaration
element appears in the JSP page, since it is not associated
with request handling “thread of control”.

UNIT-II Java Server Pages dbc@csit.fsu.edu


Method Declarations
A JSP declaration element can include a method declaration, e.g.:
<%!
String myMethod() {
return “madness” ;
}
%>
<html><head></head><body>
There is <%= myMethod() %> in my method.
</body></html>

For page initialization, use a JSP declaration to override:


public void jspInit() {}

UNIT-II Java Server Pages dbc@csit.fsu.edu


Local Variables

• Use a JSP declaration if you want to declare an instance


variable of a servlet.
• Do not use a JSP declaration if you just want to declare a
variable local to the request handling method.
• Local variables should be declared in ordinary scriplet
elements, e.g.:
<% int loopCount ; %>

UNIT-II Java Server Pages dbc@csit.fsu.edu


Directives
• Strictly speaking, JSP directives are separate from scripting elements,
but it is convenient to review them here.
• The general syntax is:
<%@ name attr1=“value1” attr2=“value2” . . . %>
where name is the name of the directive, and attr1, attr2, . . . are
the names of various attributes associated with this directive.
• The currently allowed values for name are page, include and taglib:
• The page directive defines various attributes associated with a page.
• The include directive allows another file to be textually included.
• The taglib directive imports a tag library.

UNIT-II Java Server Pages dbc@csit.fsu.edu


The import attribute
• For now the most important attribute that can be set by the
page directive is the import attribute.
• This simply adds an import directive to the generated Java
code.
• Syntax is, e.g.:
<%@ page import=“java.util.*” %>

UNIT-II Java Server Pages dbc@csit.fsu.edu


Actions
JSP actions are special elements that follow a strict XML
syntax.
They sit naturally within an HTML document (and
presumably are comfortable to Web designers).
If actions are used exclusively, there need not be any Java
source embedded in the HTML page.
These actions are the predefined standard actions.

UNIT-II Java Server Pages dbc@csit.fsu.edu


The Standard Actions
• jsp:forward
Forwards the request to another JSP page or servlet.
• jsp:include
Include another JSP page
• jsp:plugin
Include an applet in the page.
• jsp:useBean
Declares usage of a JavaBeans component in the page.
• jsp:setProperty
Sets a property of a bean.
• jsp:getProperty
Gets a property of the Bean.

UNIT-II Java Server Pages dbc@csit.fsu.edu


Syntax
All actions have a strict XML syntax.
An element either has the form:
< name attr1=“value1” attr2=“value2” . . . />
or the form:
< name attr1=“value1” attr2=“value2” . . . >
JSP body of element
</ name >
Here name is the name of the element, and attr1, attr2, . . . are the names of
various attributes associated with this element.
Differences from HTML:
Case is significant.
Attribute values must always be quoted.
Single-tag elements (elements with no body) are closed by />.

UNIT-II Java Server Pages dbc@csit.fsu.edu


The Forward Action
The jsp:forward action transfers control from the current JSP page to
another location on the server.
Some possible uses:
Send the contents of a display page at the end of a page that mainly does some
actions.
In a conditional scriptlet, forward control to some error page when a particular
situation arises.
In some of the earlier servlet examples we used sendRedirect() to transfer
to a display page after doing some actions.
Using jsp:forward would be more efficient, because it does not involve the
browser in the transfer.

UNIT-II Java Server Pages dbc@csit.fsu.edu


Example
<html><head></head> <body>
<%
String who = request.getParameter(“who”) ;
if (who == null) {
%>
<jsp:forward page=“noparam.html” />
<%
} else {
%>
<h1>Hello <%= “who” %> </h1>
<%
}
%>
</body> </html>

UNIT-II Java Server Pages dbc@csit.fsu.edu


The jsp:param Element
• Some of the standard actions allow jsp:param elements in their
body. jsp:forward is a case in hand.
• We could replace our static “missing parameter” error page,
noparam.html, with a JSP page that itself takes a parameter,
specifying which parameter was missing from the original request.
• The jsp:forward element would be replaced with:
<jsp:forward page=“noparam.jsp”>
<jsp:param name=“missing” value=“who” />
</jsp:forward>

UNIT-II Java Server Pages dbc@csit.fsu.edu


The Include Action
The jsp:include action temporarily transfers control from the current
JSP page to another location, and includes the text generated by the
other page in its own output.
Syntax is, e.g.:
<jsp:include page=“banner.html” />
As with jsp:forward, jsp:param elements may be optionally included
in a body.
This is subtly different from the include directive, which includes text,
before translation of the JSP.

UNIT-II Java Server Pages dbc@csit.fsu.edu


The Plug-in Action
The jsp:plugin tag introduces an element that allows an applet to be
included the generated page, in such a way that it can be displayed by the
Java plug-in in a browser.
This is a replacement for running the HTML conversion program over a file
with an applet tag.
Example (from the JSP specification):
<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 start plugin </p>
</jsp:fallback>
</jsp:plugin>
UNIT-II Java Server Pages dbc@csit.fsu.edu
Example:Access Client Information
The getRemoteHost method of the request object allows a JSP to retrieve
the name of a client computer.

<html><head>
<title>Your Information</title>
</head><body>
Your computer's IP address is
<b><%= request.getRemoteAddr() %></b>
<br>Your computer's name is
<b><%= request.getRemoteHost() %></b>
<br>Your computer is accessing port number
<b><%= request.getServerPort() %></b>
</body></html>

UNIT-II Java Server Pages dbc@csit.fsu.edu


JSP Tags + HTML Tags
<h2>Table of Square Roots</h2>
<table border=2>
<tr>
<td><b>Number</b></td>
<td><b>Square Root</b></td>
</tr>
<%
for (int n=0; n<=100; n++)
{
%>
<tr>
<td><%=n%></td>
<td><%=Math.sqrt(n)%></td>
</tr>
<%
}
%>
</table>

UNIT-II Java Server Pages dbc@csit.fsu.edu


Thank You

UNIT-II Java Server Pages dbc@csit.fsu.edu

You might also like