1 processing phase translation phase jsp page translation and processing phases client server...

48
1 Processing phase Translation phase JSP page translation JSP page translation and processing phases and processing phases Client Server Request Response Hello.jsp helloServlet.class helloServlet.java Read Generate Execute

Upload: gregory-clark

Post on 13-Dec-2015

226 views

Category:

Documents


1 download

TRANSCRIPT

11

Processing phase

Translation phase

JSP page translation JSP page translation and processing phasesand processing phases

Client Server

Request

Response

Hello.jsp

helloServlet.class

helloServlet.java

Read

Generate

Execute

22

Template PagesTemplate Pages

Server Page TemplateServer Page Template

<html><html>

<title><title>

A simple exampleA simple example

</title></title>

<body <body color=“#FFFFFF”>color=“#FFFFFF”>

The time now isThe time now is

<%= new java.util.Date() <%= new java.util.Date() %>%>

</body></body>

</html></html>

Resulting HTMLResulting HTML

<html><html>

<title><title>

A simple exampleA simple example

</title></title>

<body color=“#FFFFFF”><body color=“#FFFFFF”>

The time now isThe time now is

Tue Nov 5 16:15:11 PST Tue Nov 5 16:15:11 PST 20022002

</body></body>

</html></html>

translation

33

Dividing Pure ServletsDividing Pure ServletsPublic class MySelect {Public class MySelect {

public void doGet(…){public void doGet(…){

if (isValid(..){if (isValid(..){

saveRecord();saveRecord();

out.println(“<html>”);out.println(“<html>”);

… …..

}}

}}

private void isValid(…){…}private void isValid(…){…}

private void saveRecord(…) private void saveRecord(…) {…}{…}

}}

Servlet

JSP

JavaBeans

Process request

Presentation

Business logic

controller

view

model

Model-View-Controller (MVC) design

44

JSP ComponentsJSP Components

There are three main types of JSP There are three main types of JSP constructs that you embed in a page.constructs that you embed in a page.– Scripting elementsScripting elements

You can specify Java codeYou can specify Java code Expressions, Scriptlets, DeclarationsExpressions, Scriptlets, Declarations

– DirectivesDirectives Let you control the overall structure of the servletLet you control the overall structure of the servlet Page, include, Tag libraryPage, include, Tag library

– ActionsActions Enable the use of server side JavabeansEnable the use of server side Javabeans Transfer control between pagesTransfer control between pages

55

Types of Scripting Types of Scripting ElementsElements You can insert code into the servlet that You can insert code into the servlet that

will be generated from the JSP page.will be generated from the JSP page. Expressions:Expressions: <%= expression %><%= expression %>

– Evaluated and inserted into the servletEvaluated and inserted into the servlet ’’s output. s output. i.e., results in something like i.e., results in something like out.println(expression)out.println(expression)

Scriptlets:Scriptlets: <% code %><% code %>– Inserted verbatim into the servletInserted verbatim into the servlet ’’s _jspService s _jspService

method (called by service)method (called by service) Declarations:Declarations: <%! code %><%! code %>

– Inserted verbatim into the body of the servlet Inserted verbatim into the body of the servlet class, outside of any existing methodsclass, outside of any existing methods

66

JSP ExpressionsJSP Expressions

FormatFormat– <%=<%= Java Expression Java Expression %>%>

ResultResult– Expression evaluated, converted to String, and placed Expression evaluated, converted to String, and placed

into HTML page at the place it occurred in JSP pageinto HTML page at the place it occurred in JSP page– That is, expression placed in _jspService inside out.printThat is, expression placed in _jspService inside out.print

ExamplesExamples– Current time: <%= new java.util.Date() %>Current time: <%= new java.util.Date() %>– Your hostname: <%= request.getRemoteHost() %>Your hostname: <%= request.getRemoteHost() %>

XML-compatible syntaxXML-compatible syntax– <jsp:expression><jsp:expression>Java ExpressionJava Expression</jsp:expression></jsp:expression>– XML version not supported by Tomcat 3. Until JSP 1.2, XML version not supported by Tomcat 3. Until JSP 1.2,

servers are not required to support it.servers are not required to support it.

77

JSP/Servlet JSP/Servlet CorrespondenceCorrespondence Original JSPOriginal JSP

<H1>A Random Number</H1><H1>A Random Number</H1><%= Math.random() %><%= Math.random() %>

Possible resulting servlet codePossible resulting servlet code public void _jspService(HttpServletRequest request,public void _jspService(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { request.setContentType("text/html");request.setContentType("text/html"); HttpSession session = request.getSession(true);HttpSession session = request.getSession(true); JspWriter out = response.getWriter();JspWriter out = response.getWriter(); out.println("<H1>A Random Number</H1>");out.println("<H1>A Random Number</H1>"); out.println(Math.random());out.println(Math.random()); ...... }}

88

Example Using JSP Example Using JSP ExpressionsExpressions

<BODY><BODY><H2>JSP Expressions</H2><H2>JSP Expressions</H2><UL><UL> <LI>Current time: <LI>Current time: <%= new java.util.Date() %><%= new java.util.Date() %> <LI>Your hostname: <LI>Your hostname: <%= request.getRemoteHost() %><%= request.getRemoteHost() %> <LI>Your session ID: <LI>Your session ID: <%= session.getId() %><%= session.getId() %> <LI>The <CODE>testParam</CODE> form parameter:<LI>The <CODE>testParam</CODE> form parameter: <%= request.getParameter("testParam") %><%= request.getParameter("testParam") %></UL></UL></BODY></BODY>

99

Predefined VariablesPredefined Variables(Implicit Objects)(Implicit Objects) They are created automatically when a They are created automatically when a

web server processes a JSP page.web server processes a JSP page. requestrequest: The HttpServletRequest (1st arg to doGet): The HttpServletRequest (1st arg to doGet) responseresponse: The HttpServletResponse (2nd arg to doGet): The HttpServletResponse (2nd arg to doGet) sessionsession

– The HttpSession associated with the request (unless The HttpSession associated with the request (unless disabled with the session attribute of the page directive)disabled with the session attribute of the page directive)

outout– The stream (of type JspWriter) used to send output to the The stream (of type JspWriter) used to send output to the

clientclient applicationapplication

– The ServletContext (for sharing data) as obtained via The ServletContext (for sharing data) as obtained via getServletConfig().getContext().getServletConfig().getContext().

page, pageContext, config, exceptionpage, pageContext, config, exception

1010

Implicit objects Implicit objects –– Class Class filesfiles applicationapplication: javax.servlet.ServletContext: javax.servlet.ServletContext configconfig: javax.servlet.ServletConfig: javax.servlet.ServletConfig exceptionexception: java.lang.Throwable: java.lang.Throwable outout: javax.servlet.jsp.JspWriter: javax.servlet.jsp.JspWriter pagepage: java.lang.Object: java.lang.Object pageContextpageContext: :

javax.servlet.jsp.PageContextjavax.servlet.jsp.PageContext requestrequest: javax.servlet.ServletRequest: javax.servlet.ServletRequest responseresponse: javax.servlet.ServletResponse: javax.servlet.ServletResponse sessionsession: javax.servlet.http.HttpSession: javax.servlet.http.HttpSession

1111

Access Client Access Client InformationInformation The getRemoteHost method of the The getRemoteHost method of the

request object allows a JSP to retrieve request object allows a JSP to retrieve the name of a client computer.the name of a client computer.

<<htmlhtml><><headhead>><<titletitle>>Your InformationYour Information</</titletitle>></</headhead><><bodybody>>Your computer's IP address is Your computer's IP address is <<bb>><%= request.getRemoteAddr() %><%= request.getRemoteAddr() %></</bb>><<brbr>>Your computer's name is Your computer's name is <<bb>><%= request.getRemoteHost() %><%= request.getRemoteHost() %></</bb>><<brbr>>Your computer is accessing port number Your computer is accessing port number <<bb>><%= request.getServerPort() %><%= request.getServerPort() %></</bb>></</bodybody></></htmlhtml>>

1212

Work with the BufferWork with the Buffer

When the page is being processed, the When the page is being processed, the data is stored in the buffer instead of data is stored in the buffer instead of being directly sent to the client browser.being directly sent to the client browser.

<<htmlhtml>>This is a test of the bufferThis is a test of the buffer<<brbr/>/><%<%out.flush();out.flush();for (int x=0; x < 100000000; x++);for (int x=0; x < 100000000; x++);out.print("This test is generated about 5 out.print("This test is generated about 5

seconds later.");seconds later.");out.flush();out.flush();%>%></</htmlhtml>>

1313

Working with Session Working with Session objectobject The session object has many useful The session object has many useful

methods that can alter or obtain methods that can alter or obtain information about the current session.information about the current session.– setMaxInactiveInterval(second)setMaxInactiveInterval(second)

<<htmlhtml><><headhead>><<titletitle>>Session ValuesSession Values</</titletitle>></</headhead><><bodybody>><%<%session.setMaxInactiveInterval(10);session.setMaxInactiveInterval(10);String name = (String) String name = (String)

session.getAttribute("username");session.getAttribute("username");out.print("Welcome to my site " + name + out.print("Welcome to my site " + name +

"<br>");"<br>");%>%></</bodybody></></htmlhtml>>

1414

JSP ScriptletsJSP Scriptlets

Format: Format: <%<% Java Code Java Code %>%> ResultResult

– Code is inserted verbatim into servlet's Code is inserted verbatim into servlet's _jspService_jspService

ExampleExample– <% <%

String queryData = request.getQueryString();String queryData = request.getQueryString();out.println("Attached GET data: " + queryData); out.println("Attached GET data: " + queryData); %>%>

– <% response.setContentType("text/plain"); %><% response.setContentType("text/plain"); %> XML-compatible syntaxXML-compatible syntax

– <jsp:scriptlet><jsp:scriptlet>Java CodeJava Code</jsp:scriptlet></jsp:scriptlet>

1515

JSP/Servlet JSP/Servlet CorrespondenceCorrespondence Original JSPOriginal JSP

<%= foo() %><%= foo() %><% bar(); %><% bar(); %>

Possible resulting servlet codePossible resulting servlet code public void _jspService(HttpServletRequest request,public void _jspService(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { request.setContentType("text/html");request.setContentType("text/html"); HttpSession session = request.getSession(true);HttpSession session = request.getSession(true); JspWriter out = response.getWriter();JspWriter out = response.getWriter(); out.println(foo());out.println(foo()); bar();bar(); ...... }}

1616

JSP JSP Scriptlets Scriptlets ExampleExample

<%<%for (int i=100; i>=0; i--) for (int i=100; i>=0; i--) { { %>%> <%= i %> bottles of beer on the <%= i %> bottles of beer on the

wall.wall.<<brbr>><%<%}}%>%>

1717

Example Using JSP Example Using JSP ScriptletsScriptlets

<HTML><HTML><HEAD><HEAD> <TITLE>Color Testing</TITLE><TITLE>Color Testing</TITLE></HEAD></HEAD><%<%String bgColor = String bgColor =

request.getParameter("bgColorrequest.getParameter("bgColor");");

boolean hasExplicitColor;boolean hasExplicitColor;if (bgColor != null) {if (bgColor != null) { hasExplicitColor = true;hasExplicitColor = true;} else {} else { hasExplicitColor = false;hasExplicitColor = false; bgColor = "WHITE";bgColor = "WHITE";}}%>%><BODY BGCOLOR=<BODY BGCOLOR="<%= bgColor "<%= bgColor

%>"%>">>

1818

JSP DeclarationsJSP Declarations

FormatFormat– <%!<%! Java Code Java Code %>%>

ResultResult– Code is inserted verbatim into servlet's class Code is inserted verbatim into servlet's class

definition, outside of any existing methodsdefinition, outside of any existing methods ExamplesExamples

– <%! private int someField = 5; %><%! private int someField = 5; %>– <%! private void someMethod(...) {...} %><%! private void someMethod(...) {...} %>

XML-compatible syntaxXML-compatible syntax– <jsp:declaration><jsp:declaration>Java Java

CodeCode</jsp:declaration></jsp:declaration>

1919

Original JSPOriginal JSP<H1>Some Heading</H1><H1>Some Heading</H1><%! <%! private String randomHeading() {private String randomHeading() { return("<H2>" + Math.random() + "</H2>");return("<H2>" + Math.random() + "</H2>"); }}%>%><%= randomHeading() %><%= randomHeading() %>

Possible resulting servlet codePossible resulting servlet code

public class xxxx implements HttpJspPage {public class xxxx implements HttpJspPage { private String randomHeading() {private String randomHeading() { return("<H2>" + Math.random() + "</H2>");return("<H2>" + Math.random() + "</H2>"); }} public void _jspService(HttpServletRequest request,public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, HttpServletResponse response) throws ServletException,

IOException {IOException { request.setContentType("text/html");request.setContentType("text/html"); HttpSession session = request.getSession(true);HttpSession session = request.getSession(true); JspWriter out = response.getWriter();JspWriter out = response.getWriter(); out.println("<H1>Some Heading</H1>");out.println("<H1>Some Heading</H1>"); out.println(randomHeading());out.println(randomHeading()); ...... }}

JSP/Servlet JSP/Servlet CorrespondenceCorrespondence

2020

Example Using JSP Example Using JSP DeclarationsDeclarations

……<body><body><h1>JSP Declarations</h1><h1>JSP Declarations</h1><%! private int accessCount = 0; %><%! private int accessCount = 0; %><h2>Accesses to page since server reboot: <h2>Accesses to page since server reboot: <%= ++accessCount %><%= ++accessCount %></h2></h2></body></html></body></html>

After 15 total After 15 total visits by an visits by an arbitrary arbitrary number of number of different clientsdifferent clients

2121

JSP Tags + HTML TagsJSP Tags + HTML Tags<<h2h2>>Table of Square RootsTable of Square Roots</</h2h2>><<tabletable border border==22>> <<trtr>> <<tdtd><><bb>>NumberNumber</</bb></></tdtd>> <<tdtd><><bb>>Square RootSquare Root</</bb></></tdtd>> </</trtr>> <%<% for (int n=0; n<=100; n++) for (int n=0; n<=100; n++) { { %>%> <<trtr>> <<tdtd>><%=n%><%=n%></</tdtd>> <<tdtd>><%=Math.sqrt(n)%><%=Math.sqrt(n)%></</tdtd>> </</trtr>> <% <% } } %>%></</tabletable>>

2222

JSP DirectivesJSP Directives

Affect the overall structure of the Affect the overall structure of the servletservlet

Two possible forms for directivesTwo possible forms for directives– <%@ directive attribute=<%@ directive attribute=““valuevalue”” %> %>– <%@ directive attribute1=<%@ directive attribute1=““value1value1”” attribute2=attribute2=““value2value2”” …….. attributeN=attributeN=““valueNvalueN”” %> %>

There are three types of directivesThere are three types of directives– PagePage, , includeinclude, and , and taglibtaglib

2323

Purpose of the page Purpose of the page DirectiveDirective Give high-level information about the Give high-level information about the

servlet that will result from the JSP pageservlet that will result from the JSP page Can controlCan control

– Which classes are importedWhich classes are imported– What class the servlet extendsWhat class the servlet extends– What MIME type is generatedWhat MIME type is generated– How multithreading is handledHow multithreading is handled– If the servlet participates in sessionsIf the servlet participates in sessions– The size and behavior of the output bufferThe size and behavior of the output buffer– What page handles unexpected errorsWhat page handles unexpected errors

2424

The import AttributeThe import Attribute

FormatFormat– <%@ page import="package.class" %><%@ page import="package.class" %>– <%@ page <%@ page

import="package.class1,...,package.classN" import="package.class1,...,package.classN" %>%>

PurposePurpose– Generate import statements at top of servletGenerate import statements at top of servlet

NotesNotes– Although JSP pages can be almost anywhere on server, Although JSP pages can be almost anywhere on server,

classes used by JSP pages must be in normal servlet classes used by JSP pages must be in normal servlet dirsdirs

2525

......<BODY><H2>The import Attribute</H2><BODY><H2>The import Attribute</H2><%-- JSP page directive --%><%-- JSP page directive --%><%@ page import="java.util.*,cwp.*" %><%@ page import="java.util.*,cwp.*" %>

<%-- JSP Declaration --%><%-- JSP Declaration --%><%!<%!private String randomID() {private String randomID() { int num = (int)(Math.random()*10000000.0);int num = (int)(Math.random()*10000000.0); return("id" + num);return("id" + num);}}private final String NO_VALUE = "<I>No Value</I>";private final String NO_VALUE = "<I>No Value</I>";%>%><%<%Cookie[] cookies = request.getCookies();Cookie[] cookies = request.getCookies();String oldID = String oldID = ServletUtilitiesServletUtilities.getCookieValue(cookies, "userID", .getCookieValue(cookies, "userID",

NO_VALUE);NO_VALUE);String newID;String newID;if (oldID.equals(NO_VALUE)) { newID = randomID();if (oldID.equals(NO_VALUE)) { newID = randomID();} else { newID = oldID; }} else { newID = oldID; }LongLivedCookie cookie = new LongLivedCookie("userID", newID);LongLivedCookie cookie = new LongLivedCookie("userID", newID);response.addCookie(cookie);response.addCookie(cookie);%>%><%-- JSP Expressions --%><%-- JSP Expressions --%>This page was accessed at <%= This page was accessed at <%= new Date()new Date() %> with a userID %> with a userIDcookie of <%= oldID %>.cookie of <%= oldID %>. </BODY></HTML></BODY></HTML>

Example of Example of import import AttributeAttribute

2626

Example of import Example of import AttributeAttribute

First accessFirst access

SubsequentSubsequentaccessesaccesses

2727

The contentType The contentType AttributeAttribute FormatFormat

– <%@ page contentType="MIME-Type" <%@ page contentType="MIME-Type" %>%>

– <%@ page contentType="MIME-Type;<%@ page contentType="MIME-Type; charset=Character-Set"%> charset=Character-Set"%>

PurposePurpose– Specify the MIME type of the page Specify the MIME type of the page

generated by the servlet that results generated by the servlet that results from the JSP pagefrom the JSP page

2828

First Last Email AddressFirst Last Email Address

Marty Hall [email protected] Hall [email protected]

Larry Brown [email protected] Brown [email protected]

Bill Gates [email protected] Gates [email protected]

Larry Ellison [email protected] Ellison [email protected]

<%@ page contentType="application/vnd.ms-excel" %><%@ page contentType="application/vnd.ms-excel" %>

<%-- There are tabs, not spaces, between columns. --%><%-- There are tabs, not spaces, between columns. --%>

Generating Generating Excel Excel SpreadsheetSpreadsheetss

2929

<%-- processOrder.jsp --%><%-- processOrder.jsp --%><%@ page errorPage="orderError.jsp" <%@ page errorPage="orderError.jsp" import="java.text.NumberFormat" %>import="java.text.NumberFormat" %><<h3h3>>Your order:Your order:</</h3h3>><% <% String numTees = request.getParameter("t-shirts");String numTees = request.getParameter("t-shirts"); String numHats = request.getParameter("hats");String numHats = request.getParameter("hats"); NumberFormat currency = NumberFormat currency =

NumberFormat.getCurrencyInstance();NumberFormat.getCurrencyInstance();%>%>Number of tees: Number of tees: <%= numTees %><%= numTees %><<brbr>>Your price: Your price: <%= <%=

currency.format(Integer.parseInt(numTees)*15.00) currency.format(Integer.parseInt(numTees)*15.00) %>%><<pp>>

Number of hats: Number of hats: <%= numHats %><%= numHats %><<brbr>>Your price: Your price: <%= <%=

currency.format(Integer.parseInt(numHats)*10.00) currency.format(Integer.parseInt(numHats)*10.00) %>%><<pp>>

<!--<!-- orderForm.htm orderForm.htm -->--><<h1h1>>Order FormOrder Form</</h1h1>>What would you like to purchase?What would you like to purchase?<<pp>><<formform name name==orders actionorders action==processOrder.jspprocessOrder.jsp>><<tabletable border border==00>> <<trtr><><thth>>ItemItem</</thth>> <<thth>>QuantityQuantity</</thth>> <<thth>>Unit PriceUnit Price</</thth>> <<trtr><><trtr>>……

Form Form ProcessinProcessingg

3030

JSP ActionsJSP Actions

There are There are sevenseven standard JSP actions. standard JSP actions.– Include, param, forward, plugin, Include, param, forward, plugin, ……– Include action is similar to include Include action is similar to include

directive.directive.– You can add additional parameters to the You can add additional parameters to the

existing request by using the param action.existing request by using the param action.– The plugin action inserts object and embed The plugin action inserts object and embed

tags (such as an applet) into the response tags (such as an applet) into the response to the client.to the client.

– In the coming slides, we will talk about In the coming slides, we will talk about ““includeinclude”” and and ““pluginplugin”” actions. actions.

3131

Including Pages at Including Pages at Request TimeRequest Time FormatFormat

– <jsp:include page="Relative URL" <jsp:include page="Relative URL" flush="true" flush="true" //>>

PurposePurpose– To reuse JSP, HTML, or plain text contentTo reuse JSP, HTML, or plain text content– JSP content cannot affect main page: JSP content cannot affect main page:

only output of included JSP page is usedonly output of included JSP page is used– To permit updates to the included To permit updates to the included

content without changing the main JSP content without changing the main JSP page(s)page(s)

3232

Including Pages: Example Including Pages: Example CodeCode

......<BODY><BODY><TABLE BORDER=5 ALIGN="CENTER"><TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"><TR><TH CLASS="TITLE"> What's New at JspNews.com</TABLE>What's New at JspNews.com</TABLE><P><P>Here is a summary of our three most recent news stories:Here is a summary of our three most recent news stories:<OL><OL> <LI><LI><jsp:include page="news/Item1.html" flush="true" /><jsp:include page="news/Item1.html" flush="true" /> <LI><LI><jsp:include page="news/Item2.html" flush="true" /><jsp:include page="news/Item2.html" flush="true" /> <LI><LI><jsp:include page="news/Item3.html" flush="true" /><jsp:include page="news/Item3.html" flush="true" /></OL></OL></BODY></HTML></BODY></HTML>

3333

Background: What Are Background: What Are Beans?Beans?

Classes that follow certain conventionsClasses that follow certain conventions– Must have a zero-argument (empty) constructorMust have a zero-argument (empty) constructor– Should have no public instance variables (fields)Should have no public instance variables (fields)– Persistent values should be accessed through Persistent values should be accessed through

methods called getXxx and setXxxmethods called getXxx and setXxx If class has method getTitle that returns a String, class If class has method getTitle that returns a String, class

is said to have a String property named titleis said to have a String property named title Boolean properties use isXxx instead of getXxxBoolean properties use isXxx instead of getXxx

For more on beans, see For more on beans, see http://java.sun.com/beans/docs/http://java.sun.com/beans/docs/

3434

Basic Bean Use in JSPBasic Bean Use in JSP

Format: Format: <jsp:useBean id="name" <jsp:useBean id="name"

class="package.Class" />class="package.Class" /> Purpose: Purpose: Allow instantiation of classes Allow instantiation of classes

without explicit Java syntaxwithout explicit Java syntax NotesNotes

– Simple interpretation: JSP actionSimple interpretation: JSP action<jsp:useBean id="book1" class="cwp.Book" /><jsp:useBean id="book1" class="cwp.Book" />

can be thought of as equivalent to the scriptletcan be thought of as equivalent to the scriptlet<% cwp.Book book1 = new cwp.Book(); %><% cwp.Book book1 = new cwp.Book(); %>

– But useBean has two additional featuresBut useBean has two additional features Simplifies setting fields based on incoming request Simplifies setting fields based on incoming request

paramsparams Makes it easier to share beansMakes it easier to share beans

3535

Accessing Bean Accessing Bean PropertiesProperties Format: Format: <jsp:getProperty <jsp:getProperty

name="name" name="name" property="property" />property="property" />

Purpose: Purpose: Allow access to bean Allow access to bean properties (i.e., calls to getXxx properties (i.e., calls to getXxx methods) without explicit Java codemethods) without explicit Java code

NotesNotes– <jsp:getProperty name="book1" property="title" /><jsp:getProperty name="book1" property="title" />

is equivalent to the following JSP is equivalent to the following JSP expressionexpression<%= book1.getTitle() %><%= book1.getTitle() %>

3636

Setting Bean Setting Bean Properties: Properties: Simple CaseSimple Case Format: Format: <jsp:setProperty <jsp:setProperty

name="name" name="name" property="property" value="value" /> property="property" value="value" />

PurposePurpose– Allow setting of bean properties (i.e., calls Allow setting of bean properties (i.e., calls

to setXxx) without explicit Java codeto setXxx) without explicit Java code NotesNotes

– <jsp:setProperty name="book1" <jsp:setProperty name="book1" property="title" property="title" value="Core Servlets and JSP" /> value="Core Servlets and JSP" />

is equivalent to the following scriptletis equivalent to the following scriptlet<% book1.setTitle("Core Servlets and JSP"); %><% book1.setTitle("Core Servlets and JSP"); %>

3737

Example: StringBeanExample: StringBean

publicpublic class StringBean { class StringBean { private String message = "No message private String message = "No message

specified";specified"; publicpublic String getMessage() { String getMessage() { return(message);return(message); }} publicpublic void setMessage(String message) { void setMessage(String message) { this.message = message;this.message = message; }}}}

Installed in normal servlet directoryInstalled in normal servlet directory

3838

<jsp:useBean id="stringBean" class="cwp.StringBean" /><jsp:useBean id="stringBean" class="cwp.StringBean" /><OL><OL><LI>Initial value (getProperty):<LI>Initial value (getProperty): <I><I><jsp:getProperty name="stringBean" <jsp:getProperty name="stringBean" property="message" />property="message" /></I></I><LI>Initial value (JSP expression):<LI>Initial value (JSP expression): <I><I><%= stringBean.getMessage() %><%= stringBean.getMessage() %></I></I><LI><LI><jsp:setProperty name="stringBean" <jsp:setProperty name="stringBean" property="message" property="message" value="Best string bean: Fortex" />value="Best string bean: Fortex" /> Value after setting property with setProperty:Value after setting property with setProperty: <I><I><jsp:getProperty name="stringBean" <jsp:getProperty name="stringBean" property="message" />property="message" /></I></I><LI><LI><% stringBean.setMessage("My favorite: Kentucky Wonder"); <% stringBean.setMessage("My favorite: Kentucky Wonder");

%>%> Value after setting property with scriptlet:Value after setting property with scriptlet: <I><I><%= stringBean.getMessage() %><%= stringBean.getMessage() %></I></I></OL></OL>

JSP Page JSP Page That Uses That Uses StringBeaStringBeann

3939

JSP Page That Uses JSP Page That Uses StringBeanStringBean

4040

Associating Bean Properties Associating Bean Properties with Request (Form) with Request (Form) ParametersParameters If property is a String, you can doIf property is a String, you can do

– <jsp:setProperty ... value=<jsp:setProperty ... value='<%= request.getParameter("...") '<%= request.getParameter("...") %>'%>' /> />

Scripting expressions let you convert types, but Scripting expressions let you convert types, but you have to use Java syntaxyou have to use Java syntax

The The paramparam attribute indicates that: attribute indicates that:– Value should come from specified request paramValue should come from specified request param– Simple automatic type conversion performedSimple automatic type conversion performed

Using "Using "**" for the property attribute indicates that:" for the property attribute indicates that:– Value should come from request parameter whose Value should come from request parameter whose

name matches property namename matches property name– Simple type conversion should be performedSimple type conversion should be performed

4141

Setting Bean Properties Setting Bean Properties Case 1:Case 1:Explicit Conversion & Explicit Conversion & AssignmentAssignment

<!DOCTYPE ...><!DOCTYPE ...>......<jsp:useBean id="entry" <jsp:useBean id="entry"

class="cwp.SaleEntry" /> class="cwp.SaleEntry" />

<%-- getItemID expects a String --%><%-- getItemID expects a String --%><jsp:setProperty <jsp:setProperty name="entry" name="entry" property="itemID"property="itemID" value='<%= request.getParameter("itemID") value='<%= request.getParameter("itemID")

%>'%>' /> />

4242

Setting Bean Properties Setting Bean Properties Case 1:Case 1:Explicit Conversion & Explicit Conversion & AssignmentAssignment<%<%

int numItemsOrdered = 1;int numItemsOrdered = 1;try {try { numItemsOrdered =numItemsOrdered = Integer.parseInt(request.getParameter("numItems"));Integer.parseInt(request.getParameter("numItems"));} catch(NumberFormatException nfe) {}} catch(NumberFormatException nfe) {}%>%><%-- getNumItems expects an int --%><%-- getNumItems expects an int --%><jsp:setProperty <jsp:setProperty name="entry" name="entry" property="numItems"property="numItems" value="<%= numItemsOrdered %>"value="<%= numItemsOrdered %>" /> />

4343

Setting Bean Properties Setting Bean Properties Case 1:Case 1:Explicit Conversion & Explicit Conversion & AssignmentAssignment

<% <% double discountCode = 1.0;double discountCode = 1.0;try {try { String discountString = String discountString = request.getParameter("discountCode");request.getParameter("discountCode"); discountCode = discountCode = Double.valueOf(discountString).doubleValue();Double.valueOf(discountString).doubleValue();} catch(NumberFormatException nfe) {}} catch(NumberFormatException nfe) {}%>%><%-- getDiscountCode expects a double --%><%-- getDiscountCode expects a double --%><jsp:setProperty <jsp:setProperty name="entry" name="entry" property="discountCode"property="discountCode" value="<%= discountCode %>"value="<%= discountCode %>" /> />

4444

Case 2: Associating Individual Case 2: Associating Individual Properties with Input Properties with Input ParametersParameters<jsp:useBean id="entry" <jsp:useBean id="entry"

class="cwp.SaleEntry" />class="cwp.SaleEntry" /><jsp:setProperty <jsp:setProperty name="entry"name="entry" property="itemID"property="itemID" param="itemID"param="itemID" /> /><jsp:setProperty <jsp:setProperty name="entry"name="entry" property="numItems"property="numItems" param="numItems"param="numItems" /> /><jsp:setProperty <jsp:setProperty name="entry"name="entry" property="discountCode"property="discountCode" param="discountCode"param="discountCode" /> />

4545

Case 3: Associating Case 3: Associating AllAll Properties with Input Properties with Input ParametersParameters

<jsp:useBean id="entry" <jsp:useBean id="entry" class="cwp.SaleEntry" />class="cwp.SaleEntry" /><jsp:setProperty name="entry" <jsp:setProperty name="entry" property="*"property="*" /> />

4646

Sharing BeansSharing Beans

You can use scope attribute to specify You can use scope attribute to specify where bean is storedwhere bean is stored– <jsp:useBean id="<jsp:useBean id="……" class="" class="……" "

scope="scope="……"" /> />– Bean still also bound to local variable in Bean still also bound to local variable in

_jspService _jspService Lets multiple servlets or JSP pages share Lets multiple servlets or JSP pages share

datadata Also permits conditional bean creationAlso permits conditional bean creation

– Create new object only if you can't find Create new object only if you can't find existing oneexisting one

4747

Values of the scope Values of the scope AttributeAttribute pagepage

– Default value. Bean object should be placed Default value. Bean object should be placed in the PageContext object for the duration of in the PageContext object for the duration of the current request. Lets methods in same the current request. Lets methods in same servlet access beanservlet access bean

applicationapplication– Bean will be stored in ServletContext Bean will be stored in ServletContext

(available through the application variable or (available through the application variable or by call to getServletContext()). ServletContext by call to getServletContext()). ServletContext is shared by all servlets in the same Web is shared by all servlets in the same Web application (or all servlets on server if no application (or all servlets on server if no explicit Web applications are defined).explicit Web applications are defined).

4848

Values of the scope Values of the scope AttributeAttribute sessionsession

– Bean will be stored in the HttpSession object Bean will be stored in the HttpSession object associated with the current request, where it associated with the current request, where it can be accessed from regular servlet code can be accessed from regular servlet code with getAttribute and setAttribute, as with with getAttribute and setAttribute, as with normal session objects.normal session objects.

requestrequest– Bean object should be placed in the Bean object should be placed in the

ServletRequest object for the duration of the ServletRequest object for the duration of the current request, where it is available by current request, where it is available by means of getAttributemeans of getAttribute