Sei sulla pagina 1di 88

J2EE

JavaBeans and JSP

Module 2
Agenda

1 Introduction JSP

2 JSP Architecture

3 Elements of JSP

4 JavaBean
Objectives

At the end of this module, you will be able to:

– Compare JSP and servlets


– Explain JSP request model
– Explain JSP architecture models
– Understand the structure of a jsp page
– Use JSP constructs such as expressions, scriptlets,
and declarations
– Create simple jsp pages
Introduction to JSP
What is JSP?

JSP stands for Java Server Pages, a technology invented


by Sun to allow the easy creation of server side HTML
pages.

JSP lies in the presentation tier on the web server, with the
main responsibility of generating HTML content that needs
to be served to the browser. It also has the additional
responsibility of pass on the requests to the backend
through the JavaBeans, as and when required.
Notes

• Stands for Java Server Pages


• Is a Technology invented by Sun Microsystems
• Allows the easy creation and maintenance of server side HTML pages
• Can be used as both a kind of Dynamic HTML and CGI replacement
JSP: JSP Request Model
Notes

• The above picture brings a perspective on where JSP fits in the 3-tier
web application architecture.

• JSP lies in the presentation tier on the web server, with the main
responsibility of generating HTML content that needs to be served to
the browser. It also has the additional responsibility of pass on the
requests to the backend through the JavaBeans, as and when
required.
JSP: What makes JSP so attractive?

1. High performance

2. Convenient to code and maintain as against servlets

3. Separates presentation from content

4. Powered by Java
– Has access to all Java APIs
– Has access to all J2EE APIsa
– Inherent Platform independence
Notes

• higher performance than CGI

• can leverage the powerful features of Java

• allow the user to create their own utility, or business logic classes

• can make a complete separation of presentation (HTML) and code


(Java)
JSP Architecture
The Architecture
Notes

• Typically HTTP requests are sent to the web server from a browser
client. If the request if for a static HTML page, the web server itself
responds. However, if the request is for a JSP or a servlet, the add-
ons to a web server viz. servlet engine or JSP engine respond. These
engines require a JVM as, they are themselves Java-based.
The Architecture: The flow of JSP request
Notes
• The flow of a JSP request:
1.The HTTP request comes to a web server.
2.The server extension receives the request (as it is not a request for
static HTML but for a JSP) and passes it on to the JSP engine.
3.The JSP engine invokes the JSP parser to parse the JSP and check for
any syntax errors.
4.On successful parsing, the JSP engine invokes the Java compiler to
compile the JSP into an equivalent servlet class.
5.Once the class is generated, the control is passed on to a servlet
engine.
6.The servlet engine loads the servlet into memory using its class loader.
7.The appropriate methods in the servlet are invoked and the response is
routed back to the browser via the server extension and web server.
The Architecture: JSP Architecture Models

Sun specifies two different architectural models for building


applications using Servlet and JSP.

1. JSP Model 1 Architecture

2. JSP Model 2 Architecture


Notes

• The J2EE tutorial of SUN specifies 2 ways of building


applications using Servlet and JSP, which are known as JSP
Model 1 and JSP Model 2 Architecture. The difference between
these two lies in the way they handle the request.
The Architecture: JSP Model 1 Architecture

Application Server
Client

1. Request

Browser JSP
4. Response

2. Creates
JavaBeans

3. Retrieves Data
JavaBeans

DB
Notes

• In the model1 architecture the target of every


request is a JSP page. This page is completely
responsible for doing all the task required [to
fulfill the request. This includes authenticating
the client, using Java Bean to assess data,
managing the state of the user, and so forth.
The Architecture: JSP Model 2 Architecture
Notes
• This architecture follows the Model-View-
Controller design pattern. In this architecture,
the target of all requests are Servlet that acts
as a controller for the application. They
analyze the request and collect all the data
required to generate a response into
JavaBeans object, which act as a model for
the application. Finally the controller servlet
dispatches the request to the JSP page. This
page uses the data stored in the JavaBeans
object to generate a presentable response.
Thus the JSP page form a view for the
application.
Quiz

1.A JSP page is transformed into ___________________.

2.JSP pages provide a means to create dynamic Web


pages using HTML and the Java programming language.
(TRUE/ FALSE)

3.With JSP, the coding is done in Java and only in


Java.(TRUE/ FALSE)
Elements of JSP
Elements of JSP

The three basic elements of a JSP are:


1. Scripting elements
2. Directives
3. Actions
Notes

There are three main types of JSP constructs that


you embed in a page:
• scripting elements
• directives
• actions

To simplify the scripting elements, you have access


to a number of predefined variables, discussed
later.
Elements of JSP: Scripting Elements

Lets you insert Java code into the servlet that will be
generated from the current JSP page.
There are three forms:
• Expressions
Useful shorthand for printing out strings and
contents of variables.
• Scriptlets
Lets you insert any valid Java code into the JSP.
• Declarations
Useful for declaring page wide variables and
methods(Java) or functions.
Notes

• Expressions
• Useful shorthand for printing out strings and
contents of variables.

• Scriptlets
• Lets you insert any valid Java code into the
JSP.

• Declarations
• Useful for declaring page wide variables and
methods (Java) or functions.
Scripting Elements: Expressions

A JSP expression is used to insert Java values directly into the output.
<%= Java Expression %>

• The Java expression is evaluated, converted to a string, and inserted


in the page. This evaluation is performed at run-time (when the page is
requested), and thus has full access to information about the request.

• For example, the following shows the date/time that the page was
requested: Current time: <%= new java.util.Date() %>

• This evaluation is performed at run-time. To simplify these


expressions, there are a number of predefined variables that you can
use. Finally, note that XML authors can use an alternative syntax for JSP
expressions:
<jsp:expression> Java Expression </jsp:expression>
Example on Expressions

• A first JSP example


welcome.jsp
<html>
<head><title>A first simple JSP</title></head>
<body>
<h3>
<%= “Welcome to JSP world!!!" %>
</h3>
</body>
</html>
Expressions: Pre-defined Variables
• To simplify the expressions, there are a number of predefined
variables that you can use

• The most important ones are:


– request
– response
– session
– out
Notes
• Request: This object is asssociated with
HttpServletRequest, and lets you look at the request
parameters (via getParameter), the request type (GET,
POST, HEAD, etc.), and the incoming HTTP headers
(cookies, Referrer, etc.). Strictly speaking, request is
allowed to be a subclass of ServletRequest other than
HttpServletRequest, if the protocol in the request is
something other than HTTP. This is almost never done in
practice.
• Response: This object is associated with the
HttpServletResponse . Note that, since the output stream
is buffered, it is legal to set HTTP status codes and
response headers, even though this is not permitted in
regular servlets once any output has been sent to the
client.
Notes
• Response: This object is associated with the HttpServletResponse .
Note that, since the output stream is buffered, it is legal to set HTTP
status codes and response headers, even though this is not permitted in
regular servlets once any output has been sent to the client.
• Session: This object associated with the HttpSession. In JSPs sessions
are created automatically, so this variable is bound even if there was no
incoming session reference. If the session attribute of the page directive
to turn sessions off, in which case attempts to reference the session
variable causes errors at the time the JSP page is translated into a
servlet.
• Out: This is object type of the PrintWriter to send output to the client.
However, in order to make the response object useful, this is a buffered
version of PrintWriter called JspWriter. Note that you can adjust the buffer
size, or even turn buffering off, through use of the buffer attribute of the
page directive. Also note that out is used almost exclusively in scriptlets,
since JSP expressions automatically get placed in the output stream, and
thus rarely need to refer to out explicitly.
The Request Object Example

<html>
<head><title>Request Header Info</title></head>
<body bgcolor="white">
<ul>
<li>Request Method: <%=request.getMethod() %>
<li>Request URL :<%=request.getRequestURI()%>
<li>Request Protocol :<%=request.getProtocol() %>
<li>Server Name :<%=request.getServerName()%>
<li>Server Port :<%=request.getServerPort()%>
<li>Remote Address: <%=request.getRemoreAddr() %>
<li>Browser :<%=request.getHeader("User-Agent") %>
</ul>
</body>
</html>
The out object Example
<html>
<head><title>The Out Object Example</title></head>
<body bgcolor="white">
<% out.print("<h3> JSP BufferInformation</h3>");
<%-- display the page buffer size --%>
Buffer:<%=out.getBufferSize() %> bytes <br/>
<%-- display the AutoFlush setting -- %>
AutoFlush: <%=out.isAutoFlush() %> <br/>
<%-- display the free page buffer space --%>
Remaining buffer : <%=out.getRemaining() %> bytes
</body>
</html>
The Response Object Example
<html>
<head><title>Response Object Info</title></head>
<body bgcolor="white">
<% response.setContentType("text/html"); %>
Buffer Size: <response.getBufferSize() %> bytes <br/>
Character Encoding :<%=response.getCharacterEncoding()
%>
<br/>
Locale: <%=response.getLocale() %>
<%-- redirect the user to another.html --%>
<%
response.sendRedirect("http://localhost:8080/another.
html"); %>
</body>
</html>
The session object Example
<html>
<head><title>The Out Object
Example</title></head>
<body bgcolor="white">
Session: <%=session.getId() %><hr/>
<% session.invalidate();%>
Session : <% if(session.getId() !=null)
out.println(session.getId());
else
out.println("Session ended ") ; %>
</body>
</html>
Notes

• <HTML> <HEAD> <TITLE> Expressions </TITLE> </HEAD>


• <BODY><TABLE BORDER=2>
• <TR> <TH>Message</TH> <TH>Result</TH> </TR>
• <TR> <TD>SQRT of 4</TD>
• <TD> <%= Math.sqrt(2) %></TD> </TR>
• <TR> <TD>Current time</TD>
• <TD> <%= new java.util.Date() %></TD> </TR>
• <TR> <TD>Your hostname</TD>
• <TD> <%= request.getRemoteHost() %></TD>
</TR>
Notes

• <TR> <TD>Port :</TD>


• <TD> <%= request.getServerPort() %></TD>
</TR>
• <TR> <TD>Scheme </TD>
• <TD> <%= request.getScheme() %></TD>
</TR>
• <TR> <TD> Address</TD>
• <TD> <%= request.getServerName()
%></TD> </TR>
• </TABLE>
• </BODY> </HTML>
Scripting Elements: Scriptlets
• Are defined as any block of valid Java code that resides
between <% and %> tags

• Code that is defined within a scriptlet can access any variable


and any beans that have been declared

• Scriptlets are like declarations in that they always use


semicolons to end statements and expressions. They can have
multiple expressions and statements as long as each is ended
with a semicolon

• Scriptlets code goes into the service method of the JSP’s


compiled servlet which means it is executed only once when a
request is actually serviced by the JSP
Notes
• Scriptlets can access predefined variable like out, request
and response objects. So, for example, if you want output to
appear in the resultant page, you would use the out variable.
• <%
• String queryData = request.getQueryString();
• out.println("Attached GET data: " + queryData);
• %>
• Scriptlets are like declarations in that they always use
semicolons to end statements and expressions. They can
have multiple expressions and statements as long as each
is ended with a semicolon.
• Scriptlets code goes into the service method of the JSP’s
compiled servlet which means it is executed only once when
a request is actually serviced by the JSP.
Notes

• If you want to use the characters "%>" inside a scriptlet, enter "%\>"
instead. XML syntax scriptlet is
• <jsp:scriptlet>
• Code
• </jsp:scriptlet>
• NOTE: Declarations are executed at initialization time; Expressions
and Scriptlets at request Time.
Scriptlets Example
<html>
<head><title>Scriptlet Example</title></head>
<body bgcolor="white">

<% java.util.Date now= new java.util.Date();


%>
Current date &amp time :<%= now %>
<% if(now.getHourse()<12) { %> Good Morning!
<% } else if(now.getHours() <17 { %> Good
Afternoon!
<% } else { %> Good Evening! <% } %>
</body>
</html>
Notes
• <TABLE BORDER=3>
• <TR><TH>Course</TH><TH>Duration</TH>
• <%
• String []course = {"OOAD","Java","Internet","Web"};
• int []durn = {2,4,3,2};
• for(int i=0; i < course.length; i++)
• {%>
• <TR>
• <TD> <%=course[i]%> </TD>
• <TD> <%=durn[i]%> </TD>
• </TR>
• <%}%>
• </TABLE>
Scripting Elements: Declaration

• Used to define methods or fields that get inserted into


the main body of the servlet class

• It has the form: <%! Java Code %>

• The scope of a declaration is usually a JSP file, but if the


JSP file includes other files with the include directive, the
scope expands to cover the included files as well
Notes

• Since declarations do not generate any output,


they are normally used in conjunction with JSP
expressions or scriptlets.
• <%! private int accessCount = 0; %>
• Accesses to page since server reboot:
• <%= ++accessCount %>
• As with scriptlets, if you want to use the characters
"%>", enter "%\>" instead.
• XML equivalent of declaration is
• <jsp:declaration>
• Code
• </jsp:declaration>
Declaration Scripting Element

<html>
<head><title>Declaration sricpting element
Example</title></head>
<body bgcolor="white">

<%! int counter=0; %>

Global counter :<%=++counter %>


</body>
</html>
Above example, prints that prints out the
number of times the current page has been
requested since the server class loaded.
Notes

• Above example, prints that prints out the number


of times the current page has been requested since
the server class loaded.
Directives

• Affect the overall structure of the servlet class generated


from this JSP

• format: <%@ directive attribute="value" %>

• There are two main types of directives:


– page
– include
Notes
• A JSP directive affects the overall structure of the servlet class. It
usually has the following form:
• <%@ directive attribute="value" %>
• However, you can also combine multiple attribute settings for a single
directive, as follows:
• <%@ directive attribute1="value1"
• attribute2="value2"
• ...
• attributeN="valueN" %>
• There are two main types of directive: page, which lets you do things
like import classes, customize the servlet superclass, and the like; and
include, which lets you insert a file into the servlet class at the time the
JSP file is translated into a servlet. The specification also mentions
the taglib directive, which is not supported in JSP version 1.0, but is
intended to let JSP authors define their own tags. Tags are supported
from JSP 1.1.
Directives: Page Directives

• Defines attributes that apply to an entire JSP page

• Lets you do things like:


– Import classes
– Handle error messages
– Define if the JSP is thread-safe
– Define is session object is available
– Set the page content type
Notes
• The page directive containing information will appears as:
• <%@ page attribute1=“value” attribute2=“value2” …..%>
• Attribute meaning
• contentTypespecifies the MIME type to be used for the page
to be generated by the JSP
• Import makes available methods within the specified java
class
• Session gives access to a JSP implicit session variable when
true to allow the page to participate in an interactive user
session, by default value is true
• errorPage Status a URL to where the user is redirected if an
error occurs
• isErrorPage Gives access to a JSP implicit exception
variable when true to allow an error to be examined and
handled. By default value is false.
Notes
• <BODY>
• Some dynamic content created using various JSP mechanisms:
• <UL>
• <LI><B>Expression.</B><BR>
• Your hostname: <%= request.getRemoteHost() %>.
• <LI><B>Scriptlet.</B><BR>
• <% out.println("Attached GET data: " +
• request.getQueryString()); %>
• <LI><B>Declaration (plus expression).</B><BR>
• <%! private int accessCount = 0; %>
• Accesses to page since server reboot: <%= ++accessCount %>
• <LI><B>Directive (plus expression).</B><BR>
• <%@ page import = "java.util.*" %>
• Current date: <%= new Date() %>
• </UL>
• </BODY>
Notes
• Example on Handling Errors
• <!-- This JavaServer Page purposefully throws a NullPointerException
• that demonstrates using a JSP error page. (ErrorPage.jsp)
• -->
• <%@ page
• errorPage="ErrPage.jsp"
• import="java.util.Vector"
• import="java.io.*"
• %>
• <html>
• <head></head>
• <%! Vector vec = null; %>
• <body bgcolor=#ffffff>
• <h2> Let's call a method on a null Vector...</h2>
• Vector has <%= vec.size() %> elements.
• </body>
Directives: The Include Directive

• Inserts the contents of another file in the main JSP file,


where the directive is located

• Useful for including copyright information, scripting


language files, or anything you might want to reuse in other
applications

• The included file can be an HTML file, a JSP file, a text


file, or a code file written in the Java programming
language
Notes
• Defines text and code that gets added into the current page at
translation time. The syntax for the directive is:
• <%@ include file="relative url" %>
• The URL specified is normally interpreted relative to the JSP page that
refers to it, but, as with relative URLs in general, you can tell the
system to interpret the URL relative to the home directory of the Web
server by starting the URL with a forward slash. The contents of the
included file are parsed as regular JSP text, and thus can include static
HTML, scripting elements, directives, and actions.
• For example, many sites include a small navigation bar on each page.
Due to problems with HTML frames, this is usually implemented by way
of a small table across the top of the page or down the left-hand side,
with the HTML repeated for each page in the site. The include directive
is a natural way of doing this, saving the developers from the
maintenance nightmare of actually copying the HTML into each
separate file.
Notes
Example on include directive
• include.jsp:
• <html>
• <head><title>An Include Test</title></head>
• <body bgcolor="white">
• <font color="blue">
• The current date and time are
• <%@ include file="date.jsp" %>
• </font>
• </body>
• </html>
• date.jsp:
• <%@ page import="java.util.*" %>
• <%= (new java.util.Date( ) ).toLocaleString( ) %>
• Displays in the page:
• The current date and time are
Actions

• Control the behavior of the servlet engine

• You can dynamically insert a file, reuse JavaBeans


components

• Available actions include:


– jsp:include
– jsp:forward
– jsp:useBean
Notes
Example on include directive
• include.jsp:
• <html>
• <head><title>An Include Test</title></head>
• <body bgcolor="white">
• <font color="blue">
• The current date and time are
• <%@ include file="date.jsp" %>
• </font>
• </body>
• </html>
Notes
Example on include directive
• date.jsp:
• <%@ page import="java.util.*" %>
• <%= (new java.util.Date( ) ).toLocaleString( ) %>
• Displays in the page:
• The current date and time are
• Aug 30, 1999 2:38:40
Actions: The jsp:include Action

• Lets you insert files into the page being generated

• The syntax looks like this:

<jsp:include page="relative URL" />

• Unlike the include directive, which inserts the file at the


time the JSP page is translated into a servlet, this action
inserts the file at the time the page is requested
The include element Example
<%@ page language="java"
contentType="text/html" %>
<html>
<head><title>Include Action
Demo</title></head>

<body bgcolor="white">

<jsp:include page="nav.jsp" />

</body>
<html>
Notes
• Additional Example on include

• <body bgcolor="blue">
• <font color="red">
• <p>Static Include :
• <%@ include file="ex2.jsp" %>
• <p>Dynamic Include :
• </font>
• <jsp:include page="ex3.jsp" flush="true"/>
• </body>
Actions: The jsp:forward Action

• Forwards a client request to an HTML file, JSP file, or


servlet for processing

• Syntax
<jsp:forward page= “relativeURL" />
Notes
• Additional Example on include

• This action lets you forward the request to another page. It


has a single attribute, page, which should consist of a
relative URL. This could be a static value, or could be
computed at request time, as in the two examples below.
• <jsp:forward page="/utils/errorReporter.jsp" />
• <jsp:forward page="<%= someJavaExpression %>" />
The forward element Example
<%
double freeMem = Runtime.getRuntime().freeMemory();
double totlMem = Runtime.getRuntime().totalMemory();
double percent = freeMem/totlMem;
if (percent < 0.5) {
%>
<jsp:forward page="ex2.jsp"/>
<% } else { %>
<jsp:forward page="ex3.jsp"/>
<% } %>
JavaBean
Introduction to Java Beans
• A Java Bean is a reusable software component that works with Java
• Any Java class that follows certain design conventions can be a
JavaBeans component
• It must follow certain conventions about method naming,
construction, and behavior
– Must have a public default constructor
– Properties must be declared private
– Properties must be accessible using get, set, and other methods
(accessor and mutator methods) obeying a standard naming
convention
• JSP technology directly supports using JavaBeans components with
JSP language elements
• You can easily create and initialize beans and get and set the values
of their properties
Notes
• JavaBeans are reusable software components for Java that can
be manipulated visually in a builder tool. Practically, they are
classes written in Java conforming to a particular convention. A
JavaBean is a Java Object that is serializable, has a no-
argument constructor, and allows access to properties using
getter and setter methods. The conventions that Java beans
must follow make it possible to have tools that can use, reuse,
replace, and connect JavaBeans. AWT and Swing, the major
Java GUI toolkits, use JavaBeans conventions for their
components. This allows GUI editors like the Eclipse Visual
Editor or the Netbeans GUI Editor to maintain a hierarchy of
components and to provide access to their properties via
uniformly-named accessors and mutators.
Notes

• Reusable software components are designed to apply the


power and benefit of reusable, interchangeable parts from
other industries to the field of software construction. For
example: Reusable electronic components are found on
circuit boards. Similarly, a typical part in your car can be
replaced by a component made from one of many different
competing manufacturers. The idea is that standard
interfaces allow for interchangeable, reusable components.
For example: In swings, reusable software components can
be simple like familiar push buttons, text fields list boxes,
scrollbars, dialogs.
Identifying the property of a bean
public class A1 {
private int id; What are the properties of this bean?
private String username;
public String getName(){
return username;
}
public void setName(String x){ name
username=x;
}
public void setEmpID(int y){
id=y;
}
empID
public int getEmpID(){
return id;
}
}
Notes

• How did we arrive at the conclusion that name and empID are the
properties of this bean?

• For identifying the property of a bean, you have to group the pair of
mutator(setter) and accessor(getter) methods together.
• For ex : How many pair of setter and getter methods do we have? The
answer is two.
• 1. setName() and getName()
• 2. setEmpID() and getEmpID()
• Take the first pair. Strip off set and get. What remains is Name.
Change the case of first character(remember only first character) to
lower case. What you get is the first property. i.e. name
• When you apply the same rule to the second pair, you get the second
property. i.e. empID
Actions: The jsp:useBean Action

• Lets you load in a JavaBean to be used in the JSP page

• The simplest syntax for specifying that a bean should be


used is:
<jsp:useBean id="name" class="package.class" />

• This usually means "instantiate an object of the class


specified by class, and bind it to a variable with the name
specified by id."
Notes

• This action lets you load in a JavaBean to be used in the


JSP page. This is a very useful capability because it lets you
exploit the reusability of Java classes without sacrificing the
convenience that JSP adds over servlets.
Actions: The jsp:useBean Action (Contd.).

package p1;
public class Example1 {
private int age;
public int getAge(){
}
public void setAge(int i){
}
} If we have to instantiate the given class in java, we will
use the following syntax :
p1.Example1 obj1 = new p1.Example1();
In jsp, the same result is achieved using jsp:useBean :
<jsp:useBean id=“obj1” class =“p1.Example1” />
<jsp:getProperty>
• Converts property names following the bean standards

• Has two attributes:


name="beanInstanceName"
• The name of the Bean instance as declared in a
<jsp:useBean> tag
property="propertyName"
• The name of the Bean property whose value you
want to display
Notes

• This element retrieves the value of a bean property, converts it to


a string, and inserts it into the output. The two required attributes
are name, the name of a bean previously referenced via
jsp:useBean, and property, the property whose value should be
inserted. Here's an example;

• <jsp:useBean id="itemBean" ... />
• ...
• <UL>
• <LI>Number of items:
• <jsp:getProperty name="itemBean" property="numItems"
/>
• <LI>Cost of each:
• <jsp:getProperty name="itemBean" property="unitCost" />
• </UL>
Example on jsp:getProperty
package jspbean;
import java.util.Calendar;
public class TimeBean{
private int hour,minute,second;
public TimeBean(){
Calendar cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
}
public int getHour() { return hour; }
public int getMinute() { return minute; }
public int getSecond() { return second; }
public String getMessage(){
return "Time: "+hour+" "+minute+" "+second;
}
}
Example on jsp:getProperty (Contd.).
<HTML>
<HEAD><TITLE>Time Bean </TITLE></HEAD>
<BODY>
<jsp:useBean id="b2" class="jspbean.TimeBean" />
Hour=<jsp:getProperty name="b2" property=“hour" /> <BR>
Minute=<jsp:getProperty name="b2“property=“minute"/><BR>
Second<jsp:getProperty name="b2" property=“second"/><BR>
Message= <jsp:getProperty name="b2" property=“message"/>
</BODY>
</HTML>
<jsp:setProperty>
• Sets the value of one or more properties in a JavaBean component
Example:
<jsp:useBean id=“person" class=“p1.A1" />
<jsp:setProperty name="person" property="empID"
value="999"/>
<jsp:setProperty name="person" property="empID" value
= "<%= request.getParameter("Employee-Id") %>"/>
<jsp:setProperty name="person" property="name"
param="username" />
<jsp:setProperty name="person" property="empID" />
<jsp:setProperty name="person" property="*" />
Properties of JSP:setProperty
1. name
2. property
3. Value
name: This required attribute designates the bean whose property will be set.
The jsp:useBean element must appear before the jsp:setProperty element.

property: This required attribute indicates the property you want to set.
However, there is one special case: a value of "*" means that all request
parameters whose names match bean property names will be passed to the
appropriate setter methods.
value: This optional attribute specifies the value for the property. String values
are automatically converted to numbers, boolean to Boolean, byte to Byte,
char to Character via the standard valueOf method in the target or wrapper
class. For example, a value of "true" for a boolean or Boolean property will be
converted via Boolean.valueOf, and a value of "42" for an int or Integer property
will be converted via Integer.valueOf.
Notes

• param: This optional attribute designates the request


parameter from which the property should be derived. If the
current request has no such parameter, nothing is done: the
syastem does not pass null to the setter method of the
property. Thus, you can let the bean itself supply default
values, overriding them only when the request parameters
say to do so.
Example on jsp:setProperty
CircleBean.java
package jspbean;
public class CircleBean{
private double radius;
public void setRadius(double r) { radius = r; }
public double getArea() { return
Math.PI*radius*radius; }
}
Circle.jsp
<BODY>
<jsp:useBean id="cb" class="jspbean.CircleBean" />
<jsp:setProperty name="cb" property="radius"
value="2.0" />
Reduced Form: <jsp:getProperty name="cb"
property=“area" />
</BODY>
Notes
• Additional Example on jsp:setProperty
• <html><body>
• <%@ include file = "Header.jsp" %>
• <center> <H3>Parameter Demo</H3>
• <form name="param" method="get" action="parameterBean.jsp">
• <table>
• <tr><td>Enter Numerator</td>
• <td><input type = "text" name = "num" size="3"></td></tr>
• <tr><td>Enter Denominator</td>
• <td><input type = "text" name = "den" size="3"></td></tr>
• <tr><td colspan="2" align="center"> <input type = "submit" ></td> </tr>
• </table>
• </form>
• </center>
• <%@ include file = "Footer.jsp" %>
• </body></html>
Notes
• RationalBean.java
• package suresh;
• public class RationalBean{
• private int num,den;
• private int gcd(int m , int n ){
• return n > 0 ? gcd(n,m%n) : m;
• }
• public RationalBean() { num = 0; den = 1; }
• public void setNum(int s ) { num = s; }
• public void setDen(int s ) { den = s; }
• public String getReduced(){
• int g = gcd(num,den);
• num /= g;
• den /= g;
• return num+"/"+den;
• }
• }
Quiz

1. Identify the implicit objects in JSP


a. request b. response c. out d. session e. application

2. Is JSP page extensible?(TRUE/FALSE)

3. JSP handles runtime errors using __________ attribute in


page directive.

4. How do I use comments within a JSP page?


Summary

In this module, you were able to:


• Describe the Software Component Assembly Model
• Explain Java’s approach to developing software components
• Develop a simple Bean
• Distinguish JSP architecture vis-à-vis servlets
• Define and use the basic JSP Elements
• Create and use Java Beans
References
1. Hans Bergsten (2012). Java Server Pages, Retrieved on April 12, 2012, from,
http://shop.oreilly.com/product/9781565927469.do

2. Stephanie Bodoff (2012). JavaServer Pages Technology. Retrieved on April 12,


2012, from, http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPIntro.html

3. coe.neu.edu (2012). How JSP Works. Retrieved on April 24 , 2012, from,


http://www1.coe.neu.edu/~yozbek/isyg250/jsp.pdf

4. Marty Hall (1999). Java Server Pages (JSP) 1.0. Retrieved April 24, 2012, from,
http://users.polytech.unice.fr/~buffa/cours/internet/POLYS/servlets/Servlet-
Tutorial-JSP.html

5. Apl.jhu.edu (1999). Java Server Pages(JSP) 1.0.Retrieved April 24, 2012, from,
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-JSP.html

6. Paul Wheaton (2012). Java - JSP. Retrieved April 24, 2012, from,
http://www.coderanch.com/t/281980/JSP/java/Hyperlinks
Thank You

Potrebbero piacerti anche