KEMBAR78
Java Server Pages (JSP) | PDF | Java (Programming Language) | Computer Programming
0% found this document useful (0 votes)
6 views31 pages

Java Server Pages (JSP)

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

Java Server Pages (JSP)

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

Java Server Pages (JSP)

Introduction to JSP
• Java Server Pages (JSP) is a programming(JSP is a server-side programming technology)
tool on the application server side that supports platform-independent and dynamic methods to
construct Web-based applications.
• Inserting Java code into the HTML pages by making special JSP tags. The JSP tags which
allow java code to be included into it are <% —-java code—-%>.
• This allows programmers to use specific JSP tags to insert Java code into HTML pages.
• Dynamic content includes some fields like dropdown, checkboxes, etc. whose value will be
fetched from the database.
A JSP becomes a Servlet
• JSP pages are converted into Servlet by the Web Container. The Container translates a JSP
page into servlet class source(.java) file and then compiles into a Java Servlet class.
Why JSP is prefered over servlets?
• JSP provides an easier way to code dynamic web pages.
• JSP does not require additional files like, java class files, web.xml etc
• Any change in the JSP code is handled by Web Container(Application server like
tomcat,Glassfish), and doesn't require re-compilation.
• JSP pages can be directly accessed, and web.xml mapping is not required like in servlets.

Advantage of JSP
• Easy to maintain and code.
• High Performance and Scalability.
• JSP is built on Java technology, so it is platform independent.
Disadvantages of JSP technology
• It is difficult to debug.
• It needs to handle the concurrency issues.
JSP Life Cycle
A JSP page is converted into Servlet in order to service requests. The translation of a JSP page
to a Servlet is called Lifecycle of JSP.
The Life Cycle starts with the creation of JSP and ends with the disintegration of that.
 Following are the JSP Lifecycle steps:
• Translation of JSP page
• Compilation of JSP page(Compilation of JSP page into _jsp.java)
• Classloading (_jsp.java is converted to class file _jsp.class)
• Instantiation(Object of generated servlet is created)
• Initialisation(_jspinit() method is invoked by container)
• Request Processing(_jspservice() method is invoked by the container)
• Destroy (_jspDestroy() method invoked by the container)
JSP Lifecycle diagram.
Translation of the JSP Page:
A Java servlet file is generated from a JSP source file. This is the first step of JSP life cycle. In
translation phase, container validates the syntactic correctness of JSP page and tag files.
• demo.jsp is translated to demo_jsp.java in the first step
Let’s take an example of “demo.jsp” as shown below:
Demo.jsp
<html>
<head>
<title>Demo JSP</title>
</head>
<% int demvar=0;%>
<body>
Count is:
<% Out.println(demovar++); %>
<body>
</html>
Compilation of the JSP Page
• The generated java servlet file is compiled into java servlet class
• The translation of java source page to its implementation class can happen at any time between the
deployment of JSP page into the container and processing of the JSP page.
• demo_jsp.java is compiled to a class file demo_jsp.class
Classloading
• Servlet class that has been loaded from JSP source is now loaded into the container
Instantiation
• In this step the object i.e. the instance of the class is generated.
• The container manages one or more instances of this class in the response to requests and other
events. Typically, a JSP container is built using a servlet container. A JSP container is an extension of
servlet container as both the container support JSP and servlet.
Initialization
public void jspInit()
{ //initializing the code }
• _jspinit() method will initiate the servlet instance which was generated from JSP and will be invoked
by the container in this phase.
Request processing
void _jspservice(HttpServletRequest request HttpServletResponse response)
{ //handling all request and responses }
• _jspservice() method is invoked by the container for all the requests raised by the JSP page during its
life cycle
• For this phase, it has to go through all the above phases and then only service method can be invoked.
• It passes request and response objects
• It is responsible for generating of all HTTP methods i.eGET, POST, etc.
Destroy
public void _jspdestroy()
{ //all clean up code }
• _jspdestroy() method is also invoked by the container
• This method is called when container decides it no longer needs the servlet instance to service
requests.
• When the call to destroy method is made then, the servlet is ready for a garbage collection.This is the
end of the life cycle.
Difference between Servlet vs JSP
Servlet JSP
JSP runs slower than servlet as it takes time to compile the program and
Servlets run faster than JSP.
convert into servlets.

It is hard to write code in servlet. It’s easier to code in JSP compared to servlets.

In MVC architecture, servlet works as a controller. In MVC architecture, JSP works as a view for displaying output.

JSP is generally used when there is no involvement of much data


It should be use when there is more data processing involved.
processing.

There is no custom tag writing facility in servlets. You can easily build custom tags that can directly call Java beans.
Servlet is a java code. JSP is a HTML-based code.
It can accept all protocol requests, including HTTP. It can only accept HTTP requests.

You can override the service() method. In JSP, you can’t override the service() method.

In Servlet, by default, session management is not enabled, user has to


In JSP, session management is automatically enabled.
enable it explicitly.

In Servlet, you have to implement both business logic and presentation


In JSP, business logic is split from presentation logic using JavaBeans.
logic in the single file.

Modification in Servlet file is a time consuming due to reloading,


JSP modification is fast, as you just need to click one refresh button.
recompiling, and restarting the server.
Syntax
• A JSP syntax can contain Java language statements, variable or method declarations, or expressions that are
valid in the page scripting language.
syntax to include Scriptlet in JSP.
<% code fragment %>
For example,
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body> </html>
Implicit objects example program
<html lang="en"> //login.jsp Login.html
<head>
<html lang="en">
<title>Login page</title>
</head> <head>
<body> <title>Login page</title>
<h1> Login Form </h1>
<% String name=request.getParameter("n1");//will return value </head>
String pwd=request.getParameter("n2"); <body>
//out.println("Welcome "+name);
<h1> Login Form </h1>
if(name.equalsIgnoreCase("chandu")&&pwd.equalsIgnoreCase("rvr"))
<form method="post" action="./login.jsp">
{
out.println("succeusfully login"+name); Username: <input type="text" name="n1"><br>
out.println("<br><img Password: <input type="password"
src=chandu.jpg;width=100;height:100;/>");
name="n2"><br>
} <input type="submit" name="b1"
else value="login"><br>
{
out.println("unsucceusfully login"+name);
<input type="reset" name="b2"
out.println("<br><img src=chandu1.png; width=500;height:500;/>"); value="clear"><br>
} </form>
%>
</body>
</body>
</html> </html>
Jsp Elements
• JSP elements are called the JSP tags on JSP page. On the JSP page mainly three groups of JSP
elements are used :
JSP Scripting Elements
JSP Directive Elements
JSP Standard Action Elements
JSP Directive Elements
• Directives supply directions and messages to a JSP container. The directives provide global
information about the entire page of JSP.
• Directives can contain several attributes that are separated by a comma and act as key-value
pairs.
• In JSP, directives are described with a pair of <%@ .... %> tags.
The syntax of Directives looks like: <%@ directive attribute="" %>
There are 3 types of directives:
Page directive
Include directive
Taglib directive
Page directive
The page directive is used for defining attributes that can be applied to a complete JSP page. You may place your
code for Page Directives anywhere within your JSP page
The basic syntax of the page directive is:
<%@ page attribute = "attribute_value" %>
The attributes used by the Page directives are:
Attributes of JSP page directive

1.Import 2. contentType 3.extends 4.info 5.buffer 6.language 7.isELIgnored 8.isThreadSafe


9.autoFlush 10.session 11.pageEncoding 12.errorPage 13.isErrorPage
Import: The import attribute is used to specify a list of packages or classes used in JSP code, just as Java's import
statement does in a Java code.
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
ContentType: The ContentType attribute defines the document's MIME (Multipurpose Internet Mail
Extension) in the HTTP response header.
<html>
<body>
<%@ page contentType="tex/java"%>
Today is: <%= new java.util.Date() %>
</body>
</html>
Info: This "info" attribute sets the JSP page information
<html>
<body>
<%@ page info="composed by chandu" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
isErrorPage: This "isErrorPage" attribute of the Page directive is used to specify that the current page can
be displayed as an error page.
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
errorPage: Defining the "ErrorPage" attribute is the correct way to handle JSP errors. If an exception
occurs on the current page, it will be redirected to the error page.
<html>
<body>
<%@ page errorPage="iserror.jsp" %>
<%= 100/0 %>
</body>
Include directive
The JSP "include directive" is used to include one file in another JSP file. This includes HTML, JSP, text,
and other files. This directive is also used to create templates according to the developer's requirement and
breaks the pages in the header, footer, and sidebar.
Syntax:<%@ include file = "relative url" >
Ex:
<%@ include file="date.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Include Directive Example</title>
</head>
<body>
<p>This file includes a header file named date.jsp</p>
</body>
</html>
Taglib
The JSP taglib directive is implemented to define a tag library with "taglib" as its prefix. Custom tag
sections of JSP use taglib. JSP's taglibdirective is used as standard tag libraries.
Syntax:<%@ taglib uri="uri" prefix="value"%>
Ex:
<%@ taglib uri = "http://www.chandu.com/custlib" prefix = “cstag" %>
<!DOCTYPE html>
<html>
<body>
<mytag: hi/>
</body>
</html>
Scripting elements in JSP
JSP Scripting Elements are often wont to provide code in JSP pages. All the JSP Scripting Elements are
going to be resolved at the time of request processing. The majority of Scripting Elements will give a
direct effect on response generation.
There are four types of Scripting Elements
Declarations Scriptlets Expressions Comments
Declarations
• declaration tag is a piece of Java code for declaring variables, methods and classes.
• If we declare a variable or method inside declaration tag it means that the declaration is made inside
the servlet class but outside the service method.
• We can declare a static member, an instance variable (can declare a number or string) and methods
inside the declaration tag.
Syntax of JSP Declarations : <%! declaration; ... %>
Simple example for JSP Declarations:
<%! int i = 0; %>
<%! int a, b, c; %> <%! YourClass a = new YourClass(); %>
Examples
Declare1.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Declare2.jsp
<html>
<head>
<title>Declaration</title>
</head>
<body>
<h3>--Welcome--</h3>
<h3>Use of Declaration in JSP</h3>
<%!int num1 = 2, num2 = 3, n = 0;%>
<%
n = num1 + num2 + 1;
out.println("The number after adding declared variables is " + n);
%>
</body>
</html>
JSP Expression
• A JSP expression element contains a scripting language expression that is evaluated, converted to a String.
• The expression element can have any valid Java expression without a semicolon at the end
syntax of JSP Expression : <%= expression %>
Example of jsp expression tag : <%= "welcome to jsp" %>
Expres.jsp
<html>
<head>
<title>jsp Expression</title>
</head>
<body>
<% out.println("The expression number is "); %>
<% int num1=10; int num2=10; int num3 = 20; %>
<%= num1*num2+num3 %>
</body>
</html>
Scriptlet
• A JSP scriptlet can contain Java language statements, variable or method declarations, or expressions that
are valid in the page scripting language.
• JSP container moves statements in _jspservice() method while generating servlet from jsp.
• For each request of the client, service method of the JSP gets invoked hence the code inside the Scriptlet
executes for every request
syntax to include Scriptlet in JSP: <% code fragment %>
For example,
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
Scriptlet.jsp JSP Comments
<html> • Comments are marked as text or statements that are ignored
<head> by the JSP container.
<title>Scriplet</title> • They are useful when you want to write some useful
</head> information or logic to remember in the future.
<body> The syntax of JSP comments: <%-- This is JSP comment --%>
<% int num1=10; The following JSP has a JSP Comment.
int num2=40; <html>
int num3 = num1+num2; <body>
out.println("Scriplet Number is " +num3); <%-- This is a comment in the page.--%>
%> </body>
</body> </html>
</html> // note:<!-- comment --> is an HTML comment. Ignored by
the browser.
JSP Action Tags
• JSP specification provides the action tags to control the behaviour of the servlet engine, to control
page flow, to dynamically insert a file, to reuse JavaBeans components etc. jsp: is used as prefix.
• They perform some specific tasks and are predefined. They provide functionalities like-
Dynamic insertion of a file
Controlling behavior of the servlet engine
Forwarding a user to another page
Controlling flow between pages
Common Syntax: <jsp:action_name attribute=”value”/>
• There are in all eleven JSP action tags. They are:
jsp:include jsp:useBean jsp:setProperty jsp:getProperty jsp:forward
jsp:plugin jsp:body jsp:text jsp:element jsp:param jsp:attribute jsp:output
Common attributes of all action tags:
1. id attribute: This attribute is used to uniquely identifying the action element inside the jsp page.
2. scope attribute: This attribute is used identifying the lifecycle of the action element.
jsp:include
This "include action" allows you to include another resource in the page being generated.
This action will include the required resources like html, servlets and JSP.
There are two attributes under include:
• Page: its value is the url of the required resource.
• Flush: it checks that the buffer of the resource is flushed before it is included.
Syntax: <jsp:include page="page URL" flush="true/false">
<html> //actioninclude.jsp date.jsp
<head>
<title>JSP Actions</title>
</head>
<body>
<h3>--DataFlair--</h3>
<jsp:include page="date.jsp" flush="true" />
</body>
jsp:forward
• This action as the name suggests forwards the request to another page.
• It is used to forward the request to another jsp or any static page.
• Here the request can be forwarded with no parameters or with parameters.
Syntax:
main.jsp
<jsp:forward =“otherpage.jsp”>
Forward.jsp other.jsp
<html>
<head>
<title>JSP Forward</title>
</head>
<body>
<a>I was the requested page but forwarded the request to other</a>
<jsp:forward page="other.jsp" />
</body>
Jsp:param
This "param action" is used for setting the parameter for (forward or include) value.
Syntax:<jsp: param name = "param_name" value = "value_of_parameter" />
Ex: pram.jsp forward.jsp
<html>
<head>
<title>Example of param Action</title>
</head>
<body>
<h2>JSP page: Param with forward</h2>
<jsp:forward page="forward.jsp">
<jsp:param name="date1" value=“21-04-2024" />
<jsp:param name="time" value="10:30am" />
<jsp:param name="data" value="CHANDU" />
</jsp:forward>
</body>
jsp:useBean
The useBean action first searches for an existing object using the id and scope attributes. If an object is not found,
it then will create the specified object.
syntax: <jsp:useBean id="name" class="java.lang.String" />
It has following attributes:
• Class: Creates object of bean class.
• Type: It gives the data type to the bean existing in the specified scope. It is used with class and beanName.
• beanName: Uses the java.beans.Beans.instantiate() method and instantiates bean.
jsp:setProperty
The setProperty action sets the properties of a Bean.
Syntax:<jsp:useBean id="myName" ... />
<jsp:setProperty name="myName" property="someProperty" .../>
This has four attributes:
• name: It is literally the name of the bean whose property we want to set. It has the same name as the object we
instantiated using usebean.
• property: sets the property of the bean “*” means all the requests that match bean properties are included.
• value: gives specific value to the bean.
• Param: a name that will fetch the value .
java:getProperty
• This action gets the value of the property and gives it out on the output as a string.
To get the property of a bean, bean and its name must be defined. Our main purpose is to get the
value of the property where the property is the name of the bean property that was set by setProperty
as well.
Syntax:<jsp:useBean id="myName" ... />
...
<jsp:getProperty name="myName" property="someProperty" .../>
The attributes used by getProperty are
• name: It gets the name of the bean whose property we need to get as its value.
• property: It defines the name of the property required for the bean.
Ex: bean.jsp
<%@page "import StudentBean.Student"%>
<html>
<head>
<title> Jsp Java Beans </title>
</head>
<body>
<marquee> JaP JAVA BEANS </marquee>
<jsp:UseBean id="StudentBean” class="StudentBean.Student"/>
<jsp:setProperty name="StudentBean" property="name" value=“chandu"/> GET NAME:
<jsp:getProperty name="StudentBean" property="name"/></br>
<jsp:setProperty name="StudentBean" property="rollno" value="841"/>ROLL NO :
<jsp:getProperty name="StudentBean" property="rollno"/> </br>
<jsp:setProperty name="StudentBean" property="email" value=“chandu.yahoo.com"/> GET
EMAIL :
<jsp:getProperty name="StudentBean" property="email"/>
</jsp:UseBean>

</body>
studentBean.java public void setRollno(int rollno)
package Student; {
public class Student
this.rollno=rollno;
{
}
int rollno;
public String getName( )
String name,email;
{
public StudentBean( ){ }
return this.name;
public void setName(String name)
}
{
public int getRollno( )
this.name=name;
}
{
public void setEmail(String email) return this.rollno;
{ }
this.email=email; public String getEmail( )
} {
return this.email;
}
}

You might also like