0% found this document useful (0 votes)
45 views19 pages

JSP Notes (With Programs)

Uploaded by

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

JSP Notes (With Programs)

Uploaded by

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

Unit-5(part 2)

Introduction to JSP
JSP is a server side technology that does all the processing at server. It is used for
creating dynamic web applications, using java as programming language. It is an
extension of servlet because it provides more functionality than servlet by allowing users
to use expression language and JSTL(JSP Standard Tag Lib).
In JSP, you can embed Java code in HTML using JSP tags. JSP is used for creating dynamic
webpages. Dynamic webpages are usually a mix of static & dynamic content.
The static content can have text-based formats such as HTML, XML etc and the dynamic
content is generated by JSP tags using java code inside HTML .

Servlet Vs JSP
Like JSP, Servlets are also used for generating dynamic webpages. Here is the
comparison between them.

Servlets:

1. Servlet is a Java program which supports HTML tags too.


2. Generally used for developing business layer(the complex computational
code) of an enterprise application.
3. Servlets are created and maintained by Java developers.

JSP:

1. JSP program is a HTML code which supports java statements too. To be


more precise, JSP embed java in html using JSP tags.
2. Used for developing presentation layer of an enterprise application
3. Frequently used for designing websites and used by web developers.

Advantages of JSP

1. JSP has all the advantages of servlet, like: Better performance than
CGI Built in session features, it also inherits the the features of java
technology like – multithreading, exception handling, Database
connectivity etc.
2. JSP Enables the separation of content generation from content
presentation. Which makes it more flexible.
3. With the JSP, it is now easy for web designers to show case the
information what is needed.
4. Web Application Programmers can concentrate on how to
process/build the information.
5. It is easy to manage as business logic can be separated with
presentation logic.

Java Server Pages (JSP) Life Cycle


JSP pages are saved with .jsp extension which lets the server know that this is a
JSP page and needs to go through JSP life cycle stages.

Steps involved in JSP life Cycle:

There are 7 steps involved in translating a JSP page into a servlet code.

1. Translation process- container translates a JSP page into servlet code.

2. Compilation process- the java servlet file is compiled into a class file.

3. Loading process- the servlet class is loaded into the container.

4. Instantiation process- an instance of the servlet is created.

5. Initialization process-

JSP Page is initialized by _jspinit() method. It allows the page author to provide
initialization to the JSP Page. This method is called only once during the JSP life cycle.

6. Request process-

The _jspservice () method is used for request processing. This method is invoked by the
container. This method is called to handle each request. The response is produced from
within this method and then returned to the container so that it can be passed back to the
client.

7. Destroy process-

The _jspDestroy() method is used to destroy the JSP Page. Page author can call If any
cleanup is required . This method is called only once during JSP page Life Cycle.

JSP Processing
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are
three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
scriptlet tag
A scriptlet tag is used to execute java source code in JSP.
Syntax : <% java source code %>
Example:
<html>
<body>
<% out.print("welcome to jsp"); %>
</body> </html>
expression tag
The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.

Syntax: <%= statement %>

Example:
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body> </html>
Declaration Tag

The JSP declaration tag is used to declare fields and methods. The code written inside the
jsp declaration tag is placed outside the service() method of auto generated servlet.

So it doesn't get memory at each request.

Syntax: <%! field or method declaration %>


Example 1: declares field

<html>
<head>
<title>Declaration tag Example1</title>
</head>
<body>
<%! String name="Abhineet"; %>
<%! int age=17; %>
<%= "Name is: "+ name %><br>
<%= "AGE: "+ age %>
</body> </html>

Example 2: declares method


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

Difference b/w JSP Scriptlet tag and Declaration tag


Jsp Scriptlet Tag Jsp Declaration Tag

can only declare variables not methods. can declare variables as well as methods.

The declaration of scriptlet tag is placed The declaration of jsp declaration tag is placed
inside the _jspService() method. outside the _jspService() method.

JSP Implicit Objects


These Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being explicitly
declared. JSP implicit objects are created during the translation phase of JSP to the
servlet. They are created by the container automatically, and they can be accessed using
objects. JSP Implicit Objects are also called pre-defined variables.
There are 9 jsp implicit objects. A list of the 9 implicit objects is given below:

Object Description Example

out Used to write any data to the buffer. It Example: index.jsp


is the object of JspWriter.
<html> <body>
PrintWriter out=response.getWriter();B
ut in JSP, you don't need to write this <% out.print("Today is:"+java.util.Cal
code. endar.getInstance().getTime()); %>
</body> </html>

request It is an object of type index.html


HttpServletRequest i.e. created for <form action="welcome.jsp">
each jsp request by the web container. <input type="text" name="uname">
It can be used to get request <input type="submit" value="go"><br/>
information such as parameter, header </form>
information, remote address, server
name, server port, content type, welcome.jsp
character encoding etc. <%
String
It can also be used to set, get and name=request.getParameter("uname");
remove attributes from the jsp request out.print("welcome "+name);
scope. %>

response It is an object of type index.html


HttpServletResponse.
<form action="welcome.jsp">
It can be used to add or manipulate
response such as redirect response to <input type="text" name="uname">
another resource, send error etc. <input type="submit" value="go"><b
r/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www
.google.com");
%>

config config is an implicit object of


type ServletConfig. This object can be
used to get initialization parameter for
a particular JSP page. Generally, it is
used to get initialization parameter
from the web.xml file.
application application is an implicit object of
type ServletContext.

The instance of ServletContext is


created only once by the web container
when application or project is
deployed on the server.

This object can be used to get


initialization parameter from
configuaration file (web.xml). It can
also be used to get, set or remove
attribute from the application scope.

session It is object of type HttpSession. The


main use of session is to gain
access to all the user’s data till the
user session is active.

pageConte It is of object of type PageContext class. It


xt can be used to set,get or remove attribute
from one of the following scopes:
page
request
session
application
In JSP, page scope is the default scope.

page page is an implicit object of type


Object class.This object is assigned to
the reference of auto generated servlet
class. It is written as:
Object page=this;

exception It is an instance of
java.lang.Throwable and mainly used
for exception handling in JSP. It is only
available for error pages, which means
a JSP page should have isErrorPage
set to true in order to use exception
implicit object.

Methods of session Implicit Object


1. setAttribute(String, object): This method is used to save an object in
session by assigning a unique string to the object. Later, the object can be
accessed from the session by using the same String till the session is active.
setAttribute and getAttribute are the two most frequently used methods
while dealing with session in JSP.
2. getAttribute(String name): The object stored by setAttribute method is
fetched from session using getAttribute method. For example if we need to
access userid on every JSP page till the session is active then we should
store the user-id in session using setAttribute method and can be accessed
using getAttribute method whenever needed.
3. removeAttribute(String name): The objects which are stored in session can
be removed from session using this method. Pass the unique string identifier
as removeAttribute’s method.
4. getAttributeNames: It returns all the objects stored in session. Basically, it
results in an enumeration of objects.
5. getCreationTime(): This method returns the session creation time, the time
when session got initiated (became active).
6. getId(): Servlet container assigns a unique string identifier to session while
creation of it. getId method returns that unique string identifier.
7. isNew(): Used to check whether the session is new. It returns Boolean value
(true or false). Mostly used to track whether the cookies are enabled on client
side. If cookies are disabled the session.isNew() method would always
return true.
8. invalidate(): It kills a session and breaks the association of session with all
the stored objects.
9. getMaxInactiveInterval: Returns session’s maximum inactivate time interval
in seconds.
10. getLastAccessedTime: Generally used to know the last accessed time of a
session.

Session Implicit Object in JSP with examples


A session can be defined as an object associated with each user with a unique session ID, and the
user's data is based on the account they have registered. Different forms of data can be set in a
session; These data related to each user of the site help the user and the website owner in
different ways. As you know, HTTP is a "stateless" protocol; Whenever a user visits a web page,
the user opens a separate connection with the webserver, and the server does not keep a record
of preceding client requests.

Different approaches to maintain a session between client and server are:

1. Cookies: Cookies are text files that allow programmers to store some information on a
client computer, and they are kept for usage tracking purposes.
2. Passing Session ID in URL: Adding and passing session ID to URL is also a way to identify
a session. However, this method is obsolete and insecure because the URL can be
tracked.

The session Implicit Object

• A session object is the most commonly used implicit object implemented to store user
data to make it available on other JSP pages until the user's session is active.
• The session implicit object is an instance of a javax.servlet.http.HttpSession interface.
• This session object has different session methods to manage data within the session
scope.

Here is an example of a JSP request and session implicit objects where a user submits login
information, another JSP page receives it for processing and send redirect to output page:
1) index.html
<html> <head> <title>User login form</title>
</head> <body>
<form action="login.jsp">
Please enter Username: <input type="text" name="uname" /> <br />
<input type="submit" value="Submit Details" />
</form> </body></html>

2) login.jsp
<%@ page import = " java.util.* " %>
<%
String username = request.getParameter("uname");
if(username.equals("admin")){
session.setAttribute("uname",username);
response.sendRedirect("output.jsp");
}else{
out.print("Invalid Username");
}
%>
3) output.jsp
<html> <head>
<title>Output page: Fetching the value from session</title>
</head><body>
<%
String sessionUN = (String)session.getAttribute("uname");
out.print("Hi, and welcome ---- "+sessionUN);
%>
</body> </html>
Session is most frequently used implicit object in JSP. The main usage of it to gain access
to all the user’s data till the user session is active.

JSP Directives
The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.

Syntax: <%@ directive attribute="value" %>

There are three types of directives:

A) page directive
B) include directive
C) taglib directive

A) page directive

It is used to define the properties applying the JSP page, such as the size of the allocated
buffer, imported packages and classes/interfaces, defining what type of page it is etc.

Syntax: <%@ page attribute="value" %>

Attributes of JSP page directive


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

A-1) import
This tells the container what packages/classes are needed to be imported into the program.
It is similar to import keyword in java class or interface.

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

A-2)contentType
This defines the format of data that is being exchanged between the client and the server.
It does the same thing as the setContentType method in servlet used to.
Syntax:
<%@page contentType="value"%>
Example:
<html> <body>
<%@page contentType = "text/html" %>
Today is: <%= new java.util.Date() %>
</body> </html>

A-3)language

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

A-4)errorPage and A-5) isErrorPage

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.

The isErrorPage attribute is used to declare that the current page is the error page.

Example:

//index.jsp

<html> <body>

%@ page errorPage="myerrorpage.jsp" %>

<%= 100/0 %>

</body> </html>

//myerrorpage.jsp
<html> <body>

<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>

The exception is: <%= exception %>

</body> </html>

A-6) info: Defines the string which can be printed using the ‘getServletInfo()’ method.

Syntax:

<%@page info="value"%>

Example:

<%@page contentType = "text/html" %>


<% = getServletInfo()%>

A-7) “pageEncoding” : Defines the character encoding for JSP page.

The default is specified as “ISO-8859-1” if any other is not specified.

Syntax: <%@ page pageEncoding="vaue" %>

Here value specifies the charset value for JSP

Example:

<%@ page language="java" contentType="text/html;"


pageEncoding="ISO-8859-1"
isErrorPage="true"%>

B) 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).
Advantage: Code Reusability

Syntax: <%@ include file="resourceName" %>


Example:

In this example, we have three jsp pages: file1.jsp, file2.jsp and index.jsp. We have
included the content of file1.jsp and file2.jsp in the index.jsp using include directive.
index.jsp

<html> <head>
<title>Main JSP Page</title> </head>
<body>
<%@ include file="file1.jsp" %>
Main JSP Page: Content between two include directives.
<%@ include file="file2.jsp" %>
</body></html>

file1.jsp

<p align="center">
This is my File1.jsp and I will include it in index.jsp using include directive
</p>

file2.jsp

<p align="center">
This is File2.jsp
</p>

C) JSP Taglib directive


The taglib directive is used to mention the library whose custom-defined tags are being
used in the JSP page. It’s major application is JSTL(JSP standard tag library).
Syntax:
<%@taglib uri = "library url" prefix="the prefix to identify the tags of this library with"%>

Here “uri” attribute is a unique identifier in tag library descriptor and “prefix” attribute
is a tag name.

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

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

<html> <head> <title>Guru Directive JSP</title>

<gurutag:hello/>
</head>
<body>
</body> </html>

Here “taglib” is defined with attributes uri and prefix.


“gurutag” is the custom tag defined and it can be used anywhere

Exception Handling in JSP


The exception is normally an object that is thrown at runtime. Exception Handling is the
process to handle the runtime errors. There may occur exception any time in your web
application. So handling exceptions is a safer side for the web developer. In JSP, there
are two ways to perform exception handling:

1. By errorPage and isErrorPage attributes of page directive


2. By <error-page> element in web.xml file

Example of exception handling in jsp by the elements of page directive

In this case, you must define and create a page to handle the exceptions, as in the
error.jsp page. The pages where may occur exception, define the errorPage attribute of
page directive, as in the process.jsp page.

There are 3 files:

o index.jsp for input values


o process.jsp for dividing the two numbers and displaying the result
o error.jsp for handling the exception

index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>

process.jsp
<%@ page errorPage="error.jsp" %>
<%

String num1=request.getParameter("n1");
String num2=request.getParameter("n2");

int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>

error.jsp
<%@ page isErrorPage="true" %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>

JSP Standard Tag(Action Element)


JSP specification provides Standard(Action) tags for use within your JSP pages. These
tags are used to remove or eliminate scriptlet code from your JSP page because
scriplet code are technically not recommended nowadays. It's considered to be bad
practice to put java code directly inside your JSP page.

Standard tags begin with the jsp: prefix. There are many JSP Standard Action tag which
are used to perform some specific task.

Unlike directives, actions are re-evaluated each time the page is accessed.

The action tags are used to control the flow between pages and to use Java Bean.

Syntax: <jsp:action_name attribute="value" />

The Jsp action tags are given below.

JSP Action Description


Tags

jsp:forward forwards the request and response to another resource. It may be jsp,
html or another resource.

jsp:include includes another resource. It may be jsp, html or another resource. It


includes the resource at request time so it is better for dynamic
pages because there might be changes in future.
It can be used to include static as well as dynamic pages

jsp:useBean creates or locates bean object.


<jsp:useBean> tag is used to declare and access the JavaBeans in a JSP
page. We can access the property/properties of a JavaBeans. You can
use the jsp:setProperty tag to set the property/properties value and
jsp:getProperty tag to get the property/properties value. For this you
have to define the setter and/or getter methods of the properties in
JavaBeans.
Rules for JavaBean class

• It should have a no-arg constructor.

• It should be Serializable.

• It should provide methods to set and get the values of

the properties, known as getter and setter methods.

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.

Program on Action Tags:


Example of index.jsp
jsp:forward action <html> <body>
tag without <h2>this is index page</h2>
parameter <jsp:forward page="printdate.jsp" />
</body> </html>

printdate.jsp
<html> <body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime());
%>
Example of </body> </html>
jsp:forward action
tag with parameter index.jsp
<html> <body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="JaiShriKrishna" />
</jsp:forward>
</body> </html>

printdate.jsp
<html> <body>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body> </html>
In this example, we are simply forwarding the request to the
printdate.jsp file.
Example of File: index.jsp
jsp:include action <h2>this is index page</h2>
tag <jsp:include page="printdate.jsp" />

<h2>end section of index page</h2>

File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime());
%>

jsp:useBean Create a Java Bean. The Java Bean is a specially constructed Java
jsp:setProperty class that provides a default, no-argument constructor, implements
jsp:getProperty the Serializable interface and it has getter and setter methods for its
properties.
• Use the useBean action to declare the JavaBean for use in the
JSP page. Once declared, the bean becomes a scripting
variable that can be accessed by both scripting elements
and other custom tags used in the JSP.
• Use the getProperty action to access get methods
and setProperty action to access set methods of the bean.

Attributes and Usage of jsp:useBean action tag


1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request, session or application.
The default scope is page.
o page: specifies that you can use this bean within the JSP page. The default scope
is page.
o request: specifies that you can use this bean from any JSP page that processes the
same request. It has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the same session
whether processes the same request or not. It has wider scope than request.
o application: specifies that you can use this bean from any JSP page in the same
application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it
must have no-arg or no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It is mainly
used with class or beanName attribute. If you use it without class or beanName, no bean
is instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
Simple example of jsp:useBean action tag

Program 1: In this example, we are simply invoking the method of the Bean class.

Calculator.java (a simple Bean class)


package abc.test;
public class Calculator{
public int cube(int n)
{return n*n*n;}
}

index.jsp file
<jsp:useBean id="obj" class=" abc.test.Calculator"/>

<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Program 2:
index.html
<form action="process.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>

process.jsp
<jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>

Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>

User.java
package org.sssit;

public class User {


private String name,password,email;
//setters and getters
}
Difference b/w Servlet and JSP is as follows:
Servlet JSP

Servlet is a java code. JSP is a HTML-based compilation code.

Writing code is harder than JSP as it is HTML in


JSP is easy to code as it is java in HTML.
java.

Servlet plays a controller role in the ,MVC JSP is the view in the MVC approach for
approach. showing output.

JSP is slower than Servlet because the first


Servlet is faster than JSP. step in the JSP lifecycle is the translation of
JSP to java code and then compile.

Servlet can accept all protocol requests. JSP only accepts HTTP requests.

In Servlet, we can override the service()


In JSP, we cannot override its service() method.
method.

It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.

Packages are to be imported on the top of the Packages can be imported into the JSP
program. program (i.e, bottom , middleclient-side, or top )

The facility of writing custom tags is not


The facility of writing custom tags is present.
present.

Before the execution, JSP is compiled in Java


Servlets are hosted and executed on Web
Servlets and then it has a similar lifecycle as
Servers.
Servlets.
Difference b/w JSP include directive JSP include action

JSP include directive JSP include action

includes resource at translation time. includes resource at request time.

better for static pages. better for dynamic pages.

includes the original content in the generated servlet. calls the include method.

Difference between Applets and Servlets


Applets Servlets

It is a small application which is written in Java It is a Java programming language class


and delivered to users in the form of bytecode. used to extend the capabilities of a server.

Applets are executed on client side. Servlets are executed on server side.

Life cycle of Applets init(), stop(), paint(), start(), Lifecycle of servlets are:- init( ), service( ),
destroy(). and destroy( ).

Packages available in Applets are :- import Packages available in servlets are:- import
java.applet.*; and import java.awt.*. javax.servlet.*; and import java.servlet.http.*;

More prone to risk as it is on client machine. Servlets are under the server security.

Utilize more network bandwidth as it executes Are executed on the servers and hence
on the client machine. require less bandwidth.

Applets are two types 1.) Untrusted Applets 2.) Servlet are two types 1.) Generic Servlet 2.)
trusted Applets HTTP Servlet

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy