117
Web Application: Web Application: Java Server Pages (JSP) Java Server Pages (JSP) INE2720 INE2720 Web Application Software Web Application Software Development Development Essential Materials Essential Materials

Web Application: Java Server Pages (JSP) INE2720 Web Application Software Development Essential Materials

Embed Size (px)

Citation preview

Web Application:Web Application:Java Server Pages (JSP)Java Server Pages (JSP)

INE2720INE2720

Web Application Software Web Application Software DevelopmentDevelopment

Essential MaterialsEssential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

22

OutlineOutline

Introducing JavaServer PagesIntroducing JavaServer PagesTMTM (JSP (JSPTMTM)) JSP scripting elementsJSP scripting elements

– Expressions, Scriptlets and declarationsExpressions, Scriptlets and declarations

The JSP page Directive:The JSP page Directive: – Structuring Generated ServletsStructuring Generated ServletsTMTM

Including Files in JSP DocumentsIncluding Files in JSP Documents Using JavaBeans™ components with JSPUsing JavaBeans™ components with JSP Creating custom JSP tag librariesCreating custom JSP tag libraries Integrating servlets and JSP with the MVC Integrating servlets and JSP with the MVC

architecturearchitecture

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

33

The JSP FrameworkThe JSP Framework

Idea:Idea: – Use regular HTML for most of pageUse regular HTML for most of page– Mark servlet code with special tagsMark servlet code with special tags– Entire JSP page gets translated into a servlet (once), Entire JSP page gets translated into a servlet (once),

and servlet is what actually gets invoked (for each and servlet is what actually gets invoked (for each request)request)

Example: Example: – JSP JSP

Thanks for ordering Thanks for ordering <I><%= request.getParameter("title") %></I><I><%= request.getParameter("title") %></I>

– URL URL http://host/OrderConfirmation.jsp?title=Core+Web+Programminghttp://host/OrderConfirmation.jsp?title=Core+Web+Programming

– ResultResult Thanks for ordering Core Web ProgrammingThanks for ordering Core Web Programming

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

44

Setting Up Your Setting Up Your EnvironmentEnvironment

Set your CLASSPATH. Set your CLASSPATH.

Compile your code. Compile your code.

Use packages to avoid name conflicts. Use packages to avoid name conflicts.

Put JSP page in special directory. Put JSP page in special directory. tomcat_install_dir/webapps/ROOTtomcat_install_dir/webapps/ROOT

Use special URL to invoke JSP page. Use special URL to invoke JSP page. CaveatsCaveats

– Previous rules about CLASSPATH, install dirs, Previous rules about CLASSPATH, install dirs, etc., still apply to regular classes used by JSPetc., still apply to regular classes used by JSP

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

55

<HTML><HEAD><HTML><HEAD><TITLE>JSP Expressions</TITLE><TITLE>JSP Expressions</TITLE><META NAME="author" CONTENT="Marty Hall"><META NAME="author" CONTENT="Marty Hall"><META NAME="keywords" <META NAME="keywords"

CONTENT="JSP,expressions,JavaServer,Pages,servlets"CONTENT="JSP,expressions,JavaServer,Pages,servlets">>

<META NAME="description"<META NAME="description" CONTENT="A quick example of JSP expressions.">CONTENT="A quick example of JSP expressions."><LINK REL=STYLESHEET HREF="JSP-Styles.css" <LINK REL=STYLESHEET HREF="JSP-Styles.css"

TYPE="text/css">TYPE="text/css"></HEAD></HEAD><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></BODY></HTML></UL></BODY></HTML>

ExamplExamplee

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

66

Example ResultExample Result

With default setup, if location wasWith default setup, if location was– C:\<tomcatHome>\webapps\ROOT\C:\<tomcatHome>\webapps\ROOT\

Expressions.jspExpressions.jsp URL would beURL would be

– http://localhost/Expressions.jsphttp://localhost/Expressions.jsp

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

77

How JSP works?How JSP works?

1. Web browser send JSP request2. JSP request send via Internet to the web server3. The web server send the JSP file (template pages) to JSP servlet engine4. Parse JSP file5. Generate servlet source code6. Compile servlet to class7. Instantiate servlet

8. HTML send back to the browser

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

88Processing 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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

99

JSP Life-cycleJSP Life-cycle

.jsp file newer thanPreviously compiled

Servlet?

Translate and(re-compile)Servlet code

Execute theCompiled Servlet

No

Yes

Request forJSP page

Responsean HTML

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1010

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1111

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1212

Most Common Most Common Misunderstanding:Misunderstanding:Forgetting JSP is Server-Side Forgetting JSP is Server-Side TechnologyTechnology Very common questionVery common question

– I can’t do such and such with HTML. I can’t do such and such with HTML. Will JSP let me do it?Will JSP let me do it?

Similar questionsSimilar questions– How do I put an applet in a JSP page?How do I put an applet in a JSP page?

Answer: send an <APPLET…> tag to the clientAnswer: send an <APPLET…> tag to the client– How do I put an image in a JSP page?How do I put an image in a JSP page?

Answer: send an <IMG …> tag to the clientAnswer: send an <IMG …> tag to the client– How do I use How do I use

JavaScript/Acrobat/Shockwave/Etc?JavaScript/Acrobat/Shockwave/Etc?Answer: send the appropriate HTML tagsAnswer: send the appropriate HTML tags

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1313

2nd Most Common 2nd Most Common Misunderstanding:Misunderstanding:Translation/Request Time Translation/Request Time ConfusionConfusion What happens at page translation time?What happens at page translation time?

– JSP constructs get translated into servlet codeJSP constructs get translated into servlet code What happens at request time?What happens at request time?

– Servlet code gets executed. No interpretation of Servlet code gets executed. No interpretation of JSP occurs at request time. The original JSP page JSP occurs at request time. The original JSP page is ignored at request time; only the servlet that is ignored at request time; only the servlet that resulted from it is usedresulted from it is used

When does page translation occur?When does page translation occur?– Typically, the first time JSP page is accessed after Typically, the first time JSP page is accessed after

it is modified. This should never happen to real it is modified. This should never happen to real user (developers should test all JSP pages they user (developers should test all JSP pages they install). install).

– Page translation does not occur for each requestPage translation does not occur for each request

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1414

JSP/Servlets in the JSP/Servlets in the Real WorldReal World Delta Airlines: entire Web site, including real-time schedule infoDelta Airlines: entire Web site, including real-time schedule info First USA Bank: largest credit card issuer in the world; most on-First USA Bank: largest credit card issuer in the world; most on-

line banking customersline banking customers

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1515

JSP/Servlets in the JSP/Servlets in the Real WorldReal World Excite: one of the top five Internet Excite: one of the top five Internet

portals; one of the ten busiest sites on portals; one of the ten busiest sites on the Webthe Web

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1616

Hidden / HTML Hidden / HTML CommentComment An HTML comment is sent to the An HTML comment is sent to the

client’s browser, but is not displayed. client’s browser, but is not displayed. The information can be reviewed from The information can be reviewed from the source code.the source code.– <!-- comment [<%= expression%>] --><!-- comment [<%= expression%>] -->

A hidden comment is discarded A hidden comment is discarded before any processing of the JSP page before any processing of the JSP page and is not sent to the web browser.and is not sent to the web browser.– <%-- comment --><%-- comment -->

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1717

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1818

Uses of JSP Constructs:Uses of JSP Constructs:Use of Scripting Use of Scripting elementselements

Scripting elements calling Scripting elements calling servlet code directlyservlet code directly

Scripting elements calling Scripting elements calling servlet code indirectly (by servlet code indirectly (by means of utility classes)means of utility classes)

BeansBeans Custom tagsCustom tags Servlet/JSP combo Servlet/JSP combo

(MVC architecture)(MVC architecture)

SimpleApplication

ComplexApplication

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1919

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 servlet’s output. Evaluated and inserted into the servlet’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 servlet’s _jspService Inserted verbatim into the servlet’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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2020

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.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2121

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()); ...... }}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2222

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>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2323

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2424

Implicit objects – Class Implicit objects – 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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2525

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>>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2626

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 seconds out.print("This test is generated about 5 seconds

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2727

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) session.getAttribute("userString name = (String) session.getAttribute("user

name");name");out.print("Welcome to my site " + name + "<br>");out.print("Welcome to my site " + name + "<br>");%>%></</bodybody></></htmlhtml>>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2828

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>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2929

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(); ...... }}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3030

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 wall.<%= i %> bottles of beer on the wall.<<

brbr>><%<%}}%>%>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3131

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

%>"%>">>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3232

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>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3333

ScriptletsScriptlets vs. vs. DeclarationsDeclarations<%! int count=100; %><%! int count=100; %>

<%= ++count %><%= ++count %>

public final class _scopeExpermnt1_public final class _scopeExpermnt1_xjspxjsp

{{ int count=100;int count=100;

public void _jspServicepublic void _jspService (HttpServletRequest request,(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws java.io.IOExceptionthrows java.io.IOException {{ JspWriter out = pageContext.getJspWriter out = pageContext.get

Out();Out();

out.print( out.print( "\r\n" );"\r\n" ); out.print( String.valueOf( ++cout.print( String.valueOf( ++c

ount ) );ount ) ); out.print( "\r\n" );out.print( "\r\n" ); }}}}

<% int count=100; %><% int count=100; %><%= ++count %><%= ++count %>

public final class _scopeExpermnt2_public final class _scopeExpermnt2_xjspxjsp

{{ public void _jspServicepublic void _jspService (HttpServletRequest request,(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws java.io.IOExceptionthrows java.io.IOException {{ JspWriter out = pageContext.geJspWriter out = pageContext.ge

tOut();tOut();

int count=100;int count=100;

out.print( out.print( "\r\n" );"\r\n" ); out.print( String.valueOf( ++out.print( String.valueOf( ++

count ) );count ) ); out.print( "\r\n" );out.print( "\r\n" );

}}}}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3434

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3535

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3636

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>>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3737

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=“value” %><%@ directive attribute=“value” %>– <%@ directive attribute1=“value1”<%@ directive attribute1=“value1” attribute2=“value2”attribute2=“value2” … ….. attributeN=“valueN” %>attributeN=“valueN” %>

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3838

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3939

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 dirsclasses used by JSP pages must be in normal servlet dirs– For Tomcat, this isFor Tomcat, this is

install_dir/webapps/ROOT/WEB-INF/classes orinstall_dir/webapps/ROOT/WEB-INF/classes or…/ROOT/WEB-INF/classes/directoryMatchingPackage…/ROOT/WEB-INF/classes/directoryMatchingPackage

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4040

......<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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4141

Example of import Example of import AttributeAttribute

First accessFirst access

SubsequentSubsequentaccessesaccesses

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4242

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4343

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4444

Another ExampleAnother Example

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4545

<%-- 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.getCurrencyInNumberFormat currency = NumberFormat.getCurrencyIn

stance();stance();%>%>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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4646

Other Attributes of the Other Attributes of the page Directivepage Directive sessionsession

– Lets you choose not to participate in sessionsLets you choose not to participate in sessions bufferbuffer

– Changes min size of buffer used by JspWriterChanges min size of buffer used by JspWriter autoflushautoflush

– Requires developer to explicitly flush bufferRequires developer to explicitly flush buffer extendsextends

– Changes parent class of generated servletChanges parent class of generated servlet errorPageerrorPage

– Designates a page to handle unplanned errorsDesignates a page to handle unplanned errors isErrorPage, isThreadSafe, languageisErrorPage, isThreadSafe, language, …, …

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4747

Break Time – 15 Break Time – 15 minutesminutes

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4848

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 “include” and “plugin” actions.“include” and “plugin” actions.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4949

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)

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5050

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>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5151

Including Pages: Including Pages: ResultResult

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5252

Including Files at Page Including Files at Page Translation TimeTranslation Time FormatFormat

– <%@ include file="Relative URL" %><%@ include file="Relative URL" %> PurposePurpose

– To reuse JSP content in multiple pages, To reuse JSP content in multiple pages, where JSP content affects main pagewhere JSP content affects main page

NotesNotes– Servers are not required to detect changes to the Servers are not required to detect changes to the

included file, and in practice many don'tincluded file, and in practice many don't– Thus, you need to change the JSP files whenever the Thus, you need to change the JSP files whenever the

included file changesincluded file changes– You can use OS-specific mechanisms such as the Unix You can use OS-specific mechanisms such as the Unix

"touch" command, or"touch" command, or <%-- Navbar.jsp modified 3/1/02 --%><%-- Navbar.jsp modified 3/1/02 --%>

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5353

Reusable JSP Content: Reusable JSP Content: ContactSection.jspContactSection.jsp

<%@<%@ page import="java.util.Date" page import="java.util.Date" %>%><%--<%-- The following become fields in each servlet that The following become fields in each servlet that results from a JSP page that includes this file. results from a JSP page that includes this file. --%>--%><%! <%! private int accessCount = 0;private int accessCount = 0;private Date accessDate = new Date();private Date accessDate = new Date();private String accessHost = "<I>No previous access</I>";private String accessHost = "<I>No previous access</I>";%>%><P><HR><P><HR>This page &copy; 2000 This page &copy; 2000 <A HREF="http//www.my-company.com/">my-company.com</A>.<A HREF="http//www.my-company.com/">my-company.com</A>.This page has been accessed This page has been accessed <%=<%= ++accessCount ++accessCount %>%>times since server reboot. It was last accessed from times since server reboot. It was last accessed from <%=<%= accessHost accessHost %>%> at at <%=<%= accessDate accessDate %>%>..<%<% accessHost = request.getRemoteHost(); accessHost = request.getRemoteHost(); %>%><%<% accessDate = new Date(); accessDate = new Date(); %>%>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5454

……<BODY><BODY><TABLE BORDER=5 ALIGN="CENTER"><TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"><TR><TH CLASS="TITLE"> Some Random Page</TABLE>Some Random Page</TABLE><P> Information about our products and services.<P> Information about our products and services.<P> Blah, blah, blah.<P> Blah, blah, blah.<P> Yadda, yadda, yadda.<P> Yadda, yadda, yadda.<%@ include file="ContactSection.jsp" %><%@ include file="ContactSection.jsp" %></BODY></BODY></HTML></HTML>

Using the Using the JSP ContentJSP Content

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5555

Include directive vs.Include directive vs.Include actionInclude action

A request-time include action

A translation-time include directive

<jsp:include page=“test.jsp”…

pageContext.include(test.jsp)

<%@ include file=“test.jsp”…

&copy…

<test.jsp>&copy …

<test.jsp>&copy …

<test.jsp>&copy …

translation

translation translation

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5656

The plugin action’s The plugin action’s attributeattribute <jsp:plugin type=“applet” code=“myBox” <jsp:plugin type=“applet” code=“myBox”

codebase=“path/myClass” width=“200” codebase=“path/myClass” width=“200” height=200”>… params </jsp:plugin>height=200”>… params </jsp:plugin>

We usually useWe usually use– type: to specify we place an applet or others type: to specify we place an applet or others

onto a web page.onto a web page.– Code: to give the name of the Java class to be Code: to give the name of the Java class to be

run.run.– Width/Height: to define the size of the Width/Height: to define the size of the

rectangle set aside for displaying the applet in rectangle set aside for displaying the applet in the browser’s window.the browser’s window.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5757

jsp:forward actionjsp:forward action

Used to instruct a web server to stop Used to instruct a web server to stop processing the current page and start processing the current page and start another one.another one.<jsp:forward page=“another.jsp”><jsp:forward page=“another.jsp”>

<jsp:param name=“callingPage” <jsp:param name=“callingPage” value=“current.jsp”>value=“current.jsp”>

</jsp:forward></jsp:forward>

– Another page:Another page: <%= request.getParameter(“callingPage”) %><%= request.getParameter(“callingPage”) %> Returns “current.jsp”Returns “current.jsp”

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5858

Uses of JSP Constructs:Uses of JSP Constructs:Using JavaBeans Using JavaBeans

Scripting elements calling Scripting elements calling servlet code directlyservlet code directly

Scripting elements calling Scripting elements calling servlet code indirectly (by servlet code indirectly (by means of utility classes)means of utility classes)

BeansBeans Custom tagsCustom tags Servlet/JSP combo Servlet/JSP combo

(MVC architecture)(MVC architecture)

SimpleApplication

ComplexApplication

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5959

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/

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6060

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6161

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() %>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6262

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"); %>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6363

Example: StringBeanExample: StringBean

publicpublic class StringBean { class StringBean { private String message = "No message specified";private String message = "No message 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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6464

<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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6565

JSP Page That Uses JSP Page That Uses StringBeanStringBean

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6666

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6767

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")

%>'%>' /> />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6868

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 %>" /> />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6969

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 %>" /> />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7070

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" /> />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7171

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="*" /> />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7272

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="…" class="…" <jsp:useBean id="…" 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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7373

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).

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7474

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

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7575

Conditional Bean Conditional Bean OperationsOperations Bean conditionally created Bean conditionally created

– jsp:useBean results in new bean object only if jsp:useBean results in new bean object only if no bean with same id and scope can be found no bean with same id and scope can be found

– If a bean with same id and scope is found, the If a bean with same id and scope is found, the preexisting bean is simply bound to variable preexisting bean is simply bound to variable referenced by idreferenced by id

Bean properties conditionally setBean properties conditionally set– <jsp:useBean ... /> replaced by<jsp:useBean ... /> replaced by

<jsp:useBean ...><jsp:useBean ...>statementsstatements</jsp:useBean></jsp:useBean>– The statements (jsp:setProperty elements) The statements (jsp:setProperty elements)

are executed only if a new bean is created, are executed only if a new bean is created, not if an existing bean is foundnot if an existing bean is found

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7676

Conditional Bean Conditional Bean Creation: Creation: AccessCountBeanAccessCountBeanpublicpublic class class AccessCountBean AccessCountBean {{ private String firstPage;private String firstPage; private int accessCount = 1;private int accessCount = 1;

publicpublic String String getFirstPagegetFirstPage() {() { return(firstPage);return(firstPage); }} publicpublic void void setFirstPagesetFirstPage(String firstPage) {(String firstPage) { this.firstPage = firstPage;this.firstPage = firstPage; }} publicpublic int int getAccessgetAccessCount() {Count() { return(accessCount);return(accessCount); }} public public void void setAccessCountIncrementsetAccessCountIncrement(int increment) (int increment)

{{ accessCount = accessCount + increment;accessCount = accessCount + increment; }}}}

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7777

Conditional Bean Conditional Bean Creation: Creation: SharedCounts1.jspSharedCounts1.jsp

<jsp:useBean id="counter" class="coreservlets.AccessCountBean"<jsp:useBean id="counter" class="coreservlets.AccessCountBean" scope="application">scope="application"> <jsp:setProperty name="counter" <jsp:setProperty name="counter" property="firstPage" property="firstPage"

value="SharedCounts1.jsp" />value="SharedCounts1.jsp" /></jsp:useBean></jsp:useBean>Of SharedCounts1.jsp (this page), Of SharedCounts1.jsp (this page), <a href="SharedCounts2.jsp">SharedCounts2.jsp</a>, and<a href="SharedCounts2.jsp">SharedCounts2.jsp</a>, and<a href="SharedCounts3.jsp">SharedCounts3.jsp</a>, <a href="SharedCounts3.jsp">SharedCounts3.jsp</a>, <jsp:getProperty name="counter" property="firstPage" /><jsp:getProperty name="counter" property="firstPage" />was the first page accessed.was the first page accessed.<p><p>Collectively, the three pages have been accessed Collectively, the three pages have been accessed <jsp:getProperty name="counter" property="accessCount" /><jsp:getProperty name="counter" property="accessCount" />times. times. <jsp:setProperty name="counter"<jsp:setProperty name="counter" property="accessCountIncrement" value="1" />property="accessCountIncrement" value="1" />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7878

Accessing SharedCounts1, Accessing SharedCounts1, SharedCounts2, SharedCounts2, SharedCounts3SharedCounts3 SharedCounts2.jsp was accessed first.SharedCounts2.jsp was accessed first. Pages have been accessed twelve Pages have been accessed twelve

previous times by an arbitrary number of previous times by an arbitrary number of clientsclients

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7979

Actions essentialsActions essentials

<jsp:forward> action<jsp:forward> action <jsp:setProperty> action<jsp:setProperty> action <jsp:getProperty> action<jsp:getProperty> action <jsp:plugin> action<jsp:plugin> action <jsp:include> action<jsp:include> action <jsp:useBean> action<jsp:useBean> action Can you identify the use of each Can you identify the use of each

action?action?

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8080

Uses of JSP Uses of JSP Constructs:Constructs:Custom JSP Tag Custom JSP Tag LibrariesLibraries Scripting elements calling Scripting elements calling

servlet code directlyservlet code directly Scripting elements calling Scripting elements calling

servlet code indirectly (by servlet code indirectly (by means of utility classes)means of utility classes)

BeansBeans Custom tagsCustom tags Servlet/JSP combo Servlet/JSP combo

(MVC architecture)(MVC architecture)

SimpleApplication

ComplexApplication

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8181

Components That Components That Make Up a Tag LibraryMake Up a Tag Library

The Tag Handler ClassThe Tag Handler Class– Must implement javax.servlet.jsp.tagext.Tag Must implement javax.servlet.jsp.tagext.Tag – Usually extends TagSupport or BodyTagSupportUsually extends TagSupport or BodyTagSupport– Goes in same directories as servlet class files and Goes in same directories as servlet class files and

beansbeans The Tag Library Descriptor FileThe Tag Library Descriptor File

– XML file describing tag name, attributes, and XML file describing tag name, attributes, and implementing tag handler classimplementing tag handler class

– Goes with JSP file or at arbitrary URLGoes with JSP file or at arbitrary URL The JSP FileThe JSP File

– Imports a tag library (referencing descriptor file)Imports a tag library (referencing descriptor file)– Defines tag prefix, uses tagsDefines tag prefix, uses tags

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8282

Defining a Simple Tag Defining a Simple Tag Handler ClassHandler Class

Extend the TagSupport classExtend the TagSupport class Import needed packagesImport needed packages

– import javax.servlet.jsp.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.tagext.*;import java.io.*;import java.io.*;

Override doStartTagOverride doStartTag– Obtain the JspWriter by means of pageContext.getOut()Obtain the JspWriter by means of pageContext.getOut()– Use the JspWriter to generate JSP contentUse the JspWriter to generate JSP content– Return SKIP_BODYReturn SKIP_BODY– Translated into servlet code at page-translation timeTranslated into servlet code at page-translation time– Code gets called at request timeCode gets called at request time

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8383

package cwp.tags;package cwp.tags;import javax.servlet.jsp.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.tagext.*;import java.io.*;import java.io.*;import java.math.*;import java.math.*;import cwp.*;import cwp.*;

public class SimplePrimeTag public class SimplePrimeTag extends TagSupportextends TagSupport { { protected int len = 50;protected int len = 50; public int public int doStartTagdoStartTag() {() { try {try { JspWriter out = pageContext.getOut();JspWriter out = pageContext.getOut(); BigInteger prime = BigInteger prime = Primes.nextPrime(Primes.random(len));Primes.nextPrime(Primes.random(len)); out.print(prime);out.print(prime); } catch(IOException ioe) {} catch(IOException ioe) { System.out.println("Error generating prime: " + ioe);System.out.println("Error generating prime: " + ioe); }} return(SKIP_BODY);return(SKIP_BODY); }}}}

Defining a Defining a Simple Tag Simple Tag Handler ClassHandler Class

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8484

Defining a Simple Tag Defining a Simple Tag Library DescriptorLibrary Descriptor Start with XML header and DOCTYPEStart with XML header and DOCTYPE Top-level element is Top-level element is taglibtaglib Each tag defined by tag element containing:Each tag defined by tag element containing:

– namename, whose body defines the base tag name. , whose body defines the base tag name. In this case, I use In this case, I use <name>simplePrime</name><name>simplePrime</name>

– tagclasstagclass, which gives the fully qualified class name of , which gives the fully qualified class name of the tag handler. In this case, I use the tag handler. In this case, I use <tagclass>cwp.tags.SimplePrimeTag</tagclass><tagclass>cwp.tags.SimplePrimeTag</tagclass>

– bodycontentbodycontent, which gives hints to development , which gives hints to development environments. Optional. environments. Optional.

– infoinfo, which gives a short description. Here, I use, which gives a short description. Here, I use<info>Outputs a random 50-digit prime.</info><info>Outputs a random 50-digit prime.</info>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8585

<?xml version="1.0" encoding="ISO-8859-1" ?><?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglib ...><!DOCTYPE taglib ...><taglib><taglib> <tlibversion>1.0</tlibversion><tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion><jspversion>1.1</jspversion> <shortname>cwp</shortname><shortname>cwp</shortname> <info><info> A tag library from Core Web Programming 2nd A tag library from Core Web Programming 2nd

Edition,Edition, http://www.corewebprogramming.com/.http://www.corewebprogramming.com/. </info></info> <tag><tag> <name>simplePrime</name><name>simplePrime</name> <tagclass>cwp.tags.SimplePrimeTag</tagclass><tagclass>cwp.tags.SimplePrimeTag</tagclass> <info>Outputs a random 50-digit prime.</info><info>Outputs a random 50-digit prime.</info> </tag></tag></taglib></taglib>

TLD File for TLD File for SimplePrimeTSimplePrimeTagag

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8686

Accessing Custom Accessing Custom Tags From JSP FilesTags From JSP Files Import the tag libraryImport the tag library

– Specify location of TLD fileSpecify location of TLD file<%@ taglib <%@ taglib uri= "cwp-taglib.tld"uri= "cwp-taglib.tld" prefix= prefix= "cwp" %>"cwp" %>

– Define a tag prefix (namespace)Define a tag prefix (namespace)<%@ taglib uri="cwp-taglib.tld" <%@ taglib uri="cwp-taglib.tld" prefix= prefix= "cwp""cwp" %> %>

Use the tagsUse the tags– <prefix:tagName /><prefix:tagName />

Tag name comes from TLD fileTag name comes from TLD file Prefix comes from taglib directivePrefix comes from taglib directive

– E.g., E.g., <cwp:simplePrime /><cwp:simplePrime />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8787

……

<H1>Some 50-Digit Primes</H1><H1>Some 50-Digit Primes</H1>

<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %><%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>

<UL><UL>

<LI><LI><cwp:simplePrime /> <cwp:simplePrime /> <LI> <LI><cwp:simplePrime /><cwp:simplePrime />

<LI><LI><cwp:simplePrime /> <cwp:simplePrime /> <LI> <LI><cwp:simplePrime /><cwp:simplePrime />

</UL></UL>

Using Using simplePrimsimplePrime Tage Tag

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8888

Intermediate and Intermediate and Advanced Custom TagsAdvanced Custom Tags Tags with attributesTags with attributes Tags that include their body contentTags that include their body content Tags that optionally include their bodyTags that optionally include their body Tags that manipulate their bodyTags that manipulate their body Tags that manipulating their body multiple Tags that manipulating their body multiple

times (looping tags)times (looping tags) Nested tagsNested tags See book for details (related chapter online in See book for details (related chapter online in

PDF at Java Developer’s Connection)PDF at Java Developer’s Connection)– http://developer.java.sun.com/developer/Books/http://developer.java.sun.com/developer/Books/

cservletsjsp/cservletsjsp/

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8989

……

<H1>Some N-Digit Primes</H1><H1>Some N-Digit Primes</H1>

<%@ taglib uri="cwp-taglib.tld" prefix="cwp" <%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>%>

<UL><UL>

<LI>20-digit: <LI>20-digit: <cwp:prime length="20" /><cwp:prime length="20" />

<LI>40-digit: <LI>40-digit: <cwp:prime length="40" /><cwp:prime length="40" />

<LI>80-digit: <LI>80-digit: <cwp:prime length="80" /><cwp:prime length="80" />

<LI>Default (50-digit): <LI>Default (50-digit): <cwp:prime /><cwp:prime />

</UL></UL>

Tags with Tags with AttributeAttributes: Prime s: Prime TagTag

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9090

Including Body Including Body Content: Content: heading Tagheading Tag

……

<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %><%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>

<cwp:heading bgColor="#C0C0C0"><cwp:heading bgColor="#C0C0C0">

Default HeadingDefault Heading

</cwp:heading></cwp:heading>

<P><P>

<cwp:heading bgColor="BLACK" color="WHITE"><cwp:heading bgColor="BLACK" color="WHITE">

White on Black HeadingWhite on Black Heading

</cwp:heading></cwp:heading>

<P><P>

<cwp:heading bgColor="#EF8429" fontSize="60" border="5"><cwp:heading bgColor="#EF8429" fontSize="60" border="5">

Large Bordered HeadingLarge Bordered Heading

</cwp:heading></cwp:heading>

……

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9191

Optionally Including Optionally Including Tag Body: debug TagTag Body: debug Tag<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %><%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>Top of regular page. Blah, blah, blah. Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.Yadda, yadda, yadda.<P><P><cwp:debug><cwp:debug><B>Debug:</B><B>Debug:</B><UL><UL> <LI>Current time: <%= new java.util.Date() %><LI>Current time: <%= new java.util.Date() %> <LI>Requesting hostname: <%= request.getRemoteHost()%><LI>Requesting hostname: <%= request.getRemoteHost()%>

<LI>Session ID: <%= session.getId() %><LI>Session ID: <%= session.getId() %></UL></UL></cwp:debug></cwp:debug><P><P>Bottom of regular page. Blah, blah, blah. Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.Yadda, yadda, yadda.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9292

Using debug Tag: Using debug Tag: ResultsResults

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9393

Manipulating Tag Manipulating Tag Body: Body: the filter Tagthe filter Tag<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %><%@ taglib uri="cwp-taglib.tld" prefix="cwp" %><TABLE BORDER=1 ALIGN="CENTER"><TABLE BORDER=1 ALIGN="CENTER"><TR CLASS="COLORED"><TH>Example<TH>Result<TR CLASS="COLORED"><TH>Example<TH>Result<TR><TR><TD><PRE><TD><PRE><cwp:filter><cwp:filter><EM>Some emphasized text.</EM><BR><EM>Some emphasized text.</EM><BR><STRONG>Some strongly emphasized text.</STRONG><BR><STRONG>Some strongly emphasized text.</STRONG><BR><CODE>Some code.</CODE><BR><CODE>Some code.</CODE><BR>……</cwp:filter></cwp:filter></PRE></PRE><TD><TD><EM>Some emphasized text.</EM><BR><EM>Some emphasized text.</EM><BR><STRONG>Some strongly emphasized text.</STRONG><BR><STRONG>Some strongly emphasized text.</STRONG><BR><CODE>Some code.</CODE><BR><CODE>Some code.</CODE><BR>……</TABLE></TABLE>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9494

Using the filter Tag: Using the filter Tag: ResultsResults

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9595

<%@ taglib uri="cwp-taglib.tld" prefix="cwp" <%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>%>

<OL><OL>

<!-- Repeats N times. A null reps value <!-- Repeats N times. A null reps value

means repeat once. -->means repeat once. -->

<cwp:repeat <cwp:repeat

reps='<%= request.getParameter("repeats") reps='<%= request.getParameter("repeats") %>'>%>'>

<LI><cwp:prime length="40" /><LI><cwp:prime length="40" />

</cwp:repeat></cwp:repeat>

</OL></OL>

Manipulating Manipulating the Body the Body Multiple Multiple Times: the Times: the repeat Tagrepeat Tag

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9696

Nested Tags: the if TagNested Tags: the if Tag<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %><%@ taglib uri="cwp-taglib.tld" prefix="cwp" %><cwp:if><cwp:if> <cwp:condition><cwp:condition>truetrue</cwp:condition></cwp:condition> <cwp:then><cwp:then>Condition is trueCondition is true</cwp:then></cwp:then> <cwp:else><cwp:else>Condition is falseCondition is false</cwp:else></cwp:else></cwp:if></cwp:if>……Some coin tosses:<BR>Some coin tosses:<BR><cwp:repeat reps="10"><cwp:repeat reps="10"> <cwp:if><cwp:if> <cwp:condition><cwp:condition> <%= Math.random() < 0.5 %><%= Math.random() < 0.5 %> </cwp:condition></cwp:condition>

<cwp:then><cwp:then><B>Heads</B><BR><B>Heads</B><BR></cwp:then</cwp:then>>

<cwp:else><cwp:else><B>Tails</B><BR><B>Tails</B><BR></cwp:else></cwp:else> </cwp:if></cwp:if></cwp:repeat></cwp:repeat>

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9797

Open Source Tag LibrariesOpen Source Tag Librarieshttp://jakarta.apache.org/taglibhttp://jakarta.apache.org/taglibs/s/

Internationalization (I18N)Internationalization (I18N) Database accessDatabase access Sending emailSending email JNDITMJNDITM Date/timeDate/time Populating/validating form fieldsPopulating/validating form fields Perl regular expressionsPerl regular expressions Extracting data from other Web pagesExtracting data from other Web pages XSL transformationsXSL transformations EtcEtc

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9898

Break Time – 15 Break Time – 15 minutesminutes

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

9999

Uses of JSP Constructs:Uses of JSP Constructs:Integrating Servlets and Integrating Servlets and JSPJSP

Scripting elements calling Scripting elements calling servlet code directlyservlet code directly

Scripting elements calling Scripting elements calling servlet code indirectly (by servlet code indirectly (by means of utility classes)means of utility classes)

BeansBeans Custom tagsCustom tags Servlet/JSP combo Servlet/JSP combo

(MVC architecture)(MVC architecture)

SimpleApplication

ComplexApplication

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

100100

Why Combine Servlets Why Combine Servlets & JSP?& JSP? Typical picture: use JSP to make it easier to Typical picture: use JSP to make it easier to

develop and maintain the HTML contentdevelop and maintain the HTML content– For simple dynamic code, call servlet code from For simple dynamic code, call servlet code from

scripting expressionsscripting expressions– For moderately complex cases, use custom classes For moderately complex cases, use custom classes

called from scripting expressionscalled from scripting expressions– For more complicated cases, use beans and custom For more complicated cases, use beans and custom

tagstags But, that's not enoughBut, that's not enough

– For complex processing, JSP is awkwardFor complex processing, JSP is awkward– Despite the convenience of separate classes, beans, Despite the convenience of separate classes, beans,

and custom tags, and custom tags, the assumption behind JSP is that a the assumption behind JSP is that a single page gives a single basic looksingle page gives a single basic look

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

101101

Integrating Servlets and Integrating Servlets and JSPJSP : :ArchitectureArchitecture ApproachApproach

– Original request is answered by a servletOriginal request is answered by a servlet– Servlet processes request data, does database Servlet processes request data, does database

lookup, accesses business logic, etc.lookup, accesses business logic, etc.– Results are placed in beansResults are placed in beans– Request is forwarded to a JSP page to format resultRequest is forwarded to a JSP page to format result– Different JSP pages can be used to handle different Different JSP pages can be used to handle different

types of presentationtypes of presentation TerminologyTerminology

– Often called the “Model View Controller” architecture Often called the “Model View Controller” architecture or “Model 2” approach to JSPor “Model 2” approach to JSP

– Formalized further with Apache “Struts” frameworkFormalized further with Apache “Struts” framework See http://jakarta.apache.org/struts/See http://jakarta.apache.org/struts/

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

102102

Dispatching RequestsDispatching Requests

First, call the getRequestDispatcher method First, call the getRequestDispatcher method of ServletContextof ServletContext– Supply a URL relative to the Web application Supply a URL relative to the Web application

rootroot– ExampleExample

String url = "/presentations/presentation1.jsp";String url = "/presentations/presentation1.jsp";RequestDispatcher dispatcher =RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); getServletContext().getRequestDispatcher(url);

SecondSecond– Call Call forwardforward to completely transfer control to completely transfer control

to destination page. See following exampleto destination page. See following example– Call include to insert output of destination page Call include to insert output of destination page

and then continue on.and then continue on.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

103103

public void doGet(HttpServletRequest request,public void doGet(HttpServletRequest request, HttpServletResponse response)HttpServletResponse response) throws ServletException, IOException {throws ServletException, IOException { String operation = request.getParameter("operation");String operation = request.getParameter("operation"); if (operation == null) {if (operation == null) { operation = "unknown";operation = "unknown"; }} if (operation.equals("operation1")) {if (operation.equals("operation1")) { gotoPage("/operations/presentation1.jsp",gotoPage("/operations/presentation1.jsp", request, response);request, response); } else if (operation.equals("operation2")) {} else if (operation.equals("operation2")) { gotoPage("/operations/presentation2.jsp",gotoPage("/operations/presentation2.jsp", request, response);request, response); } else {} else { gotoPage("/operations/unknownRequestHandler.jsp",gotoPage("/operations/unknownRequestHandler.jsp", request, response);request, response); }}}}private void gotoPage(String address,private void gotoPage(String address, HttpServletRequest request, HttpServletResponse HttpServletRequest request, HttpServletResponse

response)response) throws ServletException, IOException {throws ServletException, IOException { RequestDispatcher dispatcher =RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);getServletContext().getRequestDispatcher(address); dispatcher.forward(request, response);dispatcher.forward(request, response);}}

ForwardinForwarding g RequestsRequests

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

104104

Reminder: JSP Reminder: JSP useBean useBean Scope AlternativesScope Alternatives requestrequest

– <jsp:useBean id="..." class="..." <jsp:useBean id="..." class="..." scope="request"scope="request" /> /> sessionsession

– <jsp:useBean id="..." class="..." <jsp:useBean id="..." class="..." scope="session"scope="session" /> /> applicationapplication

– <jsp:useBean id="..." class="..." <jsp:useBean id="..." class="..." scope="application"scope="application" /> />

pagepage– <jsp:useBean id="..." class="..." <jsp:useBean id="..." class="..." scope="page"scope="page" /> />

or justor just<jsp:useBean id="..." class="..." /><jsp:useBean id="..." class="..." />

– This scope is not used in MVC architectureThis scope is not used in MVC architecture

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

105105

Storing Data for Later Storing Data for Later Use:Use:The Servlet RequestThe Servlet Request PurposePurpose

– Storing data that servlet looked up and that Storing data that servlet looked up and that JSP page will use only in this request.JSP page will use only in this request.

Servlet syntax to store dataServlet syntax to store dataSomeClass value = new SomeClass(…);SomeClass value = new SomeClass(…);

request.setAttribute("key", value);request.setAttribute("key", value);

// Use RequestDispatcher to forward to JSP page// Use RequestDispatcher to forward to JSP page JSP syntax to retrieve dataJSP syntax to retrieve data

<jsp:useBean id="key" <jsp:useBean id="key" class="SomeClass" class="SomeClass" scope="request"scope="request" /> />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

106106

Storing Data for Later Storing Data for Later Use:Use:The Session ObjectThe Session Object PurposePurpose

– Storing data that servlet looked up and that JSP page will Storing data that servlet looked up and that JSP page will use in this request and in later requests from same client.use in this request and in later requests from same client.

Servlet syntax to store dataServlet syntax to store dataSomeClass value = new SomeClass(…);SomeClass value = new SomeClass(…);HttpSession session = request.getSession(true);HttpSession session = request.getSession(true);session.setAttribute("key", value);session.setAttribute("key", value);// Use RequestDispatcher to forward to JSP page// Use RequestDispatcher to forward to JSP page

JSP syntax to retrieve dataJSP syntax to retrieve data<jsp:useBean id="key" <jsp:useBean id="key"

class="SomeClass“ class="SomeClass“ scope="session"scope="session" /> />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

107107

Storing Data for Later Storing Data for Later Use:Use:The Servlet ContextThe Servlet Context PurposePurpose

– Storing data that servlet looked up and that JSP page Storing data that servlet looked up and that JSP page will use in this request and in later requests from any will use in this request and in later requests from any client.client.

Servlet syntax to store dataServlet syntax to store dataSomeClass value = new SomeClass(…);SomeClass value = new SomeClass(…);

getServletContext().setAttribute("key", value);getServletContext().setAttribute("key", value);

// Use RequestDispatcher to forward to JSP page// Use RequestDispatcher to forward to JSP page JSP syntax to retrieve dataJSP syntax to retrieve data

<jsp:useBean <jsp:useBean id="key" id="key" class="SomeClass" class="SomeClass" scope="application"scope="application" /> />

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

108108

An On-Line Travel An On-Line Travel AgentAgent

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

109109

Review: JSP Review: JSP IntroductionIntroduction JSP makes it easier to create/maintain JSP makes it easier to create/maintain

HTML, while still providing full access to HTML, while still providing full access to servlet codeservlet code

JSP pages get translated into servletsJSP pages get translated into servlets– It is the servlets that run at request timeIt is the servlets that run at request time– Client does not see anything JSP-relatedClient does not see anything JSP-related

You still need to understand servletsYou still need to understand servlets– Understanding how JSP really worksUnderstanding how JSP really works– Servlet code called from JSPServlet code called from JSP– Knowing when servlets are better than JSPKnowing when servlets are better than JSP– Mixing servlets and JSPMixing servlets and JSP

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

110110

Uses of JSP ConstructsUses of JSP Constructs

Scripting elements calling Scripting elements calling servlet code directlyservlet code directly

Scripting elements calling Scripting elements calling servlet code indirectly (by servlet code indirectly (by means of utility classes)means of utility classes)

BeansBeans Custom tagsCustom tags Servlet/JSP combo Servlet/JSP combo

(MVC architecture)(MVC architecture)

SimpleApplication

ComplexApplication

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

111111

Review: Calling Java Code Review: Calling Java Code Directly: JSP Scripting Directly: JSP Scripting ElementsElements

JSP ExpressionsJSP Expressions– Format: Format: <%= expression %><%= expression %>– Evaluated and inserted into the servlet’s output. Evaluated and inserted into the servlet’s output.

JSP ScriptletsJSP Scriptlets– Format: Format: <% code %><% code %>– Inserted verbatim into the _jspService method Inserted verbatim into the _jspService method

JSP DeclarationsJSP Declarations– Format: Format: <%! code %><%! code %>– Inserted verbatim into the body of the servlet classInserted verbatim into the body of the servlet class

Predefined variablesPredefined variables– request, response, out, session, applicationrequest, response, out, session, application

Limit the Java code in pageLimit the Java code in page– Use helper classes, beans, custom tags, servlet/JSP comboUse helper classes, beans, custom tags, servlet/JSP combo

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

112112

Review: The JSP page Review: The JSP page Directive: Structuring Directive: Structuring Generated ServletsGenerated Servlets

The import attributeThe import attribute– Changes the packages imported by Changes the packages imported by

the servlet that results from the JSP the servlet that results from the JSP pagepage

The contentType attributeThe contentType attribute– Specifies MIME type of resultSpecifies MIME type of result– Cannot be used conditionallyCannot be used conditionally

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

113113

Review: Including Files Review: Including Files in JSP Documentsin JSP Documents

<jsp:include page="Relative URL" <jsp:include page="Relative URL" flush="true" />flush="true" />– Output inserted into JSP page at request timeOutput inserted into JSP page at request time– Cannot contain JSP content that affects entire pageCannot contain JSP content that affects entire page– Changes to included file do not necessitate changes Changes to included file do not necessitate changes

to pages that use itto pages that use it <%@ include file="Relative URL" %><%@ include file="Relative URL" %>

– File gets inserted into JSP page prior to page File gets inserted into JSP page prior to page translationtranslation

– Thus, file can contain JSP content that affects entire Thus, file can contain JSP content that affects entire page (e.g., import statements, declarations)page (e.g., import statements, declarations)

– Changes to included file might require you to Changes to included file might require you to manually update pages that use itmanually update pages that use it

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

114114

Review: Using Review: Using JavaBeans JavaBeans Components with JSPComponents with JSP Benefits of jsp:useBeanBenefits of jsp:useBean

– Hides the Java programming language syntaxHides the Java programming language syntax– Makes it easier to associate request parameters with Makes it easier to associate request parameters with

objects (bean properties)objects (bean properties)– Simplifies sharing objects among multiple requests or Simplifies sharing objects among multiple requests or

servlets/JSPsservlets/JSPs jsp:useBean jsp:useBean

– Creates or accesses a beanCreates or accesses a bean jsp:getPropertyjsp:getProperty

– Puts bean property (i.e. getXxx call) into outputPuts bean property (i.e. getXxx call) into output jsp:setPropertyjsp:setProperty

– Sets bean property (i.e. passes value to setXxx)Sets bean property (i.e. passes value to setXxx)

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

115115

Review: Creating Review: Creating Custom Custom JSP Tag LibrariesJSP Tag Libraries For each custom tag, you needFor each custom tag, you need

– A tag handler class (usually extending A tag handler class (usually extending TagSupport or BodyTagSupport)TagSupport or BodyTagSupport)

– An entry in a Tag Library Descriptor fileAn entry in a Tag Library Descriptor file– A JSP file that imports library, specifies prefix, and A JSP file that imports library, specifies prefix, and

uses tagsuses tags Simple tagsSimple tags

– Generate output in doStartTag, return SKIP_BODYGenerate output in doStartTag, return SKIP_BODY AttributesAttributes

– Define setAttributeName method. Update TLD fileDefine setAttributeName method. Update TLD file Body contentBody content

– doStartTag returns EVAL_BODY_INCLUDEdoStartTag returns EVAL_BODY_INCLUDE– Add doEndTag methodAdd doEndTag method

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

116116

Review: Integrating Review: Integrating Servlets and JSPServlets and JSP Use MVC (Model 2) approach when:Use MVC (Model 2) approach when:

– One submission will result in multiple basic looks One submission will result in multiple basic looks – Several pages have substantial common processingSeveral pages have substantial common processing

ArchitectureArchitecture– A servlet answers the original requestA servlet answers the original request– Servlet does the real processing & stores results in beansServlet does the real processing & stores results in beans

Beans stored in HttpServletRequest, HttpSession, or Beans stored in HttpServletRequest, HttpSession, or ServletContextServletContext

– Servlet forwards to JSP page via forward method of Servlet forwards to JSP page via forward method of RequestDispatcherRequestDispatcher

– JSP page reads data from beans by means of jsp:useBean JSP page reads data from beans by means of jsp:useBean with appropriate scope (request, session, or application)with appropriate scope (request, session, or application)

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

117117

ReferencesReferences

CWP2: Chapter 20CWP2: Chapter 20 http://java.sun.com/products/jsp/docs.htmlhttp://java.sun.com/products/jsp/docs.html http://java.sun.com/j2ee/tutorial/1_3-fcs/dohttp://java.sun.com/j2ee/tutorial/1_3-fcs/do

c/JSPIntro.htmlc/JSPIntro.html http://www.jsptut.com/http://www.jsptut.com/ http://www.jspin.com/home/tutorialshttp://www.jspin.com/home/tutorials

The End.The End. Thank you for patience!Thank you for patience!