Professional Documents
Culture Documents
Java based technology that simplifies the developing of dynamic web sites.
JSP pages are HTML pages with embedded code that allows to access data from Java code
running on the server.
JSP provides separation of HTML presentation logic from the application logic.
JSP technology provides a way to combine the worlds of HTML and Java servlet
programming.
JSP specs are built on the Java Servlet API.
JSP supports two different styles for adding dynamic content to web pages:
JSP pages can embed actual programming code (typically Java).
JSP supports a set of HTML-like tags that interact with Java objects on the server (without
the need for raw Java code to appear in the page).
JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA
servlets.
JSP uses simplified scripting language based syntax for embedding HTML into JSP.
JSP containers provide easy way for accessing standard objects and actions.
JSP reaps all the benefits provided by JAVA servlets and web container environment, but
they have an added advantage of being simpler and more natural program for web enabling
enterprise developer.
JSP use HTTP as default request / response communication paradigm and thus make JSP
ideal as Web Enabling Technology.
Java Server Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the
CGI.
Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having a separate CGI files.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires
the server to load an interpreter and the target script each time the page is requested.
Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
Finally, JSP is an integral part of J2EE, a complete platform for enterprise class applications.
This means that JSP can play a part in the simplest applications to the most complex and
demanding.
vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is
written in Java, not Visual Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems and non-Microsoft Web
servers.
vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have
plenty of println statements that generate the HTML.
vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real"
programs that use form data, make database connections, and the like.
vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image
processing etc.
vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
JSP Flow
o Scriptlet
o Expression
o Declaration
o Definition
A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language.
Embeds Java code in the JSP document that will be executed each time the JSP page is
processed.
Code is inserted in the service() method of the generated Servlet
Example:
<html>
<body>
<% for (int i = 0; i < 2; i++) { %>
<p>Hello World!</p>
<% } %>
</body>
</html>
Example: 1 Example: 2
A declaration declares one or more variables or methods that you can use in Java code later
in the JSP file. You must declare the variable or method before you use it in the JSP file.
Code is inserted in the body of the servlet class, outside the service method.
o May declare instance variables.
o May declare (private) member functions.
• <jsp:declaration> declaration(s)</jsp:declaration>
<html>
<body>
<%! private int accessCount = 0; %>
<p> Accesses to page since server reboot:
<%= ++accessCount %> </p>
</body>
</html>
<html>
<body>
<%!
int add(int a , int b) {
return a+b;
}
%>
<p> Addition Result=:
<%= add(10 + 20) %> </p>
</body>
</html>
Directives are used to convey special processing information about the page to the JSP
container.
The Directive tag commands the JSP virtual engine to perform a specific task, such as
importing a Java package required by objects and methods.
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as scripting language, error
page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page
This lets you specify what packages should be imported. The import attribute is the only
one that is allowed to appear multiple times.
Error Page:
Syntax: errorPage="url“.
Example: <%@ page errorPage="error.jsp" %>
errorPage="url“ This specifies a JSP page that should process any Throwables thrown
but not caught in the current page.
isErrorPage="true|false“ This indicates whether or not the current page can act as the
error page for another JSP page. The default is false.
Example:
<html>
<body>
<%@ include file="header.jsp" %>
Only the content of a page is unique.
Header and footer are reused from header.jsp and footer.jsp
<%@ include file="footer.jsp" %>
</body>
</html>
Warning: when included files change, the page is not automatically recompiled
Following are name of the attributes of the page directive used in JSP:
o Language
o extends
o import
o session
o buffer
o autoFlush
o isThreadSafe
o info
o errorPage
o contentType
o isErrorPage
language: This attribute of page directive of JSP is used for specifying some other scripting
languages to be used in the JSP page.
extends: This is used for specifying some other java classes to be used in the JSP page like
packagename.classname. The fully qualified name of the superclass of the Java class will be
accepted.
import: This attribute imports the java packages and it's classes. We can import more than
one java packages and classes by separating with comma (,).
We can set the name of the class with the package name directly like
packagename.classname or import all classes of the package by using packagename.*
session: This attribute sets a boolean value to either true or false. If the value of session
attribute is true then the session object refers to the current or a new session because the
client must be in the HTTP session for running the JSP page on the server. If we set the
value of session object to false then we cannot use the session object.
buffer: This attribute sets the buffer size in kilobytes i.e. used by the out object to handle
output generated by the JSP page on the client web browser. If we specify the buffer size
then the output will be buffered with at least 8kb because the default and minimum value
of the buffer attribute is 8kb.
autoFlush: This attribute of the page directive supports for flushing buffer automatically
when the buffer is full. The value of the autoFlush attribute is either true or false. If we
specify it as true, then buffer will be flushed.
isThreadSafe: This attribute support the facility of maintaining thread for sending multiple
and concurrent requests from the JSP container to the JSP page if the value the of attribute
is set to true, otherwise if we set the value of attribute to false, then the JSP container can
send only one request at one time. The default value of the attribute is true.
info: This attribute simply sets the information of the JSP page which is retrieved later by
using Servlet.getServletInfo() method. The value of the attribute will be a text string.
errorPage: This attribute sets a url. If any exception is generated then the attribute refers to
the file which is mentioned in the given url. If no url id specified, then the attribute refers
to the current page of the JSP application when exception generated
isErrorPage: This attribute sets the boolean value to either true or false. We can use the
exception object in the JSP page if we set the attribute value to true, otherwise we cannot
use the exception object because the default value of the attribute is false.
contentType: This attribute specifies the MIME type and the character encoding used for
the JSP response. The default MIME type is "text/html" and the default character set is "ISO-
88591".
Implicit objects are a set of Java objects that the JSP Container makes available to
developers in each page. These objects may be accessed as built-in variables via scripting
elements.
Implicit objects accessible to actions
o Page
o Out
o Config
o Session
o Request
o Application
o Response
o pageContext
o exception
Request
Session
Application
o PageContext has a page scope. Pagecontext is the context for the JSP page itself that
provides a single API to manage the various scoped attributes.
o This API is extensively used if we are implementing JSP custom tag handlers.
o PageContext also provides access to several page attributes like including some static
or dynamic resource.
o Used for sharing JavaBeans
Response
Exception:
o This object has a page scope and is an instance of the JSP page’s servlet class that
processes the current request.
o Page object represents the current page that is used to call the methods defined by the
translated servlet class.
o First type cast the servlet before accessing any method of the servlet through the page.
Using JSP it is easy to create dynamic content for a web page based on conditions received
from the browser.
There are two control statements used to change the flow of a JSP program.
These are the if statement and the switch statement, both of which are also used to direct
the flow of a Java program.
The power of these codes comes from the fact that the code segment that is executed or
skipped can consist of HTML tags or a combination of HTML tags and JSP tags.
<html>
<body>
<%! int grade=70;%>
<% if(grade > 69 ) { %>
<p> You Got FCD ! </p>
<% }
else { %>
<p> Better luck next time. </p>
<% } %>
<% switch (grade) {
case 70 : %>
<p> Your grade is FCD </p>
<% break;
case 60 : %>
<p> Your grade is FC </p>
<% break;
}
%>
</body> </html>
Loops in JSP:
JSP loops are nearly identical to loops used in Java programs.
The for loop, while loop, and do-While loop are the three loops.
Loops play an important role in JSP database programs
<html>
<!-- Regular Comment -->
<%-- Hidden Comment --%>
<%
// Java comment
%>
</html>
The page directive is used to provide instructions to the container that pertain to the current
JSP page. You may code page directives anywhere in your JSP page. By convention, page
directives are coded at the top of the JSP page.
This lets you specify what packages should be imported. The import attribute is the only
one that is allowed to appear multiple times.
Error Page:
Syntax: errorPage="url“.
Example: <%@ page errorPage="error.jsp" %>
errorPage="url“ This specifies a JSP page that should process any Throwables thrown
but not caught in the current page.
isErrorPage="true|false“ This indicates whether or not the current page can act as the
error page for another JSP page. The default is false.
Attributes:
Following is the list of attributes associated with page directive:
Attribute Purpose
buffer Specifies a buffering model for the output stream.
autoFlush Controls the behavior of the servlet output buffer.
contentType Defines the character encoding scheme.
errorPage Defines the URL of another JSP that reports on Java unchecked
runtime exceptions.
isErrorPage Indicates if this JSP page is a URL specified by another JSP page's
errorPage attribute.
extends Specifies a superclass that the generated servlet must extend
import Specifies a list of packages or classes for use in the JSP as the Java
import statement does for Java classes.
info Defines a string that can be accessed with the servlet's
getServletInfo() method.
isThreadSafe Defines the threading model for the generated servlet.
language Defines the programming language used in the JSP page.
session Specifies whether or not the JSP page participates in HTTP sessions
isELIgnored Specifies whether or not EL expression within the JSP page will be
ignored.
isScriptingEnabled Determines if scripting elements are allowed for use.
JSP actions use constructs in XML syntax to control the behavior of the servlet engine.
You can dynamically insert a file, reuse JavaBeans components, forward the user to another
page, or generate HTML for the Java plugin.
They assist JSP developers to develop in tags rather than scriptlet programming
Syntax:
<prefix:action_name>
body
</prefix:action_name>
JSP tags have a “start tag”, a “tag body” and an “end tag”
The start and end tag have the same name enclosed in < and >
The tag names have an embedded colon character “:” in them
the part before the colon (prefix) describes the type of the tag
the part after the “:” is the Action Name
Full syntax of JSP Action Elements is:
<prefix:action_name attr1 = “value” attr2 = “value2”>
action_body
</prefix:action_name>
If the element doesn’t have a body, can lose the end tag and use shorthand syntax of:
<prefix:action_name attr1 = “value” attr2 = “value2” />
Example:
<jsp:include page="scripts/login.jsp" />
Action elements are basically predefined functions and there are following JSP actions
available:
Syntax Purpose
jsp:include Includes a file at the time the page is requested
jsp:forward Forwards the requester to a new page
jsp:useBean Finds or instantiates a JavaBean
jsp:setProperty Sets the property of a JavaBean
jsp:getProperty Inserts the property of a JavaBean into the output
jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag
for the Java plugin
jsp:element Defines XML elements dynamically.
jsp:attribute Defines dynamically defined XML element's attribute.
jsp:body Defines dynamically defined XML element's body.
jsp:text Use to write template text in JSP pages and documents.
Example:
<jsp:forward page="/utils/errorReporter.jsp" />
<jsp:forward page="<%= someJavaExpression %>" />
<html ><body>
<% if(request.getParameter("name").equals("MCA"))
{ %>
<jsp:forward page="ForwardJsp.jsp">
<jsp:param name="MyName" value="khutub"/>
<jsp:param name="MyPassword" value="MCA"/>
</jsp:forward>
<% } %>
</body></html>
Forward.jsp
<html>
<body>
<h1>jsp using forwarded contents!</h1>
<h2> <%=request.getParameter("name")%> </h2>
<h2>parameters passed</h2>>
<h2> parameter name<%=request.getParameter("MyName")%> </h2>
<h2> parameter password<%=request.getParameter("MyPassword")%>
</h2> </body>
<html>
• Executes the included JSP page and adds its output into the page
<p> Date.jsp
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
<html> <body>
<center>
<h2>The include action Example</h2> IncludeDemo.jsp
<jsp:include page="date.jsp" flush="true" />
</center>
</body> </html>
The plugin action is used to insert Java components into a JSP page. It determines the type
of browser and inserts the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java
component. The Java component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to
format Java components.
The <param> element can also be used to send parameters to the Applet or Bean.
Following is the typical syntax of using plugin action:
AppletJsp.jsp
<html>
<body>
<jsp:plugin type="applet" code="DemoApplet.class"
width="400" height="400">
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
</jsp:plugin>
</body></html>
OUTPUT:
Java Server Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags. It also provides a
framework for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into following JSTL tag library
groups that can be used when creating a JSP page:
o Core Tags
o Formatting tags
o SQL tags
o XML tags
o JSTL Functions
o To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR files in
the distribution's 'lib' directory to your application's webapps\ROOT\WEB-INF\lib directory.
To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses the
library.
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is the syntax to
include JSTL Core library in your JSP:
Tag Description
<c:out > Like <%= ... >, but for expressions.
<c:set > Sets the result of an expression evaluation in a 'scope'
<c:remove > Removes a scoped variable (from a particular scope, if specified).
<c:catch> Catches any Throwable that occurs in its body and optionally exposes it.
<c:if> Simple conditional tag which evalutes its body if the supplied condition is
true.
<c:choose> Simple conditional tag that establishes a context for mutually exclusive
SQL tags:
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs)
such as Oracle, mySQL, or Microsoft SQL Server.
Tag Description
<sql:setDataSource> Creates a simple DataSource suitable only for prototyping
<sql:query> Executes the SQL query defined in its body or through the sql
attribute.
<sql:update> Executes the SQL update defined in its body or through the sql
attribute.
<sql:param> Sets a parameter in an SQL statement to the specified value.
<sql:dateParam> Sets a parameter in an SQL statement to the specified
java.util.Date value.
<sql:transaction > Provides nested database action elements with a shared
Connection, set up to execute all statements as one
transaction.
Designing tag libraries allows content developers to use custom tags instead of java code.
in this example of nested we will take the attribute as country for parent and child tags, and
inside child tag will check if the country is same as parent than only execute the body
content of child tag.
Web.XML
<web-app>
<display-name>tagext</display-name>
<description>Tag extensions examples</description>
<taglib>
<taglib-uri>/nest</taglib-uri>
<taglib-location>/WEB-INF/tlds/nested.tld</taglib-location>
</taglib>
</web-app>
package CustomTag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class ParentTagHandler extends TagSupport {
private String country;
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}}
package CustomTag;
import CustomTag.ParentTagHandler;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
public class ChildTagHandler extends TagSupport {
public Tag parent;
private String country;
public int doStartTag() throws JspException {
ParentTagHandler parentTag = (ParentTagHandler) parent;
if (getCountry().equals(parentTag.getCountry())) {
return EVAL_BODY_INCLUDE;
}
return SKIP_BODY;
}
public void setParent(Tag parent) {
this.parent = parent;
}
public String getCountry() {
return country;
} public void setCountry(String country) {
this.country = country;
}}
<taglib>
<tlib-version>1.0</tlib-version>
<short-name>custom-tags</short-name>
<uri>/tlds/customTags</uri>
<tag>
<name>parent</name>
<tagclass>CustomTag.ParentTagHandler</tagclass>
<bodycontent>jsp</bodycontent>
OUTPUT:
<attribute>
<name>country</name>
<required>true</required>
</attribute>
</tag>
<tag>
<name>child</name>
<tagclass>CustomTag.ChildTagHandler</tagclass>
<bodycontent>jsp</bodycontent>
<attribute>
<name>country</name>
<required>true</required>
</attribute>
</tag>
</taglib>
CustomJsp.Jsp