Programming Web Applications Programming Web Applications The - - PowerPoint PPT Presentation

programming web applications programming web applications
SMART_READER_LITE
LIVE PREVIEW

Programming Web Applications Programming Web Applications The - - PowerPoint PPT Presentation

Objectives Objectives How to program Web applications using JSP An Introduction to XML and Web Technologies An Introduction to XML and Web Technologies How to extend the JSP syntax using tag libraries Programming Web Applications


slide-1
SLIDE 1

1

An Introduction to XML and Web Technologies An Introduction to XML and Web Technologies

Programming Web Applications Programming Web Applications with JSP with JSP

Anders Møller & Michael I. Schwartzbach  2006 Addison-Wesley

2

An Introduction to XML and Web Technologies

Objectives Objectives

How to program Web applications using JSP How to extend the JSP syntax using tag libraries The relation to Servlets

3

An Introduction to XML and Web Technologies

The JSP Framework The JSP Framework

Servlets make heavy use of Java and require sophisticated programming JSP views a Web application as a collection of active pages The pages are HTML with snippets of code JSP pages are translated into servlets

4

An Introduction to XML and Web Technologies

A Tiny Example A Tiny Example

<% response.ad <% response.addDateHeader("E dDateHeader("Expires", 0); % xpires", 0); %> <html> <head><title>JSP</title></head> <body> <h1>Hello World!</h1> <%! int hi <%! int hits = 0; %> ts = 0; %> You are visitor number <% synchro <% synchronized(this) { nized(this) { out.println(++

  • ut.println(++hits); } %>

hits); } %> since the last time the service was restarted. <p> This page was last updated: <%= new ja <%= new java.util.Date() va.util.Date().toLocaleStrin .toLocaleString() %> g() %> </body> </html>

slide-2
SLIDE 2

2

5

An Introduction to XML and Web Technologies

JSP Templates JSP Templates

A text file with snippets of Java code:

  • expressions
  • statements
  • declarations

JSP directives Implicitly declared variables:

  • HttpServletRequest req

reque uest st;

  • HttpServletResponse re

resp spon

  • nse

se;

  • HttpSession se

sess ssio ion;

  • ServletContext app

appli lica cati tion

  • n;
  • ServletConfig co

conf nfig ig;

  • JspWriter ou
  • ut;
  • PageContext pa

page geCo Cont ntex ext;

6

An Introduction to XML and Web Technologies

JSP Expressions JSP Expressions

<html> <head><title>Addition</title></head> <body> The sum of <%= request.g <%= request.getParameter("x etParameter("x") %> ") %> and <%= re <%= request.getParam quest.getParameter("y") %> eter("y") %> is <%= Intege <%= Integer.parseInt(req r.parseInt(request.getParame uest.getParameter("x")) + ter("x")) + Intege Integer.parseInt(req r.parseInt(request.getParame uest.getParameter("y")) %> ter("y")) %> </body> </html>

7

An Introduction to XML and Web Technologies

JSP Statements JSP Statements

<html> <head><title>Numbers</title></head> <body> <ul> <% int n <% int n = = Integer.parseIn nteger.parseInt(request.getP t(request.getParameter("n")) arameter("n")); for ( for (int i=0; i<n; int i=0; i<n; i++) i++)

  • ut
  • ut.println("<li>

.println("<li>"+i+"</li>"); "+i+"</li>"); %> %> </ul> </body> </html>

8

An Introduction to XML and Web Technologies

JSP Declarations JSP Declarations

<%! int add(St <%! int add(String x, String ring x, String y) { y) { return I return Integer.parseIn nteger.parseInt(x)+Integer.p t(x)+Integer.parseInt(y); arseInt(y); } %> %> <html> <head><title>Addition</title></head> <body> The sum of <%= request.getParameter("x") %> and <%= request.getParameter("y") %> is <%= add(request.getParameter("x"), request.getParameter("y")) %> </body> </html>

slide-3
SLIDE 3

3

9

An Introduction to XML and Web Technologies

Be Careful About Declarations (1/2) Be Careful About Declarations (1/2)

<% response.addDateHeader("Expires", 0); %> <html> <head><title>JSP</title></head> <body> <h1>Hello World!</h1> <%! in <%! int t hit hits = s = 0 0; % %> You are visitor number <% synchronized(this) { out.println(++hits); } %> since the last time the service was restarted. <p> This page was last updated: <%= new java.util.Date().toLocaleString() %> </body> </html>

10

An Introduction to XML and Web Technologies

Be Careful About Declarations (2/2) Be Careful About Declarations (2/2)

<% response.addDateHeader("Expires", 0); %> <html> <head><title>JSP</title></head> <body> <h1>Hello World!</h1> <% int <% int h hits its = = 0; 0; %> %> You are visitor number <% synchronized(this) { out.println(++hits); } %> since the last time the service was restarted. <p> This page was last updated: <%= new java.util.Date().toLocaleString() %> </body> </html>

This page counter is always 1...

11

An Introduction to XML and Web Technologies

JSP Directives JSP Directives

header.jsp

<html> <head><title><%= title %></title></head> <body>

footer.jsp

</body> </html> <%! String title = "Addition"; %> <%@ <%@ incl nclud ude fil e file=" e="he heade ader. r.js jsp" %> p" %> The sum of <%= request.getParameter("x") %> and <%= request.getParameter("y") %> is <%= Integer.parseInt(request.getParameter("x")) + Integer.parseInt(request.getParameter("y")) %> <%@ <%@ incl nclud ude fil e file=" e="fo foote

  • ter.

r.js jsp" %> p" %>

12

An Introduction to XML and Web Technologies

Other Directives Other Directives

contentType="type" info=”description" errorPage="path" isErrorPage="boolean" import="package"

slide-4
SLIDE 4

4

13

An Introduction to XML and Web Technologies

Using Error Pages Using Error Pages

<%@ <%@ p page age e errorP

  • rPage

age=" ="err error

  • r.j

.jsp" sp" %> %> <html> <head><title>Division</title></head> <body> <% int n = Integer.parseInt(request.getParameter("n")); %> <% int m = Integer.parseInt(request.getParameter("m")); %> <%= n %>/<%= m %> equals <%= n/m %> </body> </html> <%@ <%@ p page age i isErro rrorPa rPage ge="t ="tru rue" e" %> %> <html> <head><title>Error</title></head> <body> Something bad happened: <%= except exception ion.getMessage() %> </body> </html>

14

An Introduction to XML and Web Technologies

Translation into Servlets Translation into Servlets

<% <% re respo spons nse. e.add addDat DateH eHead eader er(" ("Exp Expire ires" s", 0 , 0); % %> <html> <head><title>JSP</title></head> <body> <h1>Hello World!</h1> <%! in <%! int t hit hits = s = 0 0; % %> You are visitor number <% syn <% synch chron ronize ized( d(thi this) s) { { ou

  • ut.p

t.pri rintl ntln( n(++ ++hit hits); s); } } %> %> since the last time the service was restarted. <p> This page was last updated: <%= ne <%= new w jav java.u a.uti til.D l.Dat ate( e().t ).toLo

  • Loca

caleS leStr trin ing() g() %> %> </body> </html>

15

An Introduction to XML and Web Technologies

The Generated Servlet (1/5) The Generated Servlet (1/5)

package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class hello_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { int hi int hits ts = = 0; 0; private static java.util.Vector _jspx_dependants; public java.util.List getDependants() { return _jspx_dependants; }

16

An Introduction to XML and Web Technologies

The Generated Servlet (2/5) The Generated Servlet (2/5)

public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null;

slide-5
SLIDE 5

5

17

An Introduction to XML and Web Technologies

The Generated Servlet (3/5) The Generated Servlet (3/5)

try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext( this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession();

  • ut = pageContext.getOut();

_jspx_out = out;

18

An Introduction to XML and Web Technologies

The Generated Servlet (4/5) The Generated Servlet (4/5)

respon response. se.add addDa DateH teHea eade der(" r("Exp Expir ires" es", 0) , 0);

  • ut.write("\n");
  • ut.write("<html>

<html><h <hea ead>< d><tit title le>JS >JSP< P</t /titl itle>< e></h /head ead>\n");

  • ut.write("<body>

<body><h <h1> 1>Hel Hello Wo lo World rld!< !</h /h1> 1>\n");

  • ut.write("\n");
  • ut.write("You

You ar are vi e visit sitor nu

  • r numbe

mber "); synchr synchroni

  • nized

zed(t (this his) { out ) { out.pr .prin intln tln(+ (++h +hits its); } ); }

  • ut.write("\n");
  • ut.write("since

since th the e las last t t time t the s serv ervice ice w was as re rest start arted. ed.\n");

  • ut.write("<p>

<p>\n");

  • ut.write("This

This page was was la last st up upda date ted: d: ");

  • ut.print(new

new jav java. a.ut util. il.Dat Date( e().t ).toL

  • Loc
  • cale

aleStr Strin ing() g());

  • ut.write("\n");
  • ut.write("</body

</body>< ></h /html tml>\n");

19

An Introduction to XML and Web Technologies

The Generated Servlet (5/5) The Generated Servlet (5/5)

} catch (Throwable t) { if (!(t instanceof SkipPageException)){

  • ut = _jspx_out;

if (out != null && out.getBufferSize() != 0)

  • ut.clearBuffer();

if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); } } }

20

An Introduction to XML and Web Technologies

<% if (Math.ra if (Math.random() < 0.5) ndom() < 0.5) { %> Have a <b>nice day! <% } else { } else { %> Have a <b>lousy day! <% } %> </b>

Literal Translation Literal Translation

if (Math.random() < 0.5) {

  • ut.write("\n");
  • ut.write(" Have a <b>nice day!\n");

} else {

  • ut.write("\n");
  • ut.write(" Have a <b>lousy day!\n");

}

  • ut.write("</b>\n”);
slide-6
SLIDE 6

6

21

An Introduction to XML and Web Technologies

Problematic Whitespace Problematic Whitespace

<%@ page contentType=”text/plain” %> <%@ page info=”A Tiny Test” %> This is a tiny test This is a tiny test

22

An Introduction to XML and Web Technologies

Advanced Features Advanced Features

XML version of JSP The expression language Tag files JSTL The Model-View-Controller pattern

23

An Introduction to XML and Web Technologies

JSP Pages Are Not XML JSP Pages Are Not XML

<html> <head><title>JSP Color</title></head> <body bgcolor=<%= req <%= reque uest st.ge .getPa tPara ramet meter er(" ("col color"

  • r") %>

) %>> <h1>Hello World!</h1> <%! in <%! int t hit hits = s = 0 0; % %> You are visitor number <% syn <% synch chron ronize ized( d(thi this) s) { { ou

  • ut.p

t.pri rintl ntln( n(++ ++hit hits); s); } } %> %> since the last time the service was restarted. <p> This page was last updated: <%= ne <%= new w jav java.u a.uti til.D l.Dat ate( e().t ).toLo

  • Loca

caleS leStr trin ing() g() %> %> </body> </html>

This page generates HTML, not XHTML <%...%> is not well-formed XML

24

An Introduction to XML and Web Technologies

XML Version of JSP XML Version of JSP

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0" xmlns="http://http://www.w3.org/1999/xhtml"> <jsp:directive.page contentType="text/html"/> <jsp:scriptlet> response.addDateHeader("Expires", 0); </jsp:scriptlet> <html> <head><title>JSP</title></head> <jsp:element name="body"> <jsp:attribute name="bgcolor"> <jsp:expression> request.getParameter("color") </jsp:expression> </jsp:attribute> <h1>Hello World!</h1> <jsp:declaration> int hits = 0; </jsp:declaration> You are visitor number <jsp:scriptlet> synchronized(this) { out.println(++hits); } </jsp:scriptlet> since the last time the service was restarted. <p/> This page was last updated: <jsp:expression> new java.util.Date().toLocaleString() </jsp:expression> </jsp:element> </html> </jsp:root>

  • Uses <jsp:...>
  • No schema seems

to be available

  • No validation
  • f the output
  • No validation
  • f Java code
  • but it’s there...
slide-7
SLIDE 7

7

25

An Introduction to XML and Web Technologies

The Expression Language The Expression Language

We want to avoid explicit Java code in JSP templates The syntax ${ ${exp} exp} may be used in

  • template text
  • attribute values in markup

The expression may access

  • variables in the various scopes
  • implicit objects, such as param

The usual operators are available

26

An Introduction to XML and Web Technologies

An Expression Example An Expression Example

<html> <head><title>Addition</title></head> <body bgcolor="${para ${param. m.co color lor}"> The sum of ${p ${par aram. am.x} x} and ${p ${par aram. am.y} y} is ${pa {para ram.x m.x+p +par aram. am.y} y} </body> </html>

27

An Introduction to XML and Web Technologies

Tag Files Tag Files

Define abstractions as new tags

wrap.tag: <%@ <%@ t tag ag %> %> <%@ <%@ a attr ttrib ibut ute n e name ame=" ="tit title le" " req requir uired ed="t ="tru rue" e" %> %> <html> <head><title>${t ${tit itle} le}</title></head> <body> <jsp:d <jsp:doB

  • Body
  • dy/>

/> </body> </html> <%@ <%@ t tagl aglib ib p pref refix= ix="f "foo"

  • o" t

tagdir dir="/ ="/WE WEB-I B-INF NF/t /tags ags" % " %> <foo: foo:wra wrap title tle="Addition"> The sum of ${param.x} and ${param.y} is ${param.x+param.y} </foo:wr foo:wrap ap>

28

An Introduction to XML and Web Technologies

Content as a Value: A New Image Tag Content as a Value: A New Image Tag

image.tag: <%@ tag %> <jsp:doBody var="src" var="src"/> <img src="http://www.brics.dk/ixwt/images/${src} ${src}"/> <%@ taglib prefix="foo" tagdir="/WEB-INF/tags" %> <foo:image>widget.jpg</foo:image>

slide-8
SLIDE 8

8

29

An Introduction to XML and Web Technologies

Declaring Variables: A Date Context Tag Declaring Variables: A Date Context Tag

date.tag: <%@ tag import="java.util.*" %> <%@ variable n <%@ variable name-given="dat ame-given="date" %> e" %> <%@ variable n <%@ variable name-given="mon ame-given="month" %> th" %> <%@ variable n <%@ variable name-given="yea ame-given="year" %> r" %> <% Calendar cal = new GregorianCalendar(); int date = cal.get(Calendar.DATE); int month = cal.get(Calendar.MONTH)+1; int year = cal.get(Calendar.YEAR); jspContext. jspContext.setAttribute(" setAttribute("date", String. date", String.valueOf(date)) valueOf(date)); jspContext. jspContext.setAttribute(" setAttribute("month", String month", String.valueOf(month .valueOf(month)); )); jspContext. jspContext.setAttribute(" setAttribute("year", String. year", String.valueOf(year)) valueOf(year)); %> <jsp:doBody/>

30

An Introduction to XML and Web Technologies

Using the Date Context Using the Date Context

<%@ taglib <%@ taglib pre prefix="foo" tagd fix="foo" tagdir="/WEB-INF/t ir="/WEB-INF/tags" %> ags" %> <foo:date> <foo:date> In the US today is ${month month}/${date date}/${year year}, but in Europe it is ${date date}/${month month}/${year year}. </foo:date> </foo:date>

31

An Introduction to XML and Web Technologies

Quick Poll Tags (1/2) Quick Poll Tags (1/2)

<%@ <%@ tagl aglib ib pref refix= ix="p "poll

  • ll" ta

" tagdi gdir=" r="/W /WEB- EB-IN INF/ F/tag tags/p s/pol

  • ll" %>

l" %> <po <poll ll:qu :quic ickp kpoll

  • ll ti

titl tle=" e="Qu Quic ickie kies" du s" durat ratio ion= n="36 "3600" 00"> <poll: <poll:qu ques estio tion> n> The question has been set to "${questi question

  • n}".

</poll </poll:q :que uesti stion>

  • n>

<poll: <poll:as ask> k> ${quest question ion}? <select name="vote"> <option>yes <option>no </select> <input type="submit" value="vote"> </poll </poll:a :ask sk>

32

An Introduction to XML and Web Technologies

Quick Poll Tags (2/2) Quick Poll Tags (2/2)

<poll: <poll:vo vote te> You have voted ${vote vote}. </poll </poll:v :vot

  • te>

e> <poll: <poll:re resu sults lts> In favor: ${yes yes}<br> Against: ${no no}<br> Total: ${tota

  • tal}

</poll </poll:r :res esult ults> s> <poll: ll:ti time meout

  • ut>

Sorry, the polls have closed. </poll </poll:t :tim imeou eout> t> </p </pol

  • ll:q

l:qui uick ckpol poll> l>

See the tag files in the book...

slide-9
SLIDE 9

9

33

An Introduction to XML and Web Technologies

Tag Libraries Tag Libraries

Libraries of tags capturing common patterns:

  • pagination of large texts
  • date and times
  • database queries
  • regular expressions
  • HTML scraping
  • bar charts
  • cookies
  • e-mail
  • WML
  • ...

34

An Introduction to XML and Web Technologies

JSTL 1.1 JSTL 1.1

JSP Standard Tag Library covers:

  • assigning to variables
  • writing to the output stream
  • catching exceptions
  • conditionals
  • iterations
  • URL construction
  • string formatting
  • SQL queries
  • XML manipulation

35

An Introduction to XML and Web Technologies

Selecting Some Recipes Selecting Some Recipes

36

An Introduction to XML and Web Technologies

<%@ ta <%@ taglib glib uri uri="http ="http://j ://java. ava.sun.co sun.com/js m/jsp/js p/jstl/cor tl/core" p e" prefi refix="c"% x="c"%> <%@ ta <%@ taglib glib uri uri="http ="http://j ://java. ava.sun.co sun.com/js m/jsp/js p/jstl/xml tl/xml" pr " prefix efix="x"%> ="x"%> <c:imp <c:import url=

  • rt url="http:

"http://ww //www.br w.brics.dk ics.dk/ixw /ixwt/re t/recipes. cipes.xml" xml" var var="xml" ="xml"/> <x:par <x:parse x se xml=" ml="${xml} ${xml}" va " var="r r="recipes ecipes" sc " scope=

  • pe="sessi

"session"/

  • n"/>

<html> <head><title>Select Some Recipes</title></head> <body> <form method="post" action="show.jsp"> <x:f <x:forEa

  • rEach sel

ch select= ect="$re "$recipes/ cipes//rec /recipe" ipe"> <c <c:set :set var=" var="id"> id"><x:o <x:out sel ut select= ect="@id "@id"/></c "/></c:set :set> <input type="checkbox" name="selected" value="${id} ${id}"/> <x <x:out :out selec select="t t="title itle/text( /text()"/> )"/> <br/> </x: </x:forE forEach> ach> <input type="submit" value="Select"/> </form> </body> </html>

Using JSTL for the Menu Using JSTL for the Menu

slide-10
SLIDE 10

10

37

An Introduction to XML and Web Technologies

Using JSTL for the Table (1/3) Using JSTL for the Table (1/3)

<html> <head><title>Nutrition Overview</title></head> <body> <table border="1"> <tr> <td>Title</td> <td>Calories</td> <td>Fat</td> <td>Carbohydrates</td> <td>Protein</td> <td>Alcohol</td> </tr>

38

An Introduction to XML and Web Technologies

Using JSTL for the Table (2/3) Using JSTL for the Table (2/3)

<x:for <x:forEa Each ch se selec lect= t="$r "$rec ecip ipes/ es//re /reci cipe" pe"> <c:f c:for

  • rEa

Each var ch var=" ="id" id" items= ms="${ "${pa param ramVa Valu lues. es.sel selec ected ted}" }"> <x: <x:if if s sele elect= ct="@ "@id= id=$i $id" d"> <tr> <td> <x:o <x:out sel ut selec ect=" t="./ .//t /titl itle"/ e"/> </td> <td align="right"> <x:o <x:out sel ut selec ect=" t="./ .//n /nutr utriti ition

  • n/@c

/@cal alor

  • ries

ies"/> "/> </td> <td align="right"> <x:o <x:out sel ut selec ect=" t="./ .//n /nutr utriti ition

  • n/@f

/@fat at"/ "/> </td> <td align="right"> <x:o <x:out sel ut selec ect=" t="./ .//n /nutr utriti ition

  • n/@c

/@car arbo bohyd hydrat rates es"/> "/> </td>

39

An Introduction to XML and Web Technologies

Using JSTL for the Table (3/3) Using JSTL for the Table (3/3)

<td align="right"> <x:o <x:out ut sel selec ect=" t="./ .//n /nutr utriti ition

  • n/@p

/@pro rote tein" in"/> /> </td> <td align="right"> <x:o <x:out ut sel selec ect=" t="./ .//n /nutr utriti ition

  • n/@a

/@alc lcoh

  • hol"
  • l"/>

/> <x <x:i :if sele elect ct="n ="not

  • t(.

(.//n //nutr utrit ition ion/@ /@al alcoh cohol)

  • l)">

"> 0% </x: </x:if> if> </td> </tr> </x:i </x:if> f> </c: /c:fo forE rEach ach> </ </x:f x:for

  • rEa

Each> ch> </table> </body> </html>

40

An Introduction to XML and Web Technologies

Evaluation of Tags Evaluation of Tags

Make Web applications available to a wider range of developers May be used to structure applications A myriad of domain-specific languages Brittle implementation, hard to debug

slide-11
SLIDE 11

11

41

An Introduction to XML and Web Technologies

The Model The Model-

  • View

View-

  • Controller Pattern

Controller Pattern Model View Controller

encapsulates data representation and business logic provides views to clients handles interactions with clients

42

An Introduction to XML and Web Technologies

The Benefit of MVC The Benefit of MVC

Separation of concerns!

(high cohesion – low coupling)

43

An Introduction to XML and Web Technologies

Using MVC Using MVC

Controller: one servlet View: JSP pages Model: pure Java (e.g. JavaBeans) [Example in the book: Business Card Server]

44

An Introduction to XML and Web Technologies

Summary Summary

JSP templates are HTML/XHTML pages with embedded code The simple expression language is often sufficient in place of full-blown Java code Tag files and libraries allow code to be hidden under a tag-like syntax MVC provides separation of programming and HTML design tasks

slide-12
SLIDE 12

12

45

An Introduction to XML and Web Technologies

Essential Online Resources Essential Online Resources

Sun’s home page for JSP:

http://java.sun.com/products/jsp/

JSTL:

http://java.sun.com/products/jsp/jstl/