Adv. P Chapter Five

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 47

Chapter 5

Java Server Page(JSP)

10/19/2024
1
Contents
 Introduction
 Java Server Pages Overview
 Elements of JSP
 Static content
 Scripting elements
 Action
 Directives
 First Java Server Page Examples
 Implicit Object

2 10/19/2024
What's Wrong with Servlets?
import javax.servlet.*; out.println("<HEAD><TITLE>Using
import javax.servlet.http.*; Servlets</TITLE></HEAD>");
import java.io.*; out.println("<BODY BGCOLOR=#123123>");
import java.util.*; //Get parameter names
public class MyDearServlet extends HttpServlet Enumeration parameters =
{ request.getParameterNames();
//Process the HTTP GET request String param = null;
public void doGet(HttpServletRequest request, while (parameters.hasMoreElements()) {
HttpServletResponse response) param = (String) parameters.nextElement();
throws ServletException, IOException { out.println(param + ":" +
request.getParameter(param) +
doPost(request, response);
"<BR>");
}
} Displays All
//Process the HTTP POST request
out.println("</BODY>"); Parameter/Value
public void doPost(HttpServletRequest
request, out.println("</HTML>"); Pairs in a Request
HttpServletResponse response) out.close(); Using JSP
throws ServletException, IOException { } //End of doPost method
response.setContentType("text/html"); } //End of class
PrintWriter out = response.getWriter();
out.println("<HTML>");
3 10/19/2024
Servlet vs JSP
 JSP solves drawbacks in the servlet technology by
allowing the
programmer to intersperse code with static content, for
example.

 If the programmer has to work with an HTML page


template

written by a web designer, the programmer can simply


add code into the HTML page and save it as a .jsp file.

 If at a later stage the web designer needs to change the


HTML body background color, he or she can do it without
wasting the charging-by-the-hour programmer's time.
4 10/19/2024

Displays All Parameter/Value Pairs
in a Request Using JSP
<%@ page import="java.util.Enumeration" %>
<HTML>
<HEAD><TITLE>Using JSP</TITLE></HEAD>
<BODY BGCOLOR=#DADADA>
<%
//Get parameter names
Enumeration parameters = request.getParameterNames();
String param = null;
while (parameters.hasMoreElements()) {
param = (String) parameters.nextElement();
out.println(param + ":" + request.getParameter(param) +
"<BR>");
}
out.close();
%>
</BODY>
</HTML>

5 10/19/2024
Servlet vs JSP
 Youcan see that <HTML> tags stay as they are.
 When you need to add dynamic content, all you
need to do is enclose your code in <% … %> tags.

 Again, JSP is not a replacement for servlets.


 Rather, JSP technology and servlets together
provide an attractive solution to web
scripting/programming by offering platform
independence, enhanced performance, separation of
logic from display, ease of administration,
extensibility into the enterprise, and most
6 10/19/2024
What is JSP ?
 Java
Server Pages (JSP) is a technology for
developing Webpages that supports
dynamic content.

 Thishelps developers insert java code in


HTML pages by making use of special JSP
tags.

7 10/19/2024
What is JSP ?
A Java Server Pages component is a type of
Java servlet that is designed to fulfill the
role of a user interface for a Java web
application.

 Webdevelopers write JSPs as text files that


combine HTML or XHTML code, XML
elements, and embedded JSP actions and
commands.

8 10/19/2024
Why Use JSP?
 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.

 JSPare 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.
9 10/19/2024
Why use JSP ?
 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.
 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.

10 10/19/2024
Advantages of JSP over Servlets
 Servlets use println statements for printing an HTML
document which is usually very difficult to use.
 JSP has no such tedious task to maintain.

 In a JSP page visual content and logic are separated,


which is not possible in a servlet.

 There is automatic deployment of a JSP, recompilation


is done automatically when changes are made to JSP
pages.

 Usually with JSP, Java Beans and custom tags web


application is simplified.

11 10/19/2024
Advantages of JSP-over other
Technologies
 Following is the list of other advantages of using JSP over
other technologies:
 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.


 Pure Servlets
It is more convenient to write (and to modify!)

regular HTML than to have plenty of println


statements that generate the HTML.

12 10/19/2024
Advantages of JSP-over other
Technologies
 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.
 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.
 Static HTML
 Regular HTML, of course, cannot contain dynamic
information.

13 10/19/2024
Elements of JSP
1. The Scriptlet
 A scriptlet can contain any number of JAVA language
statements, variable or expressions that are valid in
the page scripting language.
 Following is the syntax of Scriptlet:

<% code fragment %>


You can write the XML equivalent of the above
syntax as follows:

<jsp:scriptlet>
code fragment
</jsp:scriptlet>
14 10/19/2024
Elements of JSP-scriptlet
 Any text, HTML tags, or JSP elements you write must be
outside the scriptlet. Following is the simple and first
example for JSP:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " +
request.getRemoteAddr());
%>
</body>
</html>

15 10/19/2024
The Scriptlet-example
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<h1><font color="red"> Hello World</h1>
<body>
<h1>Hello World!</h1>
<%
for(int i=0;i<10;i++){
out.println(i);
}
%>
</body>
</html>

16 10/19/2024
Elements of JSP
2. JSP Declarations : allow you to declare methods and
variables that can be used from any point in the JSP
page.
 Declarations also provide a way to create initialization
and clean-up code by utilizing the jspInit and jspDestroy
methods.
 can appear anywhere throughout the page
<%! declaration; [ declaration; ]+ ...
Following is the syntax for JSP Declarations:
%>

example for JSP Declarations:


<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
17 10/19/2024
Elements of JSP
3. JSP Expression
The expression is evaluated when the JSP
page is requested and, converted into a
string, and sent to the output stream of the
servlet.
 If this is not detected at translation time, at
request-processing time, a ClassCastException
will be raised.

 Theexpression element can contain any


expression that is valid according to the Java
Language Specification but you cannot use a
semicolon to end an expression.
18 10/19/2024
Elements of JSP-expressions
 Following is the syntax of JSP Expression:

<%= expression %>

example shows a JSP Expression:


<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()
%>
</p>
</body>
</html>

19 10/19/2024
Expressions- Example
<html>
<%
int a = 5;
int b = 8;
%>
<body>
The first number is : <%= a %> <br/>
The second number is : <%= b %>
<br/>
The sum is : <%= ( a + b ) %> <br/>
</body
</html>
20 10/19/2024
Elements of JSP
4. 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.

 Following is the syntax of the JSP comments:

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

21 10/19/2024
Elements of JSP
 example shows the JSP Comments:

<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the
page source --%>
</body>
</html>

22 10/19/2024
Elements of JSP
5. JSP Directives
A JSP directive is a statement that gives the JSP
engine information about the JSP page.

 For example, if your JSP page uses a Java class


from a package other than the java.lang package,
you have to use a directive to import this package.
The general syntax for a JSP directive is shown
below:

<%@ directive attribute="value" %>

23 10/19/2024
Elements of JSP-Directives
There are three types of directive tag:
Directive Description

page lets you provide information for the


page, such as importing classes and setting
up content type. The page directive can
<%@ page ... %> appear anywhere in the JSP file. Also Defines
page-dependent attributes, such as scripting
language, error page, and buffering
requirements.

include lets you insert a file to the servlet


when the page is translated to a servlet. The
<%@ include ... %>
include directive must be placed where you
want the file to be inserted.

<%@ taglib ... %> tablib lets you define custom tags.

24 10/19/2024
JSP ─ DIRECTIVES
 These directives provide directions and
instructions to the container, telling it how to
handle certain aspects of the JSP processing.

A JSP directive affects the overall structure of the


servlet class.
 It usually has the following form:

<%@ directive attribute="value"


%>

25 10/19/2024
The 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.

The general usage form of this directive is as follows:

<%@ include file="relative url" >

26 10/19/2024
include example

display.j
Index.js sp
<html>
p
<head> <html>
<title>JSP include Directive <head>
example</title> <body>
</head> <p>This is the content of my
<body> file</p>
<%@ include file="display.jsp" </body>
%> </html>
</body>
</html>

27 10/19/2024
Include -Example
A good example of the include directive is
including a common header and footer with
multiple pages of content.
 Let us define following three files

a) header.jps,
b) footer.jsp,
c) main.jsp as follows:

28 10/19/2024
Include -Example
 The following is the content of header.jsp:

<%!
int pageCount = 0;
void addCount() {
pageCount++;
}
%>
<% addCount(); %>
<html>
<head>
<title>The include Directive Example</title>
</head>
<body>
<center>
<h2>The include Directive Example</h2>
<p>This site has been visited <%= pageCount %> times.</p>
</center>
<br/><br/> 10/19/2024
29
Include -Example
 Following is the content of footer.jsp:

<%@ include file="header.jsp" %>


<center>
<p>Thanks for visiting my
page.</p>
</center>
<%@ include file="footer.jsp" %>

30 10/19/2024
Include -Example
 you will receive the following output:

31 10/19/2024
The page Directive
 The page directive is used to provide instructions
to the container.
 These instructions pertain to the current JSP page.
 You may code page directives anywhere in your
JSP page.

 By convention, page directives are coded at the


top of the JSP page.
 Following is the basic syntax of the page directive:

<%@ page attribute="value" %>

32 10/19/2024
The page Directive-example
Example:

<%@ page buffer="16384" %>


<%@ page session="false" %>
<%@ page info="Written by Moti" %>
<%@ page language="java" %>

33 10/19/2024
The page Directive-Attributes
Following table lists out the attributes associated with page directive:
Attribute Purpose
buffer Specifies a buffering model for the output stream.
autoFlush Controls the behavior of the servlet output buffer.
contentType Defines the character encoding scheme.
Defines the URL of another JSP that reports on Java
errorPage
unchecked runtime exceptions.
Indicates if this JSP page is a URL specified by another JSP
isErrorPage
page's errorPage attribute.
Specifies a superclass that the generated servlet must
extends
extend.
Specifies a list of packages or classes for use in the JSP as
import
the Java import statement does for Java classes.
Defines a string that can be accessed with the servlet's
info
getServletInfo() method.
isThreadSafe Defines the threading model for the generated servlet.
language Defines the programming language used in the JSP page.
Specifies whether or not the JSP page participates in HTTP
session
sessions

34 10/19/2024
Example
 The extends Attribute
The extends attribute specifies a superclass that
the generated servlet must extend.

For example, the following directive directs the JSP


translator to generate the servlet such that the
servlet extends somePackage.SomeClass:

<%@ page extends="somePackage.SomeClass" %>

35 10/19/2024
Example
The import Attribute
The import attribute serves the same function as, and
behaves like, the Java import statement.
 The value for the import option is the name of the
package you want to import.

 To import java.sql.*, use the following page directive:

<%@ page import="java.sql.*" %>

To import multiple packages, you can specify them separated


by comma as follows:

<%@ page import="java.sql.*,java.util.*" %>

36 10/19/2024
Elements of JSP
6. JSP Actions
JSP 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.

 There is only one syntax for the Action element, as


it conforms to the XML standard:

<jsp:action_name attribute="value" />

37 10/19/2024
Elements of JSP-Actions
 Action elements are basically predefined functions.
Following table lists out the available JSP Actions:

Syntax Purpose

Includes a file at the time the


jsp:include
page is requested.

jsp:useBean Finds or instantiates a JavaBean.

jsp:setProperty Sets the property of a JavaBean.


Inserts the property of a JavaBean
jsp:getProperty
into the output.
Forwards the requester to a new
jsp:forward
page.

38 10/19/2024
Elements of JSP-Actions

Generates browser-specific code


jsp:plugin that makes an OBJECT or
EMBED tag for the Java plugin.

jsp:element Defines XML elements dynamically.

Defines dynamically-defined XML


jsp:attribute
element's attribute.

Defines dynamically-defined XML


jsp:body
element's body.

Used to write template text in JSP


jsp:text
pages and documents.

39 10/19/2024
JSP Implicit Objects
JSP supports nine automatically defined variables, which are
also called implicit objects. These
variables are:

Objects Description

This is the HttpServletRequest object


request associated with the
request.

This is the HttpServletResponse


response object associated with the
response to the client.

This is the PrintWriter object used to


out send output to the
client.

This is the HttpSession object


session
associated with the request.

40 10/19/2024
JSP Implicit Objects
This is the ServletContext object
application associated with
application context.

This is the ServletConfig object


config
associated with the page.

This encapsulates use of server-specific


pageContext features like higher
performance JspWriters.

This is simply a synonym for this, and is


used to call the
page
methods defined by the translated
servlet class.
The Exception object allows the
Exception exception data to be
accessed by designated JSP.

41 10/19/2024
First JSP program
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Hello World.</h1>
</body>
</html>

42 10/19/2024
First JSP program
<html>
<%
int a = 5;
int b = 8;
%>
<body>
The first number is : <%= a %> <br/>
The second number is : <%= b %>
<br/>
The sum is : <%= ( a + b ) %> <br/>
</body
</html>
43 10/19/2024
First JSP program

Variable or method declarations can be also


written between the Declaration tags ( <%!
%> ):
<%!
int a, b;
public int sum( int i1, int i2 ) {
return i1 + i2;
}
%

44 10/19/2024
JSP JDBC Example
<%@ page session="false" %>
<%@ page import="java.sql.*" %>
<%
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("JDBC driver loaded");
}
catch (ClassNotFoundException e) {
System.out.println(e.toString()); }
%>
<HTML>
<HEAD>
<TITLE>Display All Users</TITLE>
</HEAD>
<BODY>
<CENTER>
<BR><H2>Displaying All Users</H2>

45 10/19/2024
JSP JDBC Example
<BR>
<BR>
<TABLE>
<TR>
<TH>First Name</TH>
<TH>Last Name</TH>
<TH>User Name</TH>
<TH>Password</TH>
</TR>
<%
String sql = "SELECT FirstName, LastName, UserName, Password" +
" FROM Users";
try {
Connection con = DriverManager.getConnection(“com:mysql:jdbc:Driver");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(sql);

46 10/19/2024
JSP JDBC Example
while (rs.next()) {
out.println("<TR>");
out.println("<TD>" + rs.getString(1) + "</TD>");
out.println("<TD>" + rs.getString(2) + "</TD>");
out.println("<TD>" + rs.getString(3) + "</TD>");
out.println("<TD>" + rs.getString(4) + "</TD>");
out.println("</TR>");
}
rs.close();
s.close();
con.close(); }
catch (SQLException e) {}
catch (Exception e) { }
%>
</TABLE>
</CENTER>
</BODY>
</HTML>

47 10/19/2024

You might also like