You are on page 1of 21

JSP

JSP Technology is used to create web application just like Servlet Technology. This page Contains Html
Tags & Jsp Tags.

Advantages:
Extension to Servlet: It is Extension to Servlet. Additional to Servlet features, we can use implicit
objects, predefined Tags, Expressional Language & Custom Tags in Jsp, that make Jsp Development easy.
Easy to Maintain: We can Easily Separate our Business logic with Presentation logic. In Servlet, we mix
our Business logic with the Presentation logic.
Fast Development: If we modify Jsp Page, No need to Recompile & Redeploy.
Less Code than Servlet: We can use a lot of tags such as action tags, jstl, custom tags, EL & implicit
Objects etc. reduces the code.

Life Cycle: It follow these phases. jspInit(), _jspService() & jspDestroy() are life cycle methods.

From Diag, Jsp page is translated into Servlet by Jsp Translator. It is part of Web server
responsible to translate the Jsp page into Servlet. After Servlet page is compiled by the compiler & gets
converted into class file. And all the processes that happen in Servlet are performed on Jsp later like
Initialization, committing response to the Browser & Destroy.
Translation
Compilation
Classloading (class loaded by the classloader)
Instantiation (Object of Generated Servlet is created)
Initialization ( jspInit() is invoked by the container)
Request Processing (_jspService() is invoked by the container)
Destroy ( jspDestroy()is invoked by the container)
To Run a Simple JSP Page:
Start the Server
Put the Jsp file in folder & deploy on the Server.
Visit the Browser by the Url http://localhost:portno/contextRoot/jspfile
Ex: http://localhost:8888/myapp/mine.jsp
* There is no need of directory structure if you don't have class files or tld files. For example, put jsp files
in a folder directly and deploy that folder. It will be running fine. But if you are using bean class, Servlet
or tld file then directory structure is required.
Directory Structure: Same as Servlet. Outside the WEB-INF folder or in any Directory.
JSP API Consists of 2 Packages:
javax.servlet.jsp
javax.servlet.jsp.tagext

javax.servlet.jsp: has 2 interfaces and classes.


JspPage
HttpJspPage
Classes
JspWriter

PageContext
JspFactory
JspEngineInfo
JspException
JspError

JspPage: According to JSP Spec, all the Generated Servlet classes must implement the JspPage. It
Extends the Servlet interface. Provides 2 life cycle methods.
public void jspInit(): It is invoked only once during the life cycle of the JSP when JSP page is
requested firstly. It is used to perform initialization. It is same as the init() method of Servlet interface.
public void jspDestroy(): It is invoked only once during the life cycle of the JSP before the JSP
page is destroyed. It can be used to perform some cleanup operation.
HttpJspPage: Provides on life cycle method. It extends JspPage interface.
public void _jspService(): It is invoked each time when request for the JSP page comes to the
container. It is used to process the request. The underscore _ signifies that you cannot override this
method.
JSP in Eclipse with Tomcat
Create a Dynamic web project
Create a jsp
Start Tomcat server & deploy the project

JSP Scriptlet Tag: In Jsp, java code can be written inside the jsp page using the scriptlet tag.
Elements: Provides the ability to insert java code inside the jsp.
scriptlet tag: used to execute java source code in Jsp.
Syn:

<% java source code %>

Ex:

<html><body><% out.print(Welcome); %></html></body>

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. mainly used to print the values of var or method.
Syn:

<%= statement %>

Ex:

<html><body><%= Welcome %></html></body>

declaration tag: used to declare fields and methods. The code written inside the jsp declaration tag is
placed outside the service() of auto generated Servlet. So doesnt get memory at each request.
Syn:

<%! Field or method declaration %>

Diff:
Scriptlet Tag

Declaration Tag

Only declare variables not methods

declare variables as well as methods

Declaration placed inside the _jspService().

Declaration is placed outside the _jspService().

JSP Implicit Objects: 9 Objects are there. These objects are created by the web containers that are
available to all the jsp pages.
out

JspWriter

request

HttpServletRequest

response

HttpServletResponse

config

ServletConfig

application

ServletContext

session

HttpSession

pageContext

PageContext

page

Object

exception

Throwable

out: for writing any data to the buffer, JSP provides out. It is the object of JspWriter.
PrintWriter out = response.getWriter();
In Jsp,
<html><body><% out.print(Today: +java.util.Calender.getInstance().getTime()); %></html></body>

request: It is an Implicit object of HttpServletRequest i.e. created for each jsp request by the web
container. Used to get request info such as parameter, header info, remote address, server name, server
port, content type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp request scope.
<% String name=request.getParameter(uname);
out.print(welcome +name); %>

response: It is an Implicit object of HttpServletResponse. The instance of HttpServletResponse is created


by the web container for each jsp request.
used to add or manipulate response such as redirect response to another resource, send error etc.
<% response.sendRedirect(http://www.google.com); %>
config: It is an Implicit object of type ServletConfig. This object can be used to get initialization
parameter for a particular JSP. The config object is created by the web container for each jsp page.
It is used to get initialization parameter from the web.xml file.
application: It is an implicit object of type ServletContext. Instance of ServletContext is created only
once by the web container when project or application is deployed on the server. This object can be used
to get initialization parameter from configuration file(web.xml). It can also be used to get, set or remove
attribute from the application scope.
This initialization parameter can be used by all jsp pages.
session: It is an Implicit object of type HttpSession. Use this object to set, get or remove attribute or to
get session info.
pageContext: It is an Implicit object of type PageContext class. The pageContext object can be used to
set, get or remove attribute from one of the following scopes:
page
request
session
application
page scope is the default scope.
page: It is an Implicit object of type Object class. This object is assigned to the reference of auto
generated Servlet class.
Object page=this;
For using this object it must be cast to Servlet type.
Ex:

<% (HttpServlet)page.log(message); %>

Since it is of type object it is less used bcoz you can use this object directly in jsp.
Ex:

<% this.log(message); %>

exception: It is an implicit object of type java.langThrowable class. This object can be used to print the
exception. But it can only be used in Error pages.

JSP directives:

messages that tells the web container how to translate a JSP page into

Corresponding Servlet.
page directive
include directive
taglib directive
Syn:

<%@ directive attribute=value %>

JSP page directive: defines attributes that apply to an entire JSP page.
Syn:

<%@ page attribute=value %>

Attributes:
Import: used to import class, interface or all the members of a package.
contentType: defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response. The
default value is text/html;charset=ISO-8859-1.
extends: defines the parent class that will be inherited by the Generated Servlet. It is rarely used.
info: simply sets the info of the Jsp page which is retrieved later by using getServletInfo() of Servlet
interface.
buffer: sets the buffer size in kbs to handle output generated by the Jsp page. Default size is 8kb.
language: specifies the scripting language used in the JSP page. Default value is java.
isELIgnored: We can ignore the Expression Language in jsp by the isELIgnored attribute. Default value
is false i.e. EL is enabled by default.
<%@ page isELIgnored=true %>//Now EL ignored
isThreadSafe: Servlet and JSP both are multithreaded. If you want to control this behavior of JSP page,
you can use isThreadSafe attribute of page directive. The value of isThreadSafe value is true. If you make
it false, the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes
responding to a request before passing another request to it.
<%@ page isThreadSafe=false %>
In this case, web container generate the Servlet as:
public class SimplePage_jsp extends HttpJspBase implements SingleThreadModel{

errorPage: used to define the error page, if exception occurs in the current page, it will be redirected to
the error page.
isErrorPage: used to declare that current page is the error page.
The exception object can only be used in the error page.

JSP Include directive: used to include the contents of any resource it may be jsp/html/text file. It
includes the original content of the included resource at page translation time.
Advantage: code Reusability.
Syn:

<% include file=resourceName %>

Ex:

<% include file=index.html %>


<%= java.util.Calender.getInstance().getTime() %>

It Includes the Original Content, So the Actual page size grows at Runtime.

JSP Taglib directive: used to define a tag library that defines many tags. We use TLD(Tag Library
Descriptor) file to define the tags.
Syn:

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

Ex:

<%@ taglib uri=http://www.javatpoint.com/jsp prefix=mytag %>


<mytag:currentDate>

Exception Handling in JSP: The Exception is normally an Object that is thrown at runtime. It
is the process of handling 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, 2 ways:
1. By errorPage and isErrorPage attributes 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, as in the process.jsp page.
There are 3 files:
index.jsp for input values.
<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 for dividing the 2 numbers & displaying the result.


<%@ 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 for handling the exception.
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
2. By <error-page> element in web.xml file
This approach is better. Bcoz you no need to specify errorPage in each jsp page. Specifying single entry
in th web.xml will handle the exception. In this case, either specifies exception-type or error-code with
the location element. If you want to handle all the Exception, you will have to specify the
java.lang.Exception in the exception type element. There are 4 files:
Web.xml file for specifying the error-page element.
index.jsp for input values
process.jsp for dividing the 2 numbers & displaying the result.
error.jsp for displaying the exception.

JSP Action Tags: use to perform some specific tasks.


Action tags are used to control the flow between pages and to use Java Bean.
JSP Action Tags

Description

jsp:forward

forwards the request & response to another resource.

jsp:include

include 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 other components such as applet.

jsp:param

sets the parameter value. It is used in forward & include mostly.

jsp:fallback

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

The jsp:useBean, jsp:setProperty and jsp:getProperty are used for bean development.

jsp:forward action tag: used to forward the request to another resource(jsp,html etc).
Syn:

<jsp:forward page="relativeURL | <%= expression %>" >//without parameter


<jsp:forward page="relativeURL | <%= expression %>" >//with parameter
<jsp:param name="parametername" value="parametervalue | <%=expression%>"
</jsp:forward>

jsp:include action tag: used to include the content of another resource(jsp,html or Servlet).
This includes the resource at request time so it is better for dynamic pages Bcoz there might be changes
in future. It can be used to include static as well as dynamic web pages.
Advantage: code Reusability
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 Generated Servlet.

Calls the include method.

Syn:

<jsp:include page="relativeURL | <%= expression %>" >//without parameter

Java Bean: Its a Java class that should follow following conventions:
It should have a no-arg constructor.
It should be Serializable.
Use: According to Java white paper, it is a reusable software component. A bean encapsulates many
objects into one object, so we can access this object from multiple places. It provides easy maintenance.
To Access java bean class, we should use getter & setter methods.
There are 2 ways to provide the values to the object, by constructor & setter method.

jsp:useBean action tag: used to locate or instantiate a bean class. If bean object of bean class is
already created, it doesnt create the bean depending on the scope. But if object of bean is not created, it
instantiates the bean.

Syn:

<jsp:useBean id= "instanceName" scope= "page | request | session | application"


class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
Attributes & usage:
id: used to identify the bean in the specified scope.

scope: represents the scope of the bean. It may page, request, session or application. Default is
page.
page: specifies that you can use this bean within the JSP page.
request: can use this bean from any JSP page that processes the same request. It has wider scope
than page.

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

application: can use this bean from any JSP page in the same application. It has wider scope
than session.

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.

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.

beanName: instantiates the bean using the java.beans.Beans.instantiate() method.


jsp:setProperty & jsp:getProperty: used for developing web application with Java Bean. In web
development, bean class is mostly used Bcoz it is a reusable software component that represents data.
jsp:setProperty action tag sets a property value or values in a bean using the setter method.

Syn:

<jsp:setProperty name="instanceOfBean" property= "*" |


property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>

Ex:

<jsp:setProperty name="bean" property="*" /> //incoming request in the bean


<jsp:setProperty name="bean" property="username" /> //incoming specific prop.
<jsp:setProperty name="bean" property="username" value="Kumar" />//with val

jsp:getProperty action tag returns the value of the property.


Syn: <jsp:getProperty name="instanceOfBean" property= propertyName" />
Ex:
<jsp:getProperty name="obj" property="name" />

Ex. of Bean Development in JSP:


index.html for input of values.
welcome.jsp file that sets the incoming values to the bean object & prints the one value.
User.java bean class that have setter & getter methods.
Displaying applet in JSP(jsp:plugin action tag): used to embed applet in the jsp file. This action tag
downloads plugin at client side to execute an applet or bean.
Syn:

<jsp:plugin type= "applet | bean" code= "nameOfClassFile"


codebase= "directoryNameOfClassFile"
</jsp:plugin>

Expression Language(EL) in JSP: It Simplifies the accessibility of data stored in the Java Bean
component, and other objects like request, session, application.
There are many implicit objects, operators and reserve words in EL.
It is added in JSP version 2.0.
Syn:

${ expression }

Implicit Objects:
Objects

Usage

pageScope

it maps the given attribute name with the value set in the pageScope.

requestScope

it maps the given attribute name with the value set in the requestScope.

sessionScope

it maps the given attribute name with the value set in the sessionScope.

applicationScope

it maps the given attribute name with the value set in the applicationScope.

param

it maps the request parameter to the single value.

paramValues

it maps the request parameter to an array of values.

header

it maps the request header name to the single value.

headerValues

it maps the request header name to an array of values.

cookie

it maps the given cookie name to the cookie value.

initParam

it maps the initialization parameter.

pageContext

it provides access to many objects request, session etc.

Precedence Operators in EL:


[] .
()
-(unary) not ! empty
* / div % mod
+ - (binary)
< <= > >= lt le gt ge
==!= eq ne
&& and
|| or
?:
Reserve words:
lt

le

instanceof

gt

ge

eq

ne

div

mod

empty null

true

false

and

or

not

MVC in JSP
Stands for Model, View and Controller. It is a Design Pattern that separates the Business logic,
presentation logic and data.
Model represents state of application i.e. data. It can be Business Logic.
View represents presentation i.e. UI(User Interface).
Controller acts as an Interface between View and Model. Controller intercepts all the incoming requests.
Advantage:
Navigation Control is centralized
Easy to maintain the large application
Mostly we will use Java Bean class as a Model, jsp as a view component and Servlet as a Controller.

JSTL: represents a set of tags to simplify the JSP development.


Advantages:
Fast Development It provides many tags that simplify the JSP.
Code Reusability We can use the JSTL tags in various pages.
No need to use scriptlet tag It avoids the use of scriptlet tag.
It mainly provides 5 types of tags: core tags provide variable support, URL management, flow control etc.
url:

http://java.sun.com/jsp/jstl/core . prefix is c.

sql tags provide SQL Support


url:

http://java.sun.com/jsp/jstl/sql. prefix is sql.

xml tags provide flow control, transformation etc.


url:

http://java.sun.com/jsp/jstl/xml. prefix is x.

internalization tags provide support for message formatting, number and date formatting etc.
url:

http://java.sun.com/jsp/jstl/fmt. prefix is fmt.

functions tags provide support for string manipulation and string length.
url:

http://java.sun.com/jsp/jstl/functions. prefix is fn.

For creating JSTL application, you need to load jstl.jar file.

JSTL Core Tags:


miscellaneous tags: catch and out.
url management tags: import, url and redirect.
variable support tags: remove and set.
Flow control tags: forEach, forTokens, if and choose.
Syn:

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

c:catch Alternative approach of Global Exception Handling of JSP. It handles exception & doesnt
propagate the exception or error page. The exception object thrown at runtime is stored in a variable var.
<%@ taglib uri=http://java.sun.com/jsp/jstl/core prefix=c%>
<c:catch> int i=10/0; </c:catch>

c:out like Jsp expression tag but it is used for expression. It renders data to the page.
c:import like Jsp include but it can include the content of any resource either within server or outside the
server.

c:forEach It repeats the Nested Body content for fixed number times or over Collection.
c:if It tests the Condition.
c:redirect redirects the request to the given url.

Custom Tags in JSP:

These are user-defined Tags. They eliminate the possibility of


scriptlet tag and separate the business logic from the JSP page. The same business logic can be
used many times by the use of custom tag.

Advantages:
Eliminates the need of scriptlet tag This tags eliminates the need of scriptlet tag which is considered
bad programming approach in JSP.
Separation of business logic from JSP This tags separate the the business logic from the JSP page so
that it may be easy to maintain.
Re-usability This tags makes the possibility to reuse the same business logic again and again.

Ex:

prefix:tagname attr1=value1....attrn=valuen >


body code
</prefix:tagname>

JSP Custom Tag API The javax.servlet.jsp.tagext package contains classes and interfaces for JSP
custom tag API. The JspTag is the root interface in the Custom Tag hierarchy.

JspTag interface is the root interface for all the interfaces and classes used in custom tag. It is a
marker interface.

Tag interface is the sub interface of JspTag interface. It provides methods to perform action at the start
and end of the tag.

Fields:
public static int EVAL_BODY_INCLUDE it evaluates the body content.
public static int EVAL_PAGE it evaluates the JSP page content after the custom tag.
public static int SKIP_BODY it skips the body content of the tag.
public static int SKIP_PAGE it skips the JSP page content after the custom tag.

Methods:
public void setPageContext(PageContext pc) it sets the given PageContext object.
public void setParent(Tag t) it sets the parent of the tag handler.
public Tag getParent() it returns the parent tag handler object.
public int doStartTag()throws JspException
public int doEndTag()throws JspException
public void release() it is invoked by the JSP page implementation object to release the state.

IterationTag interface is the sub interface of the Tag interface. It provides an additional method to
reevaluate the body.
public static int EVAL_BODY_AGAIN it reevaluates the body content.
public int doAfterBody()throws JspException

TagSupport class implements the IterationTag interface. It acts as the base class for new Tag
Handlers. It provides some additional methods also.

Ex: To create a Custom Tag, we are performing action at start of the tag.
> Create the Tag Handler class and perform action at the start or at the end of the tag.
To create this class, we need to inherit the TagSupport class & overriding its method doStartTag(). To
write data for the jsp, we need to use JspWriter class.
The PageContext class provides getOut() method that returns the instance of JspWriter class. TagSupport
class provides instance of pageContext bydefault.

> Create the Tag Library Descriptor(TLD) file and define tags. It contains info of tag & Tag Handler
class. It must be contained inside the WEB-INF dir.
> Create the JSP file that uses the Custom tag defined in the TLD file.
It uses taglib directive to use the tags defined in the tld file.

Attributes:
There can be defined too many attributes for any custom tag. To define the attribute, you need to perform
two tasks:
Define the property in the TagHandler class with the attribute name and define the setter method
define the attribute element inside the tag element in the TLD file
<m:cube number="4"></m:cube>

m is prefix, cube is tag name and number is attribute.

Iteration using JSP Custom tag:


We can iterate the body content of any tag using the doAfterBody() method of IterationTag interface.
Here we are going to use the TagSupport class which implements the IterationTag interface. For iterating
the body content, we need to use the EVAL_BODY_AGAIN constant in the doAfterBody() method.

Custom URI in JSP Custom tag: We can use the custom URI, to tell the web container about the
tld file. In such case, we need to define the taglib element in the web.xml. The web container gets the
information about the tld file from the web.xml file for the specified URI.

Registration Form in JSP: For creating registration form, you must have a table in the database.
You can write the database logic in JSP file, but separating it from the JSP page is better approach. Here,
we are going to use DAO, Factory Method, DTO and Singletion design patterns. There are many files:

index.jsp, for getting the values from user


User.java, a bean class that having properties and setter and getter methods.
process.jsp, that processes the request and calls the methods.
Provider.java, an interface that contains many constants like DRIVER_CLASS, CONNECTION_URL,
USERNAME and PASSWORD
ConnectionProvider.java, a class that returns an object of Connection. It uses the Singleton and factory
method design pattern.
RegisterDao.java, a DAO class that is responsible to get access to the database

You might also like