JSP Word Document
JSP Word Document
JSP Word Document
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
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:
Ex:
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:
Ex:
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:
Diff:
Scriptlet Tag
Declaration Tag
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); %>
Since it is of type object it is less used bcoz you can use this object directly in jsp.
Ex:
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:
JSP page directive: defines attributes that apply to an entire JSP page.
Syn:
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:
Ex:
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:
Ex:
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>
Description
jsp:forward
jsp:include
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:plugin
jsp:param
jsp:fallback
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: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
Syn:
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:
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.
Syn:
Ex:
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
paramValues
header
headerValues
cookie
initParam
pageContext
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.
http://java.sun.com/jsp/jstl/core . prefix is c.
http://java.sun.com/jsp/jstl/xml. prefix is x.
internalization tags provide support for message formatting, number and date formatting etc.
url:
functions tags provide support for string manipulation and string length.
url:
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.
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:
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>
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: