JSP Tutorial
JSP Tutorial
Java language and enables the development of dynamic web sites. JSP was
developed by Sun Microsystems to allow server side development. JSP files
are HTML files with special Tags containing Java source code that provide the
dynamic content.
The following shows the Typical Web server,different clients connecting via
the Internet to a Web server. In this example,the Web server is running on
Unix and is the very popular Apache Web server
First static web pages were displayed. Typically these were people?s first
experience with making web pages so consisted of My Home Page sites and
company marketing information. Afterwards Perl and C were languages used
on the web server to provide dynamic content. Soon most languages
including Visualbasic,Delphi,C and Java could be used to write applications
that provided dynamic content using data from text files or database
requests. These were known as CGI server side applications. ASP was
developed by Microsoft to allow HTML developers to easily provide dynamic
content supported as standard by Microsoft?s free Web Server,Internet
Information Server (IIS). JSP is the equivalent from Sun Microsystems,a
comparison of ASP and JSP will be presented in the following section.
The following diagram shows a web server that supports JSP files. Notice that
the web server also is connected to a database.
JSP source code runs on the web server in the JSP Servlet Engine. The JSP
Servlet engine dynamically generates the HTML and sends the HTML output
to the client?s web browser.
JSP is easy to learn and allows developers to quickly produce web sites and
applications in an open and standard way. JSP is based on Java,an object-
oriented language. JSP offers a robust platform for web development.
Multi platform
Component reuse by using Javabeans and EJB.
Advantages of Java.
You can take one JSP file and move it to another platform,web server or JSP
Servlet engine.
This means you are never locked into one vendor or platform.
HTML and graphics displayed on the web browser are classed as the
presentation layer. The Java code (JSP) on the server is classed as the
implementation.
JSP and ASP are fairly similar in the functionality that they provide. JSP may
have slightly higher learning curve. Both allow embedded code in an HTML
page,session variables and database access and manipulation. Whereas ASP
is mostly found on Microsoft platforms i.e. NT,JSP can operate on any
platform that conforms to the J2EE specification. JSP allow component reuse
by using Javabeans and EJBs. ASP provides the use of COM / ActiveX controls.
A Servlet is a Java class that provides special server side service. It is hard
work to write HTML code in Servlets. In Servlets you need to have lots of
println statements to generate HTML. JSP pages are converted to Servlets so
actually can do the same thing as old Java Servlets.
JSP architecture
JSPs are built on top of SUN Microsystems' servlet technology. JSPs are
essential an HTML page with special JSP tags embedded. These JSP tags can
contain Java code. The JSP file extension is .jsp rather than .htm or .html. The
JSP engine parses the .jsp and creates a Java servlet source file. It then
compiles the source file into a class file,this is done the first time and this
why the JSP is probably slower the first time it is accessed. Any time after
this the special compiled servlet is executed and is therefore returns faster.
Steps required for a JSP request:
1. The user goes to a web site made using JSP. The user goes to a JSP page
(ending with .jsp). The web browser makes the request via the Internet.
2. The JSP request gets sent to the Web server.
3. The Web server recognises that the file required is special (.jsp),therefore passes
the JSP file to the JSP Servlet Engine.
4. If the JSP file has been called the first time,the JSP file is parsed,otherwise go to
step 7.
5. The next step is to generate a special Servlet from the JSP file. All the HTML
required is converted to println statements.
6. The Servlet source code is compiled into a class.
7. The Servlet is instantiated,calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
9. HTML results are displayed on the user's web browser.
10.Creating your first JSP page
<html>
<head>
<title>My first JSP page
</title>
</head>
<body>
<%@ page language="java" %>
<% out.println("Hello World"); %>
</body>
</html>
11.Type the code above into a text file. Name the file helloworld.jsp.
12.Place this in the correct directory on your JSP web server and call it via
your browser.
1. Declaration tag
2. Expression tag
3. Directive tag
4. Scriptlet tag
5. Action tag
For Example,
<%!
private int counter = 0 ;
private String get Account ( int accountNo) ;
%>
Expression tag ( <%= %>)
This tag allows the developer to embed any Java expression and is short for
out.println().
A semicolon ( ; ) does not appear at the end of the code inside the tag.
For example,to show the current date and time.
Date : <%= new java.util.Date() %>
A JSP directive gives special information about the page to the JSP Engine.
There are three main types of directives:
1) page - processing information for this page.
2) Include - files to be included.
3) Tag library - tag library to be used in this page.
Directives do not produce any visible output when the page is requested but
change the way the JSP Engine processes the page.
1. Page directive
This directive has 11 optional attributes that provide the JSP Engine with
special processing information. The following table lists the 11 different
attributes with a brief description:
language
2. Include directive
This includes the html from privacy.html found in the include directory into
the current jsp page.
Include files are discussed in more detail in the later sections of this tutorial.
A tag lib is a collection of custom tags that can be used by the page.
<%@ taglib uri = "tag library URI" prefix = "tag Prefix" %>
Custom tags were introduced in JSP 1.1 and allow JSP developers to hide
complex server side code from web designers.
Scriptlet tag ( <% ... %> )
Between <% and %> tags,any valid Java code is called a Scriptlet. This code
can access any variable or bean declared.
<%
String username = "visualbuilder" ;
out.println ( username ) ;
%>
Action tag
Javabeans
A Javabean is a special type of class that has a number of methods. The JSP page can
call these methods so can leave most of the code in these Javabeans. For example,if
you wanted to make a feedback form that automatically sent out an email. By having a
JSP page with a form,when the visitor presses the submit button this sends the details
to a Javabean that sends out the email. This way there would be no code in the JSP
page dealing with sending emails (JavaMail API) and your Javabean could be used in
another page (promoting reuse).
<HTML>
<HEAD>
<!-- Example2 -->
<TITLE> JSP loop</TITLE>
</HEAD>
<BODY>
<font face=verdana color=darkblue>
JSP loop
<BR> <BR>
<%!
public String writeThis(int x)
{
String myText="";
for (int i = 1; i < x; i )
myText = myText "<font size=" i " color=darkred
face=verdana>VisualBuilder JSP Tutorial</font><br>" ;
return myText;
}
%>
<br>
<%= writeThis(8) %>
</font>
</BODY>
</HTML>
Implicit Objects
So far we know that the developer can create Javabeans and interact with
Java objects. There are several objects that are automatically available in JSP
called implicit objects.
Request Javax.servlet.http.httpservletreque
st
Response Javax.servlet.http.
httpservletresponse
Out Javax.servlet.jsp.JspWriter
Session Javax.servlet.http.httpsession
PageContent Javax.servlet.jsp.pagecontext
Application Javax.servlet.http.ServletContext
Config Javax.servlet.http.ServletConfig
Page Java.lang.Object
Page object
Represents the JSP page and is used to call any methods defined by the
servlet class.
Config object
Request object
Creating a Form
Processing a Form
Here we show how to process the html form your just created.
Copy the code below and place in a file named: myformconfirm.jsp
Go to myform.jsp
Fill in some details and submit the form
You should see the results of your submission
<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>
</head>
<body>
<font size=3>
Your info has been received:
<br><br>
<%
String sName = request.getParameter("website");
out.print(sName);
%>
</font>
</body>
</html>
This example shows how to create and process more form elements.
Copy the code below and place in a file named: fullform.jsp
<html>
<head>
<!-- Example5 -->
<title>VisualBuilder.com</title>
</head>
<body>
<h1>
Website submission form
</h1>
<form action="fullformconfirm.jsp" method="post">
Enter in the website name:
<input type="text" name="website">
<br>
<br>
Enter in the url:
<input type="text" name="url">
<br>
<br>
category:
<select name="category" size="1">
<option selected value="java">java</option>
<option value="ejb">ejb</option>
<option value="servlet">servlet</option>
<option value="jsp">jsp</option>
<option value="jdbc">jdbc</option>
</select>
<br>
<br>
Description:
<textarea rows="4" cols='42' name="desc"></textarea>
<br>
<br>
Search engines:
<input type="checkbox" name="yahoo" value="T">Yahoo
<input type="checkbox" name="google" value="T" CHECKED>Google
<input type="checkbox" name="altavista" value="T">Altavista
<br>
<br>
<input type="submit" name="submit" value="Go">
</form>
</body>
</html>
Here we show how to process the html form your just created.
Copy the code below and place in a file named: fullformconfirm.jsp
Go to fullform.jsp
Fill in some details and submit the form
You should see the results of your submission
<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>
</head>
<body>
<font size=3>
Thank you for your submission,it has been successfully received:
<br><br>
<%
String sName = request.getParameter("website");
String sUrl = request.getParameter("url");
String sCategory = request.getParameter("category");
String sDesc = request.getParameter("desc");
String sGoogle = request.getParameter("google");
String sYahoo = request.getParameter("yahoo");
String sAltavista = request.getParameter("altavista");
%>
Name:<%=sName%><br>
Url:<%=sUrl%><br>
Desc:<%=sDesc%><br>
Category:<%=sCategory%><br>
Desc:<%=sDesc%><br>
Google:<%=sGoogle%><br>
Yahoo:<%=sYahoo%><br>
Altavista:<%=sAltavista%><br>
</font>
</body>
</html>
Processing a Form (more elements)
Here we show how to process the html form your just created.
Copy the code below and place in a file named: fullformconfirm.jsp
Go to fullform.jsp
Fill in some details and submit the form
You should see the results of your submission
<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>
</head>
<body>
<font size=3>
Thank you for your submission,it has been successfully received:
<br><br>
<%
String sName = request.getParameter("website");
String sUrl = request.getParameter("url");
String sCategory = request.getParameter("category");
String sDesc = request.getParameter("desc");
String sGoogle = request.getParameter("google");
String sYahoo = request.getParameter("yahoo");
String sAltavista = request.getParameter("altavista");
%>
Name:<%=sName%><br>
Url:<%=sUrl%><br>
Desc:<%=sDesc%><br>
Category:<%=sCategory%><br>
Desc:<%=sDesc%><br>
Google:<%=sGoogle%><br>
Yahoo:<%=sYahoo%><br>
Altavista:<%=sAltavista%><br>
</font>
</body>
</html>
The following is the explanation for the different scopes of a bean object in jsp:
1. Page scope:- This scope helps to keep the data available while the page is
loading. Any object whose scope is defined as page scope will disappear as
soon as the response is sent to the browser. The object with a page scope
may be modified as often as desired within the particular page but the
changes are lost as soon as the user moves away from the page. By default
all beans have page scope.
2. Request scope:- Any object created in the request scope will be available as
long as the request object is valid. For example if the JSP page uses a
<jsp:forward> tag, then the bean will be accessed in the forwarded page and
if redirect is used then the bean is destroyed.
3. The Session scope:- In JSP terms, the data associated with the user has
session scope. A session does not correspond directly to the user; rather, it
corresponds with a particular period of time the user spends at a site.
Typically, this period is defined as all the hits a user makes to a website
JSP Bean scope examples
The following example will demonstrate the various bean scopes for the JSP
application. All the examples will use the Counter bean which has only one property
counter of type int .
Note:- This is the default scope for the bean object. So in the following JSP example
"bean1" is accessed only in this page and not anywhere else.
<HTML>
<BODY>
<H1>Using Beans and Page Scope</H1>
<jsp:useBean id="bean1" class="com.visualbuilder.Counter"
scope="page" />
<%bean1.setCounter(bean1.getCounter() + 1);%>
The counter value is: <jsp:getProperty name="bean1"
property="counter" />
</BODY></HTML>
index.jsp
request.jsp
<jsp:useBean id="counter" scope="request"
class="com.visualbuilder.Counter" />
<html>
Uploading Application in JSP.
The request object is used to send the raw data in form of key/value pair to the
server from the browser. What if, we want to send the multipart data i.e. images, files
and binary data to the server. The below example will demonstrate the multiple type
data send to the server.
1. Coding and debugging both are very easy as compared to single file.
2. The code is reused if required in the multiple pages.
3. If any logic becomes obsolete then it can be replaced without disturbing other
components in the application. The following tags are used to add the multiple
JSP pages into one:-
a. <jsp:include>:- The <jsp:include> includes the given file on runtime. When
container encounters this tag, it checks for the JSP file and compile that given
JSP file. The output is then included in the page at runtime. As a result
response time increases to some extent. It is always better to use
<jsp:include> when the JSP page content are dynamically changes and the
restarts of the servers are not done periodically.
b. <%@include%>:- This tag includes the contents of the given file during the
compilation of the JSP file. When the container encounter this tag it will
generate the servlet and include all the contents of the included file to the
servlet. Now if we change the included file then it would not reflect to its
parent page until or unless it is reloaded to the container or the server gets a
restart. So it is always better to use <%@include%> for the static type of the
pages.
Example:-
The below is given the use of the <jsp:include> and also the
<%@include%> tag.
<jsp:include page="coretaglib1.jsp"/><br>
<%@include file="coretaglib2.jsp"%>
The below example will demonstrate the exception handling in the JSP and
use of exception implicit object.
Exceptionhandling.jsp
String s=null;
s.toString();
%>
errorpage.jsp
1. Cookies:-
You can use HTTP cookies to store information about a session. The cookies are
small text files stored in the client side. This is an excellent most widely used
approach. However, even though servlets have a high-level and easy-to-use
interface to cookies, there are still a number of relatively tedious details that need to
be handled, while working with cookies.
2. URL Rewriting:
You can append some extra data on the end of each URL that identifies the session,
and the server can associate that session identifier with data it has stored about that
session. This is also an excellent solution, and even has the advantage that it works
with browsers that don't support cookies or where the user has disabled cookies.
However, it has most of the same problems as cookies, namely that the server-side
program has a lot of straightforward but tedious processing to do.
Example:-
<html>
<form action="formsecurity.jsp" method="post">
<input type="hidden" name="action" value="submit">
Enter the user name :- <input type="text" name="username" ><br>
Enter the password :- <input type="password" name="password"
><br>
<input type="submit" name="submit" value="submit">
</form>
</html>
<%}%>
Security in JSP -1
Security is defined as the condition of being protected against danger or
loss. The security is very important in any web application as the web
applications are mostly exposed to all the people in the world. The levels
of security can be
The web application can be configured to use any level of security as per
the requirement and criticality of the site.
Container Managed
Application Managed
• Authentication and
Authorization are specified in
web.xml.
• It uses multiple authentication
schemes, such as Password
Authentication Form-based
Authentication Client side
Digital Certificates etc..
• Redirects are handled
automatically.
Internationalization in JSP application
Few years back, the sites were developed using a single language and the
developer used to create the sites to their specific languages. As the
globalization occured, many frameworks have developed to support the
multiple languages at a time. Now this can be achieved by having the
multi language text in key/value pair and at runtime the text is read from
the key as per the language required. This multilingual support is known
as Internationalization. Internationalization is defined as the process of
designing an application so that it can be adapted to various languages
and regions without engineering changes.
Note:- The fmt is the jstl tag library used to implement the
internationalization in JSP. The below example will tell you "how to use the
fmt taglib in the application". The example displays the text coming from
the different properties files. The properties file lables.properties is
created with different locale suffix example en is for english, de for
Germany etc. We have hello key in both the files. hello=This is german
File in de file and hello=This is english File in english file.
The following is the EL operator table which can be used with the EL language.
Expression
Result
\${3+2-1}
${3+2-1} <%--
Addition/Subtraction
--%>
\${"1"+2}
${"1"+2} <%--
String conversion --
%>
\${3%2}
${3%2} <%--
Modulo --%>
• JSTL tags are XML based tags which are cleanly and uniformly blend into a
page's HTML markup tags.
• The four JSTL tag libraries include most functionality that would be needed in
a JSP page. JSTL tags are easier for non-programmers and inexperienced
programmers, because they do not require any knowledge of Java
programming.
• JSTL tags encapsulate reusable logic such as formatting dates and numbers.
• JSTL tags can reference objects in the request and session without knowing
the object's type and no casting is required.
• JSP's EL (Expression Language) makes it easy to call getter and setter
methods on Java objects. This is not possible in JSP 1.2, but became
available in JSP 2.0. EL is used extensively in JSTL.
JSTL Drawbacks:
• JSTL can add processing overhead to the server. Both Java scriptlet code and
tag libraries are compiled into a resulting servlet, which is then executed by
Introduction To Core Taglib -1
Core taglib is the important taglib in the JSTL. It includes the core concepts of the
programming like declaring the variable, decision making tags etc.. The next
sections will explain all the core taglib tags, which are generally used in the
programming.
Standard Syntax:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
The <c:set> tag sets the value of an EL variable or the property in any of the JSP
scopes (page, request, session, or application). If the variable does not exists, it will
be created.
The JSP EL variable or property can be set either from the attribute value:
OR
<c:set var="var">
...
</c:set>
Conditional Tags
The <c:if> tag allows the conditional execution of its body according to the value of
the test attribute. The syntax of the <c:if> conditional block is as follows:-
<c:choose>
<c:when test="condition1" >
Introduction To Core Taglib -2
Iterator Tags
The <c:forEach> tag allows you to iterate over a collection of objects. You specify the
collection via "items" attribute, and the current item is available through a variable
named given in the "var" attribute. A large number of collection types are supported
by <c:forEach>, including all implementations of java.util.Collection and
java.util.Map. If given collection is of type java.util.Map, then the current item will be
of type java.util.Map.Entry, which has the following properties:
• key: The key under which the item is stored in the underlying Map
• value: The value that corresponds to the key
Arrays of objects as well as arrays of primitive types (for example, int) are also
supported. For arrays of primitive types, the current item for the iteration is
automatically wrapped with its standard wrapper class (for example, Integer for int,
Float for float, and so on).
URL Tags
The <c:url> tag is used to create the URL for the submit actions or the hyperlinks.
The <c:url> tag is used to create the URL variable and <c:param> is used to add the
parameters in the <c:url> tag. The syntax is as follows:-
<c:url var="var" value="..." >
<c:param name="param1" value="val1" />
</c:url>
Example:-
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
<%
String[] value = new String[10];
value[0]="one";
value[1]="two";
value[2]="three";
value[3]="four";
value[4]="five";
Function Taglib
The function taglib contains the basic String functions for the JSTL functionality.
Standard Syntax:
java.lang.Strin
g
substring (
java.lang.String
, int, int)
Returns a
subset of a
string.
java.lang.String
substringAfte
r(
java.lang.String
,
java.lang.String
Database Handling in JSP.
The database interaction with the JSP page is similar to the core JDBC interaction.
The complete JDBC code for the database interaction is to be written in the scriptlet
tags. The following example shows the process of database handling with the JSP
page. The following example will display the total hit for the current page and update
the counter in the database.
Output:-
ReverseTag.java
package com.visualbuilder.taglibrary;
import java.io.IOException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
CustomTag.jsp file
<html>
<head>
<title>Your Custom Tag library</title>
</head>
<body bgcolor="#ffffff">
<hr />
<reverse:stringreverse>
Visual Builder
</reverse:stringreverse>
<hr />
</body>
</html>
Best Practices in JSP
There are some standard practices that can be followed while writing the
JSP files. The standards of writing JSP code helps to develop the
application easily and effectively. It reduces the complexity and the
debugging time for the JSP application. The following are the best
practices, while working on JSP application:-
• Separate HTML from Java:- For small JSP files with least of logic, it seems
as best to have the Java and html in the same JSP file as all available
resources and dependencies are in the same file. As the JSP's go on to
higher complexity, this approach fails as the code becomes
complex and less readable and hard to understand.
• Place business logic in JavaBeans:- We must write our business logic in
JavaBeans as the code will be reused anywhere in the application. Also if any
logical change occurs during the development so it requires to change only at
one place and hence avoiding rework everywhere.
• Factor general behavior out of custom tag handler classes:- If we are
using custom tags then we must tend to write the common code in a Java file
separately instead of writing inside the customTagHandler. Because Handler
classes are not readily used like ordinary Java utility classes rather Handler
classes can access the utility classes easily.
• Favor HTML in Java handler classes over Java in JSPs:- Sometimes
cleanly separating HTML, JSP tags, and HTML-like custom tags from Java
requires unnecessarily convoluted code. In these cases, you either include
Java scriptlets and expressions in the JSP or put some HTML code in the
Java tag handler class.
• Use an appropriate inclusion mechanism: - The JSP is a combination of
the tags and the Java code. It is very difficult to maintain the two types of code
in a single file. JSP gives us the flexibility to create the multiple JSP pages
and then call those JSP pages into the complex page wherever required.
• Use a JSP template mechanism:- Using templates is the best approach
when we can see the total structural changes in the look and feel of the page.
It is not a good way to change each and every JSP page for the html
changes, rather we will define the layout of the page in a JSP and will use the
templates mechanism to import the contents of different portions from different
JSP's through templates. So, when you want to change the layout, you need
to modify only one template file rather making changes in all pages.
• Use stylesheets:- We must use CSS to give the styles to different
components across the site, providing same CSS styles to similar kind of
components. If we want to change the look of a particular type of component
throughout the website, we are required to change one style only and it will be
reflected everywhere.