You are on page 1of 55

Introduction to JSP

with Forms and


JavaBeans
Overview
• Embeds Java code
• In HTML tags
• When used well
• Simple way to generate dynamic web-pages
• When misused (complex embedded Java)
• Terribly messy
• Keep the embedded Java simple
• Use external helper classes (Beans?)
How does JSP work?
JSP Document

Translation
.java file

Compilation

.class file

Reinitialization

.class file ready to run

Subsequent
User Requests

Response Document
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
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 woth 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"); %>
</head> Retrieving the string from application...<br>
<body style="font-family:verdana;font-size:10pt"> <b>Name:</b>
<p> <%= application.getAttribute("name") %>
Using Request parameters...<br> </p>
<b>Name:</b> <%= request.getParameter("name") %> <p>
</p> Storing a string to the page context...<br>
<p> <% pageContext.setAttribute("name", "Meeraj"); %>
<% out.println("This is printed using the out implicit Retrieving the string from page context...</br>
variable"); %>
<b>Name:</b>
</p>
<%= pageContext.getAttribute("name") %>
<p>
</p>
Storing a string to the session...<br>
</body>
<% session.setAttribute("name", "Meeraj"); %>
</html>
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

Using Request parameters...


Name: sanjay
This is printed using the out implicit variable
Storing a string to the session...
Retrieving the string from session...
Name: Meeraj
Storing a string to the application...
Retrieving the string from application...
Name: Meeraj
Storing a string to the page context...
Retrieving the string from page context...
Name: Meeraj
Directives
Basics & Types
• Messages sent to the JSP container
• Aids the container in page translation
• Used for
• Importing tag libraries
• Import required classes
• Set output buffering options
• Include content from external files
• The jsp specification defines three directives
• Page: provder information about page, such as scripting language
that is used, content type, or buffer size
• Include – used to include the content of external files
• Taglib – used to import custom actions defined in tag libraries
Page Directives
Basics & Types
• Page directive sets page properties used during translation
• JSP Page can have any number of directives
• Import directive can only occur once
• Embedded in <%@ and %> delimiters
• Different directives are
• Language: (Default Java) Defines server side scripting language (e.g. java)
• Extends: Declares the class which the servlet compiled from JSP needs to
extend
• Import: Declares the packages and classes that need to be imported for
using in the java code (comma separated list)
• Session: (Default true) Boolean which says if the session implicit variable
is allowed or not
• Buffer: defines buffer size of the jsp in kilobytes (if set to none no
buffering is done)
Page Directives
Types con’t.

• Different directives are (cont’d.)


• autoFlush:When true the buffer is flushed when max buffer size is
reached (if set to false an exception is thrown when buffer exceeds
the limit)
• isThreadSafe: (default true) If false the compiled servlet
implements SingleThreadModel interface
• Info: String returned by the getServletInfo() of the compiled servlet
• errorPage: Defines the relative URI of web resource to which the
response should be forwarded in case of an exception
• contentType: (Default text/html) Defines MIME type for the output
response
• isErrorPage: True for JSP pages that are defined as error pages
• pageEncoding: Defines the character encoding for the jsp page
Include Directive
Basics

• Used to insert template text and JSP code during the


translation phase.
• The content of the included file specified by the directive is
included in the including JSP page

• Example
• <%@ include file=“included.jsp” %>
Life Cycle
• A JSP page is translated into a Java Servlet
• And then compiled
• On Tomcat, the compilation happens the first time a page is
requested
• First request can be very slow!
• Afterwards, just as fast as a Servlet (because it is then a
servlet)
Hello World
<html>
<head> <title> Hello JSP </title>
</head>
<body>
<p> Hello World:
<%= new java.util.Date() %>
</p>
</body>
</html>
Date_jsp.java (extract)
• This extract shows the part that produces the output – compare it with
the JSP:
out = pageContext.getOut();
_jspx_out = out;

out.write("<html>\r\n");
out.write("<head> ");
out.write("<title> Hello JSP ");
out.write("</title> ");
out.write("</head>\r\n");
out.write("<body> \r\n");
out.write("<p> Hello World:\r\n ");
out.print( new java.util.Date() );
out.write("\r\n");
out.write("</p>\r\n");
out.write("</body>\r\n");
out.write("</html>\r\n");
Produced
Basic Constructs
• So far we’ve seen literals:
• E.g. <html>
• Copied straight to output (to browser)
• And expressions:
• E.g. <%= new java.util.Date() %>
• Return a value included in the output
• Also have:
• Directives, Declarations and Scriptlets
Directives
• Instructions to the compiler
• Examples:
• Include another page (compile-time)
• <%@ include file="header.jsp" %>
• <jsp:include page="page.jsp" flush="true" />
What is the difference ???
• Import some Java packages (comma sep.)
• <%@ page import=“java.util.Collection”%>
JSP Tags
 These are tags that start with the word jsp as in the previous
example
 These are mainly for handling form beans as will be shown
later apart from 3 tags.
 <jsp:forward, to forward user to another page
 <jsp:forward page="/servlet/login" />
 <jsp:plugin, to import plugin as a java applet in the client
browser.
 <jsp:plugin type=applet code="Molecule.class"
codebase="/html">
 <jsp:include, to include the result of a jsp page
Declarations
• Used to declare variables and methods
• Go in the declaration section of the Servlet
• Can then be used later in the JSP page
• Note the syntax
• Examples:
• <%! int count = 0 %>
• <%! double sqr(double x) {
return x * x; } %>
Scriptlets
• These are sections of Java code embedded in the page
• Unlike expressions, they do not return a value
• But may write directly to the page
• Get the writer: response.getWriter()
• They go in the service method of the servlet
• Get executed each time a page is requested
Illustrative Example
• Demonstrates much of the above
<%! int n = 0; %>
Page accessed: <%= ++n %> times
<% if ( (n % 10) == 0 ) {
n = 0;
}
%>
What happens on next
refresh?
JSP Actions
Basics & Types
• Processed during the request processing phase.
• As opposed to JSP directives which are processed during translation
• Standard actions should be supported by J2EE compliant web servers
• Custom actions can be created using tag libraries
• The different actions are
• Include action
• Forward action
• Param action
• useBean action
• getProperty action
• setProperty action
• plugIn action
JSP Actions
Include

• Include action used for including resources in a JSP page


• Include directive includes resources in a JSP page at translation time
• Include action includes response of a resource into the response of the
JSP page
• Same as including resources using RequestDispatcher interface
• Changes in the included resource reflected while accessing the page.
• Normally used for including dynamic resources

• Example
• <jsp:include page=“inlcudedPage.jsp”>
• Includes the the output of includedPage.jsp into the page where this is
included.
JSP Actions
Forward

• Forwards the response to other web specification resources


• Same as forwarding to resources using RequestDispatcher interface

• Forwarded only when content is not committed to other web


application resources
• Otherwise an IllegalStateException is thrown
• Can be avoided by setting a high buffer size for the forwarding jsp
page

• Example
• <jsp:forward page=“Forwarded.html”>
• Forwards the request to Forwarded.html
JSP objects
• Application
• Config
• Out
• Request
• Response
• Session
Request and Response
• Each JSP page has access to two special objects
• The Request object carries information passed by the HTTP
request (e.g. made by the browser)
• This includes any submitted form data
• The Response object is used to pass information back to the
Client (browser)
• E.g. response.getWriter() provides an output stream
for direct writing to the client
Form Handling with JSP
• JSP makes form handling easy
• Can use request.getParameter() to get submitted
values
• Or can define a JavaBean to grab the values semi-
automatically.
• We’ll see this in action later with a simple example
Processing form input
 Global object: request, session

<% session.putValue(“username”,
request.getParameter(“UserName”)) %>

<html><body>
Thanks for giving us your name, <%=
session.getValue(“username”) %>
</body></html>
Form Processing
• The form can specify whether data is supplied via a GET or
POST request
• POST is the usual way
• Therefore, a servlet should implement the doPost() method to
process a form
• JSP hides these GET/POST details (see
request.getParameter and <jsp:setProperty>)
Form Processing
Architectures
• Helper classes for servlets
• To generate forms (+ other HTML)
• Process the form input
• JSP + JavaBeans (more later)
• JSP + Tag Library (will be covered later)
JavaBeans
• Come in two types
• Simple (this course)
• Enterprise (EJB: more complex, not covered)
• Simple JavaBeans
• Data bound classes
• Define properties (fields)
• Define get/set methods
• See following example
Hotel Booking Form
HTML (body) for Booking Form
<body>
<h3 align="center">Welcome to the Hotel
California</h3>
<form method="POST" action="BookHotel.jsp">
<p>Name: <input type="text" name="name"
size="20"></p>
<p>How many nights:
<select size="1" name="nNights">
<option selected="">1</option>
<option>2</option>
<option>3</option>
</select></p>
<p>
<input type="submit" value="Submit" name="B1">
</p>
</form>
</body>
Accessing Submitted Values
(manual version)
<html>
<head><title>Bean test</title></head>
<body>
<h2>
<%=request.getParameter("name") %>
to stay for
<%= request.getParameter("nNights") %>
nights.
</h2>
</body>
</html>
JavaBean Version (Auto)
<jsp:useBean id='roomBooking'
scope='page'
class='beans.HotelBean'
/>

<jsp:setProperty name='roomBooking' property='*' />

<html>
<head><title>Bean test</title></head>

<body>
<h2> <%=roomBooking.getName()%>
to stay for
<%= roomBooking.getnNights() %> nights. </h2>
</body>
</html>
Java Code for Bean Version
package beans;
public class HotelBean {
String name;
int nNights;

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public int getnNights() {
return nNights;
}
public void setnNights(int nNights) {
this.nNights = nNights;
}
}
Resulting Page
Bean Scope
• Note the setting: scope='page'
• Scope has four possible settings:
• Page
• Bean exists for execution of that page only
• Request
• Like page, but survives any forward or include requests
Bean Scope (cont.)
• Session
• The Bean exists for multiple requests within the web application,
from a particular web browser instance
• Used for shopping baskets etc.
• Application
• The Bean exists for all requests from all users, for all pages that use
it.
• Survives until the Web Application Server is restarted
• Can be used for a database connection (or connection pool)
Beans v. Manual
• For this example, consider the differences:
• JavaBean JSP page: more complex
• JavaBean also required an external class definition
• Discussion question:
• When would JavaBean solutions be better than manual versions?
• Answer:
Functions
<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%!    
Date theDate = new Date();    
Date getDate()     {        
return theDate;    
}
%>
Hello!  The time is now <%= getDate() %>
</BODY>
</HTML>
Functions
• The JSP can get really intractable with lots of scriplets
• A direct example of using scriplet is a for loop to display
records from a database in a table format.
• Put the code for the view in a function and call it as much as
you need
Function – Loop example
<%
public void printRecord(int Number){
out.print(“<TR>”);
out.print(“<TD>Number</TD>”);
out.print(“<TD>” +Number+“</TD>”);
out.print(“</TR>”);
}
%>
<TABLE BORDER=2>
<%
for ( int i = 0; i < n; i++ )
{
printRecord(i+1);
}
%>
</TABLE>
Functions
 This doesn’t look anymore like an HTML code.
 What is the point of JSP then, is it to get messy code!!
 So, sun devised a remedy for that and the final result looked
really good, but not the development
 The solution is called JSP Standard Tag Library or JSTL.
 The last example will be written in one tag as
<mylib: for start=“1” end=“10”/>
JAVA BEANS
• A JavaBean is a specially constructed Java class written in the
Java and coded according to the JavaBeans API specifications.
• Following are the unique characteristics that distinguish a
JavaBean from other Java classes −
• It provides a default, no-argument constructor.
• It should be serializable and that which can implement
the Serializable interface.
• It may have a number of properties which can be read or
written.
• It may have a number of "getter" and "setter" methods for
the properties.
JavaBeans Properties

• A JavaBean property is a named attribute that can be accessed


by the user of the object. The attribute can be of any Java data
type, including the classes that you define.
• A JavaBean property may be read, write, read only, or write
only. JavaBean properties are accessed through two methods
in the JavaBean's implementation class
S.No. Method & Description

getPropertyName()
For example, if property name is firstName, your method name would
be getFirstName() to read that property.
1 This method is called accessor.

setPropertyName()
For example, if property name is firstName, your method name would
be setFirstName() to write that property.
2 This method is called mutator.
Accessing JavaBeans

• The useBean action declares a JavaBean for use in a JSP.


• Once declared, the bean becomes a scripting variable that can
be accessed by both scripting elements and other custom tags
used in the JSP.
• Syntax for the useBean tag is as follows −
• <jsp:useBean id = "bean's name" scope = "bean's scope"
typeSpec/>
• Here values for the scope attribute can be a page, request,
session or application based on your requirement.
• The value of the id attribute may be any value as a long as it is a
unique name among other useBean declarations in the same
JSP.
Accessing JavaBeans Properties
• Along with <jsp:useBean...> action, you can use
the <jsp:getProperty/> action to access the get methods and
the <jsp:setProperty/> action to access the set methods.
• Syntax
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property
name"/> ........... </jsp:useBean>
The name attribute references the id of a JavaBean previously
introduced to the JSP by the useBean action.
The property attribute is the name of the get or the set methods
that should be invoked.

You might also like