You are on page 1of 51

JAVA SERVER PAGE(JSP)

Prepared by:-Jaydeep R. Viradiya


JSP INTRODUCTION
 JavaServer Pages (JSP) is a server-side programming
technology that enables the creation of dynamic,
platform-independent method for building Web-based
applications.
 JSP technology is used to create web application just
like Servlet technology.
 It can be thought of as an extension to servlet because
it provides more functionality than servlet
CONTINUE…
 A JSP page consists of HTML tags and JSP tags.
 The jsp pages are easier to maintain than servlet
because we can separate designing and
development.
JSP VS SERVLET
Servlet JSP

 Handles Business Logic  Handles Presentation Logic


 Lifecycle Methods  Lifecycle Methods
 init()-can be overridden  Jspinit()-can be overriden
 Service() -can be overridden  _jspservics()-can be overridden
 Destroy() -can be overridden.  Jspdestroy()-can be overriden

 HTML within Java  Java within HTML


IN THE END ,A JSP IS JUST A SERVLET
Is loaded and
initialized as

Is translated to Compiles to

Import 010101
JSP javax. 010100
sevlet. 101010 Servlet
Httpservlet 010
Myjsp.jsp Myjsp_jsp.java Myjsp_jsp.class
LIFE CYCLE OF A JSP PAGE
ADVANTAGE OF JSP OVER SERVLET
EXTENSION TO SERVLET
 JSP technology is the extension to servlet
technology. We can use all the features of servlet
in JSP.
 In addition to, we can use implicit objects,
predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.
EASY TO MAINTAIN
 JSP can be easily managed because we can easily
separate our business logic with presentation
logic.
FAST DEVELOPMENT: NO NEED TO
RECOMPILE AND REDEPLOY

 If JSP page is modified, we don't need to


recompile and redeploy the project. The servlet
code needs to be updated and recompiled if we
have to change the look and feel of the
application.
LESS CODE THAN SERVLET
 In JSP, we can use a lot of tags such as action
tags, jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.
JSP ELEMENTS
 Need to write some java in your HTML?

 Want to make Your HTML more dynamic

Jsp Declarations :: Code that goes outside the service method

Jsp Scriplets :: Code that goes within the service method

Jsp Expressions :: Code inside expression is evaluated

Jsp Directives :: Commands given to the JSP engine


JSP ELEMENTS- DECLARATIONS
 What are declarations?
 Whatever goes inside the “<%!{JAVA_HERE}>” tag is
called a declaration.
 Everything you write in a declaration goes outside the
service method
 Treat them as instance method and instance variables

What do you declare in declarations?

you can declare methods and variable in declarations.


Why do you need declarations?
You have any variable that needs to be shared across
different requests
You have repeated common code in your JSP ,
declare it in a method.
Example:
<%! Int var=10; %>
JSP Elements - Declarations

Request 1

Service1 Service2 Service3

Request 2

Declarations

Request 3

14
JSP ELEMENTS - SCRIPLETS
 What are Scriplets?
 Whatever goes inside “<%JAVA_HERE%>” tag is called a
scriplet
 Everything you write in a scriplet goes in the sevice method
 Treat variables in scriplets as methods/local variables

 What do you put in scriplets?


 Business logic in JSPs are put in scriplets. Set of java
statements
Why do you need scriplets?
Need to perform some small business logic
Need to perform some basic validations
Example
<% int localVar=10; %>
EXAMPLE
JSP ELEMENTS : EXPRESSIONS
 What are Expressions?
 Whatever goes inside the “<%={JAVA_HERE}%>” tags is called
an expressions
 Code inside expressions is evaluated, and output is displayed.
 Whatever is put inside expressions should evaluate to value.

What do you put in Expressions?


Variables or methods that return some values.

Why do you need expressions?


Need to print some text onto the page.

Example:
<%= localvar %>
EXAMPLE
JSP Elements - Example

<html><head><title>JSP Elements Example</title>


</head>
<body> Declarations
<%! int userCnt = 0; %>

<% Scriptlets
String name = "Sharad";
userCnt++;
%> Expressions
<table>
<tr><td>
Welcome <%=name%>. You are user number <%=userCnt%>
</td></tr>
</table>
</body>
</html>

19
JSP ELEMENTS :- DIRECTIVES
 What are Directives?
 Whatever goes inside “<%@{Directives}%>” tags are called directive
 Directives gives pre-processing commands to the JSP engine.
 Everything in directives are processed before jsp is translated to servlet

What do you put in directives?


Processing command to the JSP engine.
Why do you need directives?
To incorporate certain additional features into the jsp.
Modifying the servlet behaviour generated from the jsp.
Include other HTML/JSP file in the JSP
Provide tags Libraries

Example:
<%@ page import =“java.util.ArrayList” %>
THERE ARE THREE TYPES OF DIRECTIVE
TAG:

Directive Description

<%@ page ... %> Defines page-dependent attributes, such as


scripting language, error page, and buffering
requirements.

<%@ include ... %> Includes a file during the translation phase.

<%@ taglib ... %> Declares a tag library, containing custom


actions, used in
DIRECTIVES: PAGE DIRECTIVE
 Any number of pre-defined attributes can be added to
the page directive.

<%@ page import = “{IMPORTED CLASS}”


contentType = “{CONTENT_TYPE}”
isThreadSafe = “{true/false}”
session = “{true/false}”
Buffer = “{BUFFER_SIZE}”
autoFlush = “{true/false}”
extends = “{EXTENDS_FROM_PAGE}”
info = “{PAGE_INFO}”
errorPage = “{ERROR_PAGE_NAME}”
isErrorPage = “{true/false}”
language = “{LANGUAGE}”
DIRECTIVES: INCLUDE DIRECTIVE
 Including other page content into your JSP.
 <%@ include file ={PAGE_URL_TO_INCLUDE}%>
 Includes file at translation time.
 If include file is modified , the main jsp needs need to be
recompiled
DIRECTIVES: TAGLIB DIRECTIVE
 Providing output based on common custom logic

<%@ taglib uri=“{TLD_FILE}” prefix=“{prefix}” %>


 For creating any custom tag, we need to follow following
steps:

Create the Tag handler class and perform action at the


start or at the end of the tag.

Create the Tag Library Descriptor (TLD) file and


define tags

Create the JSP file that uses the Custom tag defined
in the TLD file
FLOW OF CUSTOM TAG IN JSP
TAGLIB LIBRARY – HIGH LEVEL OVERVIEW
<%@ taglib uri=“jspTag” prefix=“mytag”%>
----
<mytag:txtbox length=“10” name = “username”/>
jspTag-taglib-tld
Test.jsp <tag>
<name>txtbox</name>
<tagclass>txtboxclass</tagclass>
</tag>

Txtboxclass.java
Web.xml Public class txtboxclass extends Tagsuport
<web-app>
<taglib> {
<taglib-uri>jspTag</taglib-uri> Public int doStartTag()
<taglib-location>jspTag-taglib-tld {
</taglib-location> --------
</taglib> }
</web-app> }
IMPLICIT OBJECTS- INTRODUCTION
 Set of predefined objects readily available for use.
 Out : JspWriter
 Request : HttpRequest
 Response : HttpResponse
 Session : HttpSession
 Config : ServletConfig
 Application : ServletContext
 Page : Jsp Page
 Page context : special objects
IMPLICIT OBJECTS:- OUT
 An instance of JspWriter

 Writes statements to the page

 The java way to display text on the webpage

 Displaying dynamic data


IMPLICIT OBJECTS: REQUEST
 Instance of HttpServletRequest
 Use the attributes stored in request object for
display/basic validation in JSP.

Forward request to JSP


Servlet Jsp page
request.setAttribute(“a “,“10”)

Helper
Object
Uses helper (a=10)
object
IMPLICIT OBJECTS: RESPONSE
 Instance of HttpServletResponse
 Send the response back to the client

Send response to the client


JSP1

Response.sendredirect(“jsp2”)
Send response to
Redirect to JSP
page the client
JSP1 JSP2
IMPLICIT OBJECTS : SESSION
 Instance of HttpSession
 Retrieve and set the session attributes in JSP

 Remember client across multiple requests

Request1
Client
Response1

Web App
Request2

Response2
IMPLICIT OBJECTS : CONFIG AND
APPLICATION

 Config : instance of ServletConfig


 Application: instance of servletContext

servletContext

JSP JSP JSP

ServletConfig ServletConfig ServletConfig


Implicit Objects – page

Hello <%=userName%>
<jsp:include page=“/header.jsp"/>

header.jsp

Main page
<table><tr>
<td>Contact Details</td>
<tr></table>
<jsp:include page=“/footer.jsp"/>

footer.jsp
main.jsp 33
Implicit Objects – pageContext

application
Least visible to most visible

session

pageContext

request

page

34
JSP Actions

• Special tags which provides special features

• The container handles these tags in a special way

• Addresses certain common functionalities

• Achieve functionality with less code, and more standard way

<jsp:include>
<jsp:forward>
<jsp:param>
<jsp:useBean>
<jsp:getProperty>
<jsp:setProperty>
35
JSP Actions - <jsp:include>

Definition:
Includes a page at the given location in the main page

Syntax:

<jsp:include page="{PAGE_TO_INCLUDE}" flush="true" />

36
JSP Actions – Include Action v/s Include Directive

Include Directive Include Action

Translation time Run time

Copies the included file References to the included file

For static content For dynamic content

Cannot pass parameters Can pass parameters

37
JSP Actions - <jsp:forward>

Definition:
Forwards the request to the given page

Syntax:

<jsp:forward page=“{PAGE_TO_FORWARD}" />

38
JSP Actions - <jsp:param>

Definition:
Pass parameters to the included/forwarded page

Syntax:

<jsp:include page="{PAGE_TO_INCLUDE}" flush="true" >


<jsp:param name=“{parameterName}” value="{paramValue}" />
</jsp:include>

<jsp:forward page="{PAGE_TO_FORWARD}" flush="true" >


<jsp:param name=“{parameterName}” value="{paramValue}" />
</jsp:forward>

39
A JAVABEAN
A Javabean is a ordinary java class that conforms to the following
rules:

 A javabean must have a public,no argument constructor(a default


constructor).

 The javabean class attributes must be accessed via accessor and


mutator methods that follow a standard naming convention(getxxxX()
and setxxxX(),isxxxX() for boolean attributes)

 Javabean class should implement the serializable interface.


WHY USE JAVABEANS

Using javabeans rather than java scriplets in your JSPs


allow better separation of the view logic from the
business logic.

Java in a JSP

* Java Scriplets
* Include Statement
* Javabeans
JSP Actions - <jsp:useBean>

getId();
setId(..)
getName()
How can I use
setName(…)
that bean?

bean

Servlet JSP

request.setAttribute(“userBean”, userBean”) <jsp:useBean …./>

42
JSP Actions - <jsp:useBean>

Definition:
Instantiate a bean class, use bean properties, and set property values

Syntax:

<jsp:useBean id=“{beanInstanceName}"
scope="page|request|session|application"
class=“{package.class}" >
</ jsp:useBean>

UserBean ub = new UserBean();


43
JSP Actions - <jsp:getProperty>

Definition:
Gets property values of a Bean

Syntax:

<jsp:getProperty name=“{beanInstanceName}"
property= “{propertyName}">

44
JSP Actions - <jsp:setProperty>

Definition:
Sets property values in a Bean

Syntax:

<jsp:setProperty name=“{beanInstanceName}"
property= "*" | property="propertyName"
param=“{parameterName}"
value="{paramValue}" } />

45
JSP Actions – useBean

<jsp:useBean id=“userBean"
scope="session“
class=“com.jaydeep.UserBean" >
<jsp:setProperty name=“userBean”
property=“userName”
value=“jaydeep”/>
</ jsp:useBean>

<jsp:getProperty name=“userBean" property=“userName" />

46
Error Handling – Types of errors

• Errors in java code in scriptlets


 handle errors in try/catch block
 may occur at runtime

• Errors in HTML

 adhere to the HTML rules

 can be caught during testing 47


Error Handling

Why is error handling important in JSPs?

48
Error Handling – Error page

• Error pages come to the rescue

<%@page isErrorPage="true" %>


<html>
<head>
<title>My Error Page</title>
</head>
<body>
We are sorry, the page you are
trying to access is currently not
available. Please try after some time
</body>
</html>

49
Error Handling

• Specify error page in your main page • Specify error page in web.xml
<%@page errorPage=“errPage.jsp" %> <web-app>
<html> …………….
<head> ……………
<title>This is the main page</title>
</head> <error-page>
<body> <exception-type>com.a.myExp</exception-type>
………………….. <location>/error.jsp</location>
………………….. </error-page>

…………………… <error-page>
…………………… <error-code>404</error-code>
<location>/errorServlet</location>
// ERROR CODE GOES HERE </error-page>

………………….
…………………. ………………..
</body> ……………….
</html> </web-app>
50
Thanks

51

You might also like