You are on page 1of 53

Introduction to JSP :JavaServer Pages (JSP) is a technology based on the

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.

Why use JSP?

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.

Main reasons to use JSP:

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.

By having a separation of presentation and implementation,web designers


work only on the presentation and Java developers concentrate on
implementing the application.
JSP compared to ASP

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.

JSP compared to ASP.NET

ASP.NET is based on the Microsoft .NET framework. The .NET framework


allows applications to be developed using different programming languages
such as Visual Basic,C# and JavaScript. JSP and Java still has the advantage
that it is supported on many different platforms and the Java community has
many years of experience in designing and developing Enterprise quality
scalable applications. This is not to say that ASP.NET is bad,actually it is quite
an improvement over the old ASP code.

JSP compared to Servlets

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.

Using JSP tags

There are five main tags:

1. Declaration tag
2. Expression tag
3. Directive tag
4. Scriptlet tag
5. Action tag

Declaration tag ( <%! %> )

This tag allows the developer to declare variables or methods.

Before the declaration you must have <%!

At the end of the declaration,the developer must have %>

Code placed in this tag must end in a semicolon ( ; ).

Declarations do not generate output so are used with JSP expressions or


scriptlets.

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

Directive tag ( <%@ directive ... %>)

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.

For example,you can make session data unavailable to a page by setting a


page directive (session) to false.

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:

Which language the file uses. <%@ page language =


"java" %>

language

Superclass used by the JSP <%@ page extends =


extends engine for the translated "com.taglib... %>
Servlet.

Import all the classes in a <%@ page import =


import java package into the current "java.util.*" %>
JSP page. This allows the JSP
page to use other java
classes.
Does the page make use of Default is set to true.
session sessions. By default all JSP
pages have session data
available. There are
performance benefits to
switching session to false.

Controls the use of buffered <%@ page buffer = "none"


buffer output for a JSP page. Default %>
is 8kb

Flush output buffer when full. <%@ page autoFlush =


autoFlush "true" %>

Can the generated Servlet


isThreadSa deal with multiple requests?
fe If true a new thread is started
so requests are handled
simultaneously.

Developer uses info attribute <%@ page info =


info to add information/document "visualbuilder.com test
for a page. Typically used to page,copyright 2001. " %>
add author,version,copyright
and date info.

Different page to deal with <%@ page errorPage =


errorPage errors. Must be URL to error "/error/error.jsp" %>
page.
This flag is set to true to
IsErrorPage make a JSP page a special
Error Page. This page has
access to the implicit object
exception (see later).

Set the mime type and


contentTyp character set of the JSP.
e

2. Include directive

Allows a JSP developer to include contents of a file inside another. Typically


include files are used for navigation,tables,headers and footers that are
common to multiple pages.

Two examples of using include files:

This includes the html from privacy.html found in the include directory into
the current jsp page.

<%@ include file = "include/privacy.html" %>

or to include a naviagation menu (jsp file) found in the current directory.

<%@ include file = "navigation.jsp" %>

Include files are discussed in more detail in the later sections of this tutorial.

3. Tag Lib directive

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.

For example,to print a variable.

<%
String username = "visualbuilder" ;
out.println ( username ) ;
%>

Action tag

There are three main roles of action tags :

1) enable the use of server side Javabeans

2) transfer control between pages

3) browser independent support for applets.

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).

To use a Javabean in a JSP page use the following syntax:

<jsp : usebean id = " ...." scope = "application" class = "com..." />

The following is a list of Javabean scopes:

page - valid until page completes.

request - bean instance lasts for the client request

session - bean lasts for the client session.

application - bean instance created and lasts until application ends.

Creating your second JSP page


For the second example,we will make use of the different tags we have
learnt. This example will declare two variables; one string used to stored the
name of a website and an integer called counter that displays the number of
times the page has been accessed. There is also a private method declared
to increment the counter. The website name and counter value are
displayed.

<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;
}
%>

This is a loop example from the

<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.

The implicit objects are


Variable Of type

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

Stores the Servlet configuration data.

Request object

Access to information associated with a request. This object is normally used


in looking up parameter values and cookies.

<% String devStr = request.getParameter("dev"); %>

Development language = <%= devStr %>


This code snippet is storing the parameter "dev" in the string devStr. The
result is displayed underneath.

Creating a Form

Here we show how to create and process an html form.

Copy the code below and place in a file named: myform.jsp

Go to myform.jsp in your browser

You will see the form you just created.

It won't do anything yet.


<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>
</head>
<body>
<form action="myformconfirm.jsp" method="post">
Enter in a website name:<br>
<input type="text" name="website"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

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>

Creating a Form (more elements)

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>

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>
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>

Getting Client Info

You can get information about a clients computer


Copy the code below and place in a file named: clientinfo.jsp
Run it from your browser -clientinfo.jsp
You should see the results of your submission
<html>
<head>
<!-- Example5 -->
<title>VisualBuilder.com</title>
</head>
<body>
Client computer details:
<br><br>
<b>Ip address</b>:
<br>
<%=request.getRemoteAddr()%>
<br><br>
<b>Computer name</b>:
<br>
<%=request.getRemoteHost()%>
<br><br>
</body>
</html>

Beans scopes in JSP


JavaBeans are reusable components. It represents a simple Java class with some
properties. The bean properties are accessed by Getter and Setter method. They are
used to separate Business logic from the Presentation logic. Internally, a bean is just
an instance of a class. The JSP specification provides three basic tags for working
with Beans :-

jsp:useBean id="bean name" class="bean class" scope = "page | request |


session |application "/>

• <jsp:setProperty name = "bean name" property = "someProperty"


value = "someValue" />

• <jsp:getProperty name = "bean name" property = "someProperty"


/>

Where bean name = the name that refers to the bean.


Bean class = name of the java class that defines the bean.
property = name of the property to be passed to the bean.
value = value of that particular property.

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 .

(1) Page Scope

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>

(1) Request Scope

index.jsp

<jsp:useBean id="counter" scope="request"


class="com.visualbuilder.Counter" />
<html>
<head>
<title>Request Bean Example</title>
</head>
<body>
<%
counter.setCounter(10);
%>
<jsp:forward page="request.jsp" />
</body>
</html>

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.

<%@ page import="java.io.*"%>


<%
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data")
>= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();

byte dataBytes[] = new byte[formDataLength];


int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,
formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") +
1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex +
1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
Modularization in JSP
These days, users expect feature rich online applications and companies
need flexible application design to deal with complex business rules. The
day of having a single code file with all the application are gone.
Modularization is the splitting up of complex code into separate modules
of code. The following are the advantages of the modularization:-

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

Exception Handling in JSP-1


Exception Handling in JSP-2
The second way is to define the error page in the page directive as "<%@
page errorPage="errorpage.jsp" %>" and creating the error page. When
any exception or error occurs while processing the JSP page then the
container automatically calls the error page and redirects the flow to it.
Any page can be used to show the errors.Users have to set the
ErrorPage="true" property on the page directive for example:-<%@ page
isErrorPage="true" %> for error pages. While processing an error page an
implicit object named "exception" automatically created for the page,
which is used to display the error messages.

The below example will demonstrate the exception handling in the JSP and
use of exception implicit object.

Exceptionhandling.jsp

<%@ page errorPage="errorpage.jsp" %>


<%

String s=null;
s.toString();

%>

errorpage.jsp

<%@ page isErrorPage="true" %>

This is the Error page.The following error occurs:- <br>


<%= exception.toString() %>
Session Tracking in JSP
In any web application, a user moves from one page to another. So, it is necessary
to track the user's data and objects throughout the application. As we know that the
session keeps the data particular to a user, so sessions are used to hold the user's
data. For sessions JSP provide an implicit object "session", which can be use to
save the data specific to the particular user into the session scope.

There are mainly 4 ways for session Tracking as follows:

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.

3. Hidden form fields:


HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN"
NAME="session" VALUE="...">. This means that, when the form is submitted, the
specified name and value are included in the GET or POST data. This can be used
to store information about the session. However, it has the major disadvantage that it
only works if every page is dynamically generated, since the whole point is that each
session has a unique identifier.
Security in JSP -2
The user can also use the html forms to accept the username and
password. This helps to establish the application level or module level
security in web world. All sites follow the different security policies and
standards. It is always better to use the application managed security for
better results. Also, when the application is moved to some other servers
then it hardly impacts the application managed security. The following
example will demonstrate a form and shows the welcome message if user
enters the correct username and password.

Example:-

<% String action= request.getParameter("action");


if(action != null && action.equals("submit")){
String username=request.getParameter("username");
String password=request.getParameter("password");
if(username != null && password != null &&
username.equals("visualbuilder") && password.equals("test"))
{
out.println("<h3>welcome to the page</h3>");
}else{
out.println("<h3>Wrong password!!!!</h3>");
}
}else{
%>

<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

• Transport Level security using HTTPS.


• Authentication and Authorization
• Role Based Access Control
• Container-managed Security
• Application-managed Security.

The web application can be configured to use any level of security as per
the requirement and criticality of the site.

Container Managed Security Vs Application Managed

Implementation For Container Managed


Implementation For Application Managed

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.

The following classes are used to implement Internationalization to any


site.

• Locale - The fundamental Java class that supports internationalization is


Locale . Each Locale represents a particular choice of country and language,
and also a set of formatting assumptions for things like numbers and dates.
• ResourceBundle - The java.util.ResourceBundle class provides the
fundamental tools for supporting messages in multiple languages.
• PropertyResourceBundle - One of the standard implementations of
Resource Bundle allows you to define resources using the same
"name=value" syntax used to initialize properties files. This is very convenient
for preparing resource bundles with messages that are used in a web
application, because these messages are generally text oriented.

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.

Example JSP file Internationalization.jsp file .

<%@ taglib prefix="fmt" uri="/WEB-INF/fmt.tld"%>


Introduction To Expression Language.
A primary feature of JSP technology version 2.0 is its support for an expression
language (EL). An expression language makes it possible to easily access
application data stored in JavaBeans components. As the EL is introduced in JSP
2.0, we can also use the page attribute isELIgnored to ignore the EL for a page.

<%@ page isELIgnored ="true|false" %>

The following is the EL operator table which can be used with the EL language.

Note:- and,eq,gt,true,instanceof,or,ne,le,false,empty, not,lt,ge,null,div and mod are


reserved words in the EL so user cannot use these words for the identifiers.

Expression
Result

\${3+2-1}
${3+2-1} <%--
Addition/Subtraction
--%>

\${"1"+2}
${"1"+2} <%--
String conversion --
%>

\${1 + 2*3 + 3/4}


${1 + 2*3 + 3/4}
<%-- Mult/Div --%>

\${3%2}
${3%2} <%--
Modulo --%>

\${(8 div 2) mod 3}


${(8 div 2) mod 3}
<%-- Compares with
"equals" but returns
Introduction to Tag libraries
JSTL is a component technology within the Java 2 Enterprise Edition (J2EE)
specification and is controlled by Sun Microsystems. JSTL is nothing more than a set
of simple and standard tag libraries that encapsulates the core functionality
commonly needed when writing dynamic JSP pages. The following are the problems
with the JSPs:-

1. Java code embedded within scriptlet tags is ugly and obtrusive.


2. It is very difficult to modify the java code embedded in the JSP files if the file is
large.
3. Java code within JSP scriptlets cannot be reused by other JSP pages.
4. Retrieving objects out of the HTTP request and session is cumbersome and
type casting to the object's class is required.

The JSTL tags are basically categorized into four libraries:

• core:- Basic scripting functions such as loops, conditionals, and input/output.


• fmt:- Internationalization and formatting of values such as currency and
dates.
• xml:- XML processing
• sql:- Database access.

Advantages of using JSTL:-

• 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" %>

Variable Support Tags

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:

<c:set var="var" scope="session" value="..."/>

OR

<c:set var="var">
...
</c:set>

To remove an EL variable, you use the <c:remove> tag as follows:

<c:remove var="test" scope="session"/>

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:if test="${condition}"> </c:if>

The <c:choose> tag performs conditional block execution by the embedded


<c:when> tags. It renders the body of the first <c:when> tag whose test condition
evaluates to be true. If none of the test conditions evaluates to be true, then the body
of <c:otherwise> tag is evaluated, if present. The syntax 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).

<c:forEach var="item" items="collection">


</c:forEach>
or
<c:forEach begin="0" end="10" varStatus="status" step="1" >
</c:forEach>

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:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

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.

<%@page import="java.sql.*" %>


<%
int hitCount=0;
try{
Class.forName("org.gjt.mm.mysql.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
"root");
Statement statement = connection.createStatement();
int changed = statement.executeUpdate("update counters set
hitCount = hitCount + 1 " +"where page like '" + request.getRequestURI() +
"'");
if (changed == 0) statement.executeUpdate("insert counters(page)
values('" + request.getRequestURI() + "')");
ResultSet rs = statement.executeQuery("select hitCount from counters
where page like '" + request.getRequestURI() + "'");
rs.next();
hitCount = rs.getInt(1);
}catch(Exception e ){
}finally{
statement.close();
connection.close();
}
out.println("The hit count is " +hitCount );
%>

Output:-

The page prints "The hit count is 5" as output.


Creating User Defined Custom Tag -1
The most powerful feature of JSP is that - the user can also create their
own custom tags. The servlet API contains the
javax.servlet.jsp.tagext.BodyTagSupport class, which is used to create the
custom tags. All the tags need to extend the
javax.servlet.jsp.tagext.BodyTagSupport class and override doStartTag(),
doEndTag() and doAfterBody() methods. After creating the Java class for
the custom tag, the tag library description file is to be created. The
extension for the XML description file is .tld. The following example will
create a tag, which takes String and prints the reverse of the String when
displayed on the browser.

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;

public class ReverseTag extends BodyTagSupport {

private static final long serialVersionUID = 1L;

public int doStartTag() throws JspTagException{


return EVAL_BODY_TAG;
}
public int doEndTag() throws JspTagException {
try {
JspWriter out = pageContext.getOut();
} catch (Exception ex) {
throw new JspTagException("All is not well in the world." + ex);
}
return SKIP_BODY;
}

public int doAfterBody() throws JspTagException {


Creating User Defined Custom Tag -2
The following is the tag lib descriptor file for the reverse tag.

<?xml version="1.0" encoding="ISO-8859-1" ?>


<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>Visualbuilder</shortname>
<info>Visual builder Tag library</info>
<tag>
<name>stringreverse</name>
<tagclass>com.visualbuilder.taglibrary.ReverseTag </tagclass>
<info>
This is a simple tag which will reverse the text.
</info>
<!-- Optional attributes -->
</tag>
</taglib>

CustomTag.jsp file

<%@ taglib uri="/WEB-INF/reverse.tld" prefix="reverse" %>

<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.

You might also like