JSP(JAVA Server Pages)
JSP(JAVA Server Pages)
Pages)
Introduction
JavaServer Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI).
But JSP offers several advantages in comparison with the CGI.
Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having separate CGI files.
JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
JSP pages can be used in combination with servlets that handle the business logic, the
model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.
advantages
vs. Active Server Pages (ASP) The advantages of JSP are twofold.
First, the dynamic part is written in Java, not Visual Basic or other MS specific
language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.
vs. Pure Servlets It is more convenient to write (and to modify!) regular HTML
than to have plenty of println statements that generate the HTML.
vs. Server-Side Includes (SSI) SSI is really only intended for simple inclusions, not
for "real" programs that use form data, make database connections, and the like.
vs. JavaScript JavaScript can generate HTML dynamically on the client but can
hardly interact with the web server to perform complex tasks like database
access and image processing etc.
vs. Static HTML Regular HTML, of course, cannot contain dynamic information.
JSP ─ ARCHITECTURE
Processing
The following steps explain how the web server creates the Webpage using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and all
JSP elements are converted to Java code. This code implements the corresponding dynamic
behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request
to a servlet engine. A part of the web server called the servlet engine loads the Servlet class
and executes it.
During execution, the servlet produces an output in HTML format. This output is further passed
on to the web server by the servlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.
Life Cycle
A JSP life cycle is defined as the process from its creation till the
destruction.
This is similar to a servlet life cycle with an additional step which is
required to compile a JSP into servlet.
The following are the paths followed by a JSP
Compilation
Initialization
Execution
Cleanup
The four major phases of a JSP life cycle are very similar to the
Servlet Life Cycle. The four phases have been described below:
Java Server Pages (JSP)
Fundamentals
Java Server Pages are HTML pages embedded with snippets of
Java code.
It is an inverse of a Java Servlet
Four different elements are used in constructing JSPs
Scripting Elements
Implicit Objects
Directives
Actions
Java Server Pages (JSP)
Architecture
JSPs run in two phases Receive HTTP Server
Request
Translation Phase
JSP Container
Execution Phase
Page Compiler Servlet
In translation phase JSP page JSP Servlet No
Parse JSP
is compiled into a servlet Current?
Yes
called JSP Page
JSP Servlet Generate JSP
Implementation class Loaded? Servlet Source
In execution phase the Yes No
compliled JSP is processed Load Servlet
Compile JSP
Servlet
Send
Response
Scripting Elements
Types
There are three kinds of scripting elements
Declarations
Scriptlets
Expressions
Declarations
Basics
Declarations are used to define methods & instance variables
Do not produce any output that is sent to client
Embedded in <%! and %> delimiters
Example:
<%!
Public void jspDestroy() {
System.out.println(“JSP Destroyed”);
}
Public void jspInit() {
System.out.println(“JSP Loaded”);
}
int myVar = 123;
%>
The functions and variables defined are available to the JSP Page
as well as to the servlet in which it is compiled
Scriptlets
Basics
Used to embed java code in JSP pages.
Contents of JSP go into _JSPpageservice() method
Code should comply with syntactical and semantic constuct of java
Embedded in <% and %> delimiters
Example:
<%
int x = 5;
int y = 7;
int z = x + y;
%>
Expressions
Basics
Used to write dynamic content back to the browser.
If the output of expression is Java primitive the value is printed
back to the browser
If the output is an object then the result of calling toString on the
object is output to the browser
Embedded in <%= and %> delimiters
Example:
<%=“Fred”+ “ “ + “Flintstone %>
prints “Fred Flintstone” to the browser
<%=Math.sqrt(100)%>
prints 10 to the browser
Java Implicit Objects
Scope
Implicit objects provide access to server side objects
e.g. request, response, session etc.
There are four scopes of the objects
Page: Objects can only be accessed in the page where they are
referenced
Request: Objects can be accessed within all pages that serve
the current request.
(Including the pages that are forwarded to and included in
the original jsp page)
Session: Objects can be accessed within the JSP pages for which
the objects are defined
Application: Objects can be accessed by all JSP pages in a given
context
Java Implicit Objects
List
request: Reference to the current request
response: Response to the request
session: session associated worth current request
application: Servlet context to which a page belongs
pageContext: Object to access request, response, session and
application associated with a page
config: Servlet configuration for the page
out: Object that writes to the response output stream
page: instance of the page implementation class (this)
exception: Available with JSP pages which are error pages
Java Implicit Objects
Example
<html> <p>
<head> Storing a string to the application...<br>
<title>Implicit Objects</title> <% application.setAttribute("name", "Meeraj"); %>
Retrieving the string from application...<br>
</head>
<b>Name:</b>
<body style="font-family:verdana;font-size:10pt">
<%= application.getAttribute("name") %>
<p>
</p>
Using Request parameters...<br>
<p>
<b>Name:</b> <%= request.getParameter("name") %>
Storing a string to the page context...<br>
</p> <% pageContext.setAttribute("name", "Meeraj"); %>
<p> Retrieving the string from page context...</br>
<% out.println("This is printed using the out implicit <b>Name:</b>
variable"); %>
<%= pageContext.getAttribute("name") %>
</p> </p>
<p> </body>
Storing a string to the session...<br> </html>
<% session.setAttribute("name", "Meeraj"); %>
Retrieving the string from session...<br>
<b>Name:</b> <%= session.getAttribute("name") %>
</p>
Example Implicit Objects
Deploy & Run
Save file:
$TOMCAT_HOME/webapps/jsp/Implicit.jsp
Access file
http://localhost:8080/jsp/Implicit.jsp?name=Sanjay
Results of the execution
<tr> </body>
throws ServletException { }
doGet(req, res);
}
}
}
Inventory
UpdateServlet
package edu.albany.mis.goel.servlets; // Create a connection through the DriverManager class
con = DriverManager.getConnection(sourceURL);
import javax.servlet.ServletException; System.out.println("Connected Connection");
import javax.servlet.ServletConfig; PreparedStatement stmt= con.prepareStatement
import javax.servlet.http.HttpServlet; ("update item " + "set name = ?, " + "description = ?, " + "price = ?, "
} } catch(Exception ex) {
throw new ServletException(ex);
public void doGet(HttpServletRequest req, HttpServletResponse res)
}
throws ServletException {
}
Connection con = null;
}
try { // Load the driver class
}
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Inventory
Edit.jsp
<%@page contentType="text/html"%> <tr>
<jsp:useBean id="rs" scope="request" type="javax.sql.RowSet" /> <td><b>Price:</b></td>
<html> <td>
<head> <input name="price" type="text" value="<%= rs.getString(4) %>"/>
<title>Inventory - Edit</title> </td>
</head> </tr>
<body style="font-family:verdana;font-size:10pt;"> <tr>
<% <td><b>Stock:</b></td>
if(rs.next()) {
<td>
<input name="stock" type="text" value="<%= rs.getString(5) %>"/>
%>
</td>
<form action="Update">
</tr>
<input name="id" type="hidden" value="<%= rs.getString(1) %>"/>
<tr>
<table cellpadding="5" style="font-family:verdana;font-size:10pt;">
<td></td>
<tr>
<td>
<td><b>Name:</b></td>
<input type="submit" value="Update"/>
<td>
</td>
<input name="name" type="text" value="<%= rs.getString(2) %>"/>
</tr>
</td>
</table>
</tr>
<%
<tr>
}
<td><b>Description:</b></td>
%>
<td> </body>
<input name="description" type="text" value="<%= rs.getString(3) </html>
%>"/>
</td>
</tr>
Inventory
Edit.jsp
<%@page contentType="text/html"%> <tr>
<jsp:useBean id="rs" scope="request" type="javax.sql.RowSet" /> <td><%= rs.getString(2) %></td>
<td><%= rs.getString(3) %></td>
<td><%= rs.getString(4) %></td>
<html>
<td><%= rs.getString(5) %></td>
<head>
<td>
<title>Inventory - List</title>
<a href="Delete?id=<%= rs.getString(1) %>">
</head>
Delete
<body style="font-family:verdana;font-size:10pt;">
</a>
<table cellpadding="5" style="font-family:verdana;font-size:10pt;"> </td>
<tr> <td>
<th>Name</th> <a href="Edit?id=<%= rs.getString(1) %>">
<th>Description</th> Edit
<th>Price</th> </a>
<th>Stock</th> </td>
<th></th> </tr>
<th></th> <%
}
</tr>
%>
<%
</table>
while(rs.next()) {
<a href="New.html">New Item</a>
%>
</body>
</html>
Inventory
New.html
<html> <tr>
<head> <td></td>
<title>Inventory - Add New Item</title> <td><input type="submit" value="Create"/></td>
</head> </tr>
<body style="font-family:verdana;font-size:10pt;">
</table>
<form action="Create">
</body>
<table cellpadding="5" style="font-family:verdana;font-size:10pt;">
</html>
<tr>
<td><b>Name:</b></td>
<td><input name="name" type="text"/></td>
</tr>
<tr>
<td><b>Description:</b></td>
<td><input name="description" type="text"/></td>
</tr>
<tr>
<td><b>Price:</b></td>
<td><input name="price" type="text"/></td>
</tr>
<tr>
<td><b>Stock:</b></td>
<td><input name="stock" type="text"/></td>
</tr>