0% found this document useful (0 votes)
0 views

Java Server Pages

Java Server Pages (JSP) is a server-side technology used for creating dynamic web applications by embedding Java code in HTML pages. It simplifies coding, reduces code length, and facilitates database connectivity while allowing for interactive and platform-independent web content. JSP includes various components such as directives, declarations, scriptlets, expressions, and action tags, and follows a lifecycle that involves compilation into a servlet and execution to generate HTML output.

Uploaded by

sreeee437
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Java Server Pages

Java Server Pages (JSP) is a server-side technology used for creating dynamic web applications by embedding Java code in HTML pages. It simplifies coding, reduces code length, and facilitates database connectivity while allowing for interactive and platform-independent web content. JSP includes various components such as directives, declarations, scriptlets, expressions, and action tags, and follows a lifecycle that involves compilation into a servlet and execution to generate HTML output.

Uploaded by

sreeee437
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Java Server Pages(JSP)

In Java, JSP stands for Java Server Pages. It is a server-side technology which is used for creating web
applications. It is used to create dynamic web content. This helps developers insert java code in HTML
pages by making use of special JSP tags, most of which start with <% and end with %>.

JSP consists of both HTML tags and JSP tags. In this, JSP tags are used to insert JAVA code into HTML
pages. It is an advanced version of Servlet Technology i.e. a web-based technology that helps us to
create dynamic and platform-independent web pages. In this, Java code can be inserted in HTML/ XML
pages or both. JSP is first converted into a servlet by the JSP container before processing the client’s
request.

Features of JSP

 Coding in JSP is easy : As it is just adding JAVA code to HTML/XML.


 Reduction in the length of Code : In JSP we use action tags, custom tags etc.
 Connection to Database is easier : It is easier to connect website to database and allows to read
or write data easily to the database.
 Make Interactive websites : In this we can create dynamic web pages which helps user to
interact in real time environment.
 Portable, Powerful, flexible and easy to maintain : as these are browser and server
independent.
 No Redeployment and No Re-Compilation : It is dynamic, secure and platform independent so
no need to re-compilation.
Creating a simple JSP Page
JSP simply puts Java inside HTML pages.

JSP Elements(components)
JSP scripting language include several tags or scripting elements that performs various tasks such as
declaring variables and methods, writing expressions, and calling other JSP pages. These are known as
JSP scripting elements. The different types of scripting elements are

JSP Tag Brief Description Tag Syntax


Directive Specifies translation time <%@ directives %>
instructions to the JSP engine.
Declaration Declaration Declares and defines <%! variable dceclaration &
methods and variables. method definition %>
Scriptlet Allows the developer to write free- <% some Java code %>
form Java code in a JSP page.
Expression Used as a shortcut to print values in <%= an Expression %>
the output HTML of a JSP page.
Action Provides request-time instructions <jsp:actionName />
to the JSP engine.
Comment Used for documentation and for <%– any Text –%>
commenting out parts of JSP code.
1. Directive Tag:
The jsp directives are messages that tells the web container how to translate a JSP page into
the corresponding servlet. Directive tags provide general information about the JSP page to the JSP
engine. A directive tag always starts with <%@ and ends with %>.

Syntax of JSP Directive:


<%@ directive attribute="value" %>

There are 3 types of directives: page, include, and taglib.


The general syntax for the 3 directives is:

<%@ page attribute-list %>


<%@ include attribute-list %>
<%@ taglib attribute-list %>

In the above shown syntax, the attribute-list represents one or more attribute value-pairs that are
specific to the directive. Some important points that are needed to be remembered about the syntax of
the directive are as follows:

 The tag names, their attributes, and their values are all case sensitive.
 The value must be enclosed within a pair of single or double quotes.
 A pair of single quotes is equivalent to a pair of double quotes.
 There must be no space between the equals sign (=) and the value.
JSP page directive

A page directive informs the JSP engine about the overall properties of a JSP page. For example, the
following page directives inform the JSP engine that Java will be used as scripting language in our JSP
page:
<%@ page language=”java” %>

Attributes of JSP page directive

o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

1)import
The import attribute is used to import class,interface or all the members of a package.It is similar to imp
interface.

Example of import attribute


<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>

2)contentType

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute

<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>

3)extends

The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.

4)info

This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

Example of info attribute

<html>
<body>
<%@ page info="composed by Sonoo Jaiswal" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

The web container will create a method getServletInfo() in the resulting servlet.For example:

public String getServletInfo() {


return "composed by Sonoo Jaiswal";
}

5)buffer

The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.

Example of buffer attribute

<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

6)language

The language attribute specifies the scripting language used in the JSP page. The default value is
"java".

7)isELIgnored

We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is fal
is enabled by default. We see Expression Language later.
<%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe

Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use isT
directive.The value of isThreadSafe value is true.If you make it false, the web container will serialize the
wait until the JSP finishes responding to a request before passing another request to it.If you make
attribute like:

<%@ page isThreadSafe="false" %>


The web container in such a case, will generate the servlet as:

public class SimplePage_jsp extends HttpJspBase


implements SingleThreadModel{
.......
}

9)errorPage

The errorPage attribute is used to define the error page, if exception occurs in the current page,
it will be redirected to the error page.

Example of errorPage attribute

//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>

10)isErrorPage

The isErrorPage attribute is used to declare that the current page is the error page. The
exception object can only be used in the error page.

Example of isErrorPage attribute

//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
Jsp Include Directive

The include directive is used to include the contents of any resource it may be jsp file, html file
or text file. The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include static
resource).

Syntax of include directive

<%@ include file="resourceName" %>

Example of include directive

In this example, we are including the content of the header.html file. To run this example you
must create an header.html file.

<html>
<body>

<%@ include file="header.html" %>

Today is: <%= java.util.Calendar.getInstance().getTime() %>

</body>
</html>

Example

A good example of the include directive is including a common header and footer
with multiple pages of content.

Let us define following three files (a) header.jsp, (b)footer.jsp, and (c)main.jsp as follows

Following is the content of header.jsp −

<%!
int pageCount = 0;
void addCount() {
pageCount++;
}
%>

<% addCount(); %>

<html>
<head>
<title>The include Directive Example</title>
</head>

<body>
<center>
<h2>The include Directive Example</h2>
<p>This site has been visited <%= pageCount %> times.</p>
</center>
<br/><br/>

Following is the content of footer.jsp −

<br/><br/>
<center>
<p>Copyright © 2010</p>
</center>
</body>
</html>

Finally here is the content of main.jsp −

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


<center>
<p>Thanks for visiting my page.</p>
</center>
<%@ include file = "footer.jsp" %>

JSP Taglib directive

The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD
(Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it
will be better to learn it in custom tag.

Syntax JSP Taglib directive

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive

In this example, we are using our tag named currentDate. To use this tag we must specify the
taglib directive so the container may get information about the tag.

<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>

2. Declaration Tag
Declarations declare and define variables and methods that can be used in the JSP page (a JSP
declaration can contain any valid Java declaration including inner classes and static code blocks.
However, such declarations are rarely used). A declaration always starts with <%! and ends with %>.
For e.g.: <%! int i = 0; %>
This declares an integer variable i and initializes to 0. The variable is initialized only once when the page
is first loaded by the JSP engine, and retains its value in subsequent client requests i.e. the value of i is
not reset to 0 each time we access the page. It can contain any number of valid Java declaration
statements. For example, the following tag declares a variable and a method in a single tag:

<%!
String name[] = {“biswa”, “amit”, “sreejan”};

String getName(int i) {
return name[i];
}
%>

The above declaration can also be written using two separate JSP declaration tags.

3. Scriptlet Tag:
Scriptlets are used to embed any Java code fragments in the JSP page.

For example: <% i++; %>


Here the scriptlet tag is executed and the value of i is incremented each time the page is requested. We
can use scriptlets for printing HTML statements also. For e.g.

<%@ page language="java" %>


<%! int i = 0; %>
<%
i++;
out.print("The value of i is now: " + i);
%>

Output:

The value of i is now: 1


4. Expression Tag:
Expression tags are used as a shortcut to print values in the output HTML in a JSP page. Expression tag is
used, to find the result of the given expression and send that result back to the client browser. We can
use this as a display result of variable and invoking method.

Each Expression tag of jsp will be internally converted into out.print() statement. In jsp out is an implicit
object.

The expression tags are converted into out.print() statement and insert into the _jspService(-,-) of the
servlet class by the container.
The expression tags written in a jsp are executed for each request, because _jspService(-,-) is called for
each request.
One expression tag should contains one java expression only. In a jsp we can use expression tag for any
number of times.

Syntax of Expression tag is:

<%= variable %>


The variable denotes the variable value that is needed to be printed in the output HTML page. For e.g.:
<%= i %>

The expression is evaluated each time the page is accessed, and its value is then embedded in the
output HTML. Unlike variable declarations, expressions must not be terminated with a semicolon. Thus,
the following is not valid: <%= i; %>

The below tables denotes some valid and invalid JSP expressions:

Valid JSP Expressions:

Expression Explanation

<%= 500 %> An integral literal

<%= anInt*3.5/100-500 %> An arithmetic expression

<%= aBool %> A Boolean variable

<%= false %> A Boolean literal

<%= !false %> A Boolean expression

<%= getChar() %> A method returning a char

<%= Math.random() %> A method returning a double


<%= aVector %> A variable referring to a Vector object

<%= aFloatObj %> A method returning a float

<%= aFloatObj.floatValue() %> A method returning a float

<%= aFloatObj.toString() %> A method that returns a String object

Invalid JSP expressions:

Expression Explanation

<%= aBool; %> We cannot use a semicolon in an expression

<%= int i = 20 %> We cannot define anything inside an expression

<%=sBuff.setLength(12);
%> The method does not return any value. The return type is void

Example1:

index.jsp

<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Output:
Value of the variable is:50

Example2:

index.jsp

<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

Output:
Cube of 3 is:27

5. Action Tag:
Action tags are used to provide request–time instructions to the JSP container or JSP engine. There are 7
types of action tags. The following table describes various JSP action tags:

JSP Action Tags Description

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include


mostly.

jsp:fallback can be used to print the message if plugin is working. It is used


in jsp:plugin.

6. Comment Tag:

Comments are used for documentation purposes but do not affect the output of the JSP page in any
way. The syntax of a JSP comment is:

<%-- Anything you want to be commented --%>


JSP life cycle

JSP pages follow a life cycle that begins when the page is first requested. During
the life cycle, the Java Server Page is compiled and executed. The page is then
cached and can be promptly accessed the next time it is requested.

The life cycle includes the following steps:

1. The client accesses the JSP page.

2. The JSP page is compiled into a servlet by the JSP engine.

3. The web server executes the Servlet.

4. The Servlet generates HTML output, which is sent back to the client.

JSP Control Statements


The flow of control statements in Java Server Pages are
 if else
 for loop
 while loop
 switch

IF...ELSE
JSP allows to use IF ELSE conditional statement as a programming logic of scriptlet tag. Apart from
that, IF can also be used in many other ways like nested IF or standalone IF. Here is a simple
example of IF ELSE statement.

<%! int num=8; %>

<% if(num%2==0)

out.println("Number is even"); }

else

{ out.println("Number is odd"); } %>

For Loop
Here, is a simple example of for loop.
<% for(int i=0;i<5;i++)
{ for(int j=1;j<=i+1;j++)
{ out.print(j); }
out.print(" "); } %>
While loop
Here, is a simple example of while loop.
<%! int i=0; %>
<% while(i<4)
{ i++;
out.print(i+" "); } %>
Switch Statement
Switch is used to maintain the flow of control statement. It contains various cases with one default
case. The default case will execute only once, when none other case satisfies the condition. Here, is
a simple example of switch statement.
<%! int weekday=4; %> <% switch(weekday)

{ case 1: out.print("Monday"); break;

case 2: out.print("Tuesday"); break;

case 3: out.print("Wednesday"); break;

case 4: out.print("Thursday"); break;

case 5: out.print("Friday"); break;


case 6: out.print("Saturday"); break;

default: out.print("Not a weekday"); break; } %>

You might also like