0% found this document useful (0 votes)
2 views

@_Java_JSP

Java Server Pages (JSP) is a technology for creating dynamic web content by embedding Java code in HTML, built on the Java Servlets API. JSP offers advantages over servlets such as easier maintenance, no need for recompilation, and a clear separation of presentation, logic, and data layers in a 3-tier architecture. The JSP lifecycle includes translation, compilation, initialization, request processing, and destruction, with various elements like declarations, expressions, comments, and directives to facilitate development.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

@_Java_JSP

Java Server Pages (JSP) is a technology for creating dynamic web content by embedding Java code in HTML, built on the Java Servlets API. JSP offers advantages over servlets such as easier maintenance, no need for recompilation, and a clear separation of presentation, logic, and data layers in a 3-tier architecture. The JSP lifecycle includes translation, compilation, initialization, request processing, and destruction, with various elements like declarations, expressions, comments, and directives to facilitate development.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

JSP(Java Server Pages)

Introduction
 Java Server Pages (JSP) is a technology for developing
Webpages that supports dynamic content. This helps
developers insert java code in HTML pages by making use
of special JSP tags
 Java Server Pages are built on top of the Java Servlets API,
so like Servlets, JSP also has access to all the powerful
Enterprise Java APIs
 JSP pages can be used in combination with servlets that
handle the business logic
How JSP more advantageous than
Servlet?
 They are easy to maintain.
 No recompilation or redeployment is
required.
 Less coding is required in JSP.
 JSP has access to the entire API of JAVA.
 JSP are extended version of Servlet.
 JSP architecture is a 3-tier architecture that separates a
web application's presentation, logic, and data layers.
 The presentation layer, or client side, is responsible for
displaying the user interface and handling user
interaction.
 The logic layer, or server-side, is responsible for
processing user requests and handling business logic.
 The data layer is responsible for storing and retrieving
data from a database or other storage system.
 This separation of concerns allows for better
maintainability and scalability of the application.
JSP architecture flow refers to the sequence of steps a JSP-based
web application goes through to process and execute JSP pages. The
general flow of a JSP architecture can be described as follows:
 A client (such as a web browser) sends a request for a JSP page to
a web server.
 The web server forwards the request to the JSP engine
responsible for processing JSP pages.
 The JSP engine checks if the requested JSP page has been
compiled into a servlet. If not, it compiles the JSP page into a
servlet class. This is done by parsing the JSP page and converting
its elements (such as scriptlets, expressions, and directives) into
Java code.
 The JSP engine then compiles the servlet class, which creates a
Java class file that can be executed by the Java Virtual Machine
(JVM).
 The JSP engine then creates an instance of the servlet class and
calls the service() method, which generates the dynamic content
for the JSP page. Within the service() method, the JSP engine
generates the HTML code for the response by combining the static
template in the JSP page with the dynamic content generated by
the Java code.
 The JSP engine sends the generated HTML code back to the web
server, which then sends it back to the client as a response.
 The JSP engine also maintains a cache of the compiled servlet
classes so subsequent requests for the same JSP page can be
handled more efficiently.
 The web server needs a JSP engine, i.e., a container to
process JSP pages.
 JSP is first converted into a servlet by the JSP container
before processing the client’s request.
 We use Apache which has built-in JSP container to support
JSP pages development
 A JSP container works with the Web server to provide the
runtime environment and other services a JSP needs. It
knows how to understand the special elements that are part
of JSPs.
JSP page

A JSP page is a text-based document that


contains two types of text:
 static template data, which can be expressed in
any text-based format such as HTML, SVG,
WML, and XML, and
 JSP elements, which construct dynamic
content.
JSP Processing
JSP Life Cycle
 A JSP life cycle is defined as the process from its creation till the
destruction
 The following are the paths followed by a JSP
 Translation of JSP Page
 Compilation of JSP Page
 Classloading (the classloader loads class file)
 Instantiation (Object of the Generated Servlet is created).
 Initialization ( the container invokes jspInit() method).
 Request processing ( the container invokes _jspService() method).
 Destroy ( the container invokes jspDestroy() method).
Note: jspInit(), _jspService() and jspDestroy() are the life
cycle methods of JSP.
Translation of JSP Page

 JSP page is translated into Servlet by the help of JSP


translator. The JSP translator is a part of the web server
which is responsible for translating the JSP page into
Servlet.
JSP compilation
 The JSP engine compiles the page
 The compilation process involves three steps:
1. Parsing the JSP.
2. Turning the JSP into a servlet.
3. Compiling the servlet.
Servlet page is compiled by the compiler and gets converted
into the class file.
All the processes that happen in Servlet are performed on
JSP later like initialization, committing response to the
browser and destroy.
 Class Loading – Container loads the class into
memory in this phase.

 Instantiation – Container invokes the no-args


constructor of generated class to load it into memory
and instantiate it.
JSP Initialization

 When a container loads a JSP it invokes the jspInit() method


before servicing any requests.
 If you need to perform JSP-specific initialization, override the
jspInit() method

public void jspInit(){


// Initialization code...
}
JSP Execution
 Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the
JSP.
void _jspService(HttpServletRequest req,HttpServletResponse resp)
{
// Service handling code...
}
 The _jspService() method of a JSP is invoked on request basis. This
is responsible for generating the response for that request and this
method is also responsible for generating responses to all seven of
the HTTP methods, i.e., GET, POST, DELETE, etc.
JSP Cleanup
 The destruction phase of the JSP life cycle represents when a JSP
is being removed from use by a container.
 The jspDestroy() method is the JSP equivalent of the destroy
method for servlets.
 Override jspDestroy when you need to perform any cleanup, such
as releasing database connections or closing open files.
public void jspDestroy()
{
// Your cleanup code goes here.
}
List of basic Elements used in the JSP

1. JSP declaration
2. JSP Expression
3. JSP Comments
4. Scriptlet
5. JSP Directives
6. JSP Actions
JSP Declaration
 A declaration declares one or more variables or methods that you can use in
Java code later in the JSP file.You must declare the variable or method before
you use it in the JSP file.

 Syntax
<%! declaration; [ declaration; ]+ ... %>

 Example
<%! Int a,b,c=0; %>

Examples
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
<html>
<body>
<%!
int cube(int n)
{
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
JSP Expression
 JSP expression element contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file
 The expression element can contain any expression that is valid according to the Java
Language Specification but you cannot use a semicolon to end an expression.

 Syntax
<%= expression %>
 Example
<%= (new java.util.Date()).toLocaleString()%>

Example
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
JSP Comments
 JSP comment marks the text or the statements that the JSP
container should ignore. A JSP comment is useful when you want
to hide or "comment out", a part of your JSP page

 Syntax
<%--This is JSP comment --%>

 Example
<%-- This comment will not be visible in the page source --%>
Scriptlets

 A scriptlet can contain any number of JAVA language statements,


variable or method declarations, or expressions that are valid in
the page scripting language
 Syntax
<% code fragment %>
 Example
<%
Int a,b,c;
out.println(“Name: " + name);
%>
File: index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</body>
</html>
JSP Directives
 A JSP directive affects the overall structure of the servlet class
 Syntax:
<%@ directive attribute="value" %>
 There are three types of directive tag:
1. Page Directive : This directive is used to provide instructions
to the container pertain to the current JSP page
Syntax:
<%@ page attribute="value" %>
Example
<%@ page import="java.sql.*" %>
The Page directive provides many other attributes
Attributes of JSP page directive
 import
 contentType
 extends
 info
 buffer
 language
 isELIgnored
 isThreadSafe
 autoFlush
 session
 pageEncoding
 errorPage
 isErrorPage
1)import
 The import attribute is used to import class,interface or all the
members of a package.It is similar to import keyword in java class
or interface.
Example of import attribute
<html>
<body>

<%@ page import="java.util.Date" %>


Today is: <%= new Date() %>

</body>
</html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet
Mail Extension) type of the HTTP response.The default value is
"text/html;charset=ISO-8859-1".
Example of contentType attribute
<html>
<body>

<%@ page contentType=application/msword %>


Today is: <%= new java.util.Date() %>

</body>
</html>
3)extends
The extends attribute defines the parent class that will be inherited by the
generated servlet.It is rarely used.

4)info
This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet interface.
Example of info attribute
<html>
<body>

<%@ page info="Welcome page" %>


Today is: <%= new java.util.Date() %>

</body>
</html>
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output
generated by the JSP page.The default size of the buffer is 8Kb.

Example of buffer attribute


<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

6)language
The language attribute specifies the scripting language used in the JSP page.
The default value is "java".
isThreadSafe
 By default, servlet engines load a single instance of a servlet and use a
pool of threads to service individual requests.

 This means two or more threads can be executing the same servlet
methods simultaneously. If the servlet has instance variables, and if no
provision is made to synchronize access, the threads can collide and
interfere with each others’ access to the variables.

 Let's understand this with an example. Suppose you have created a JSP
page and mentioned isThreadSafe as true, it means that the JSP page
supports multithreading (more than one thread can execute the JSP page
simultaneously).

 On the other hand, if it is set to false then JSP engine won’t allow
multithreading which means the only single thread will execute the page
code.
9)errorPage
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.

Example of errorPage attribute


//index.jsp
<html>
<body>

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

<%= 100/0 %>

</body>
</html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.

Example of isErrorPage attribute


//myerrorpage.jsp
<html>
<body>

<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>


The exception is: <%= exception %>

</body>
</html>
JSP Directives Contd…
2. Include Directive:

The include directive is used to include a file during the translation


phase. This directive tells the container to merge the content of other
external files with the current JSP during the translation phase. You may
code the include directives anywhere in your JSP page.

Syntax:
<%@ include file="relative url" >

Example
<%@ include file="header.jsp" %>
JSP Directives Contd…
 Taglib Directive: The JavaServer Pages API allow you to define
custom JSP tags that look like HTML or XML tags and a tag
library is a set of user-defined tags that implement custom
behavior.

Syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >

Example
<%@ taglib uri="http://www.example.com/custlib"
prefix="mytag" %>
JSP Actions
 These actions use constructs in XML syntax to control the behavior
of the servlet engine.
 You can dynamically insert a file, reuse JavaBeans components,
forward the user to another page, or generate HTML for the Java
plugin.

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

Example
<jsp:forward page=“home.jsp" />
Implicit Objects
 These objecrs 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 also called pre-defined
variables.

 Following list of objects are widely used


1. request 2. response 3.out 4.session 5.application
6. Config 7. pageContext 8.page 9. Exception
request
 This is the HttpServletRequest object associated with the request.
 Retrieve information sent by client
 The request object provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc.

response
 This is the HttpServletResponse object associated with the response to the
client.
 Send information such as cookies and HTTP response header

out
 This is the PrintWriter object used to send output to the client.

session
 This is the HttpSession object associated with the request.
 Access session related info such as creation time and id associated with session
Application

 This is the ServletContext object associated with the


application context.

 Share data among all pages under this application.

 This object is a representation of the JSP page through its


entire lifecycle. This object is created when the JSP page is
initialized and will be removed when the JSP page is removed
by the jspDestroy() method.
config
 This is the ServletConfig object associated with the page.
 Retrieve initial parameters, servlet name etc.

pageContext
This encapsulates use of server-specific features like higher
performance JspWriters.

page
This is simply a synonym for this, and is used to call the methods defined
by the translated servlet class.

Exception
The Exception object allows the exception data to be accessed by
designated JSP.
 A simple JSP Code

<html>
<body>
<% out.print(2*5); %>
</body>
</html>
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:

 By errorPage and isErrorPage attributes of page directive

 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:


 index.jsp for input values
 process.jsp for dividing the two numbers and displaying the result
 error.jsp for handling the exception
index.jsp

<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No12:<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 %>

You might also like