Chapter 10 - Programming Web Applications with JSP - brics

22 downloads 103 Views 164KB Size Report
An Introduction to XML and Web Technologies. The JSP Framework. ▫ Servlets make heavy use of Java and require sophisticated programming. ▫ JSP views a ...
Objectives ƒ How to program Web applications using JSP ƒ How to extend the JSP syntax using tag libraries ƒ The relation to Servlets

An Introduction to XML and Web Technologies

Programming Web Applications with JSP

Anders Møller & Michael I. Schwartzbach © 2006 Addison-Wesley An Introduction to XML and Web Technologies

The JSP Framework

A Tiny Example

ƒ 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

An Introduction to XML and Web Technologies

2

JSP

Hello World!

You are visitor number since the last time the service was restarted.

This page was last updated: 3

An Introduction to XML and Web Technologies

4

1

JSP Templates

JSP Expressions

ƒ A text file with snippets of Java code: • expressions • statements • declarations ƒ JSP directives ƒ Implicitly declared variables: • • • • • • •

Addition The sum of and is

HttpServletRequest request; HttpServletResponse response; HttpSession session; ServletContext application; ServletConfig config; JspWriter out; PageContext pageContext;

An Introduction to XML and Web Technologies

5

JSP Statements

6

JSP Declarations

Numbers



An Introduction to XML and Web Technologies

An Introduction to XML and Web Technologies

Addition The sum of and is

7

An Introduction to XML and Web Technologies

8

2

Be Careful About Declarations (1/2)

Be Careful About Declarations (2/2)

JSP

Hello World!

You are visitor number since the last time the service was restarted.

This page was last updated:

JSP

Hello World!

You are visitor number since the last time the service was restarted.

This page was last updated:

This page counter is always 1... An Introduction to XML and Web Technologies

9

An Introduction to XML and Web Technologies

JSP Directives

10

Other Directives

header.jsp

ƒ ƒ ƒ ƒ ƒ



footer.jsp

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

The sum of and is An Introduction to XML and Web Technologies

11

An Introduction to XML and Web Technologies

12

3

Using Error Pages

Translation into Servlets

Division / equals

JSP

Hello World!

You are visitor number since the last time the service was restarted.

This page was last updated:

Error Something bad happened: An Introduction to XML and Web Technologies

13

The Generated Servlet (1/5)

An Introduction to XML and Web Technologies

14

The Generated Servlet (2/5)

package org.apache.jsp;

public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {

import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*;

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;

public final class hello_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { int hits = 0; private static java.util.Vector _jspx_dependants; public java.util.List getDependants() { return _jspx_dependants; } An Introduction to XML and Web Technologies

15

An Introduction to XML and Web Technologies

16

4

The Generated Servlet (3/5)

The Generated Servlet (4/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(); out = pageContext.getOut(); _jspx_out = out;

An Introduction to XML and Web Technologies

response.addDateHeader("Expires", 0); out.write("\n"); out.write("JSP\n"); out.write("

Hello World!

\n"); out.write("\n"); out.write("You are visitor number "); synchronized(this) { out.println(++hits); } out.write("\n"); out.write("since the last time the service was restarted.\n"); out.write("

\n"); out.write("This page was last updated: "); out.print(new java.util.Date().toLocaleString()); out.write("\n"); out.write("\n");

17

The Generated Servlet (5/5)

18

Literal Translation

} catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); }

Have a nice day! Have a lousy day! if (Math.random() < 0.5) { out.write("\n"); out.write(" Have a nice day!\n"); } else { out.write("\n"); out.write(" Have a lousy day!\n"); } out.write("\n”);

} }

An Introduction to XML and Web Technologies

An Introduction to XML and Web Technologies

19

An Introduction to XML and Web Technologies

20

5

Problematic Whitespace

Advanced Features ƒ ƒ ƒ ƒ ƒ

This is a tiny test

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

This is a tiny test

An Introduction to XML and Web Technologies

21

JSP Pages Are Not XML

XML Version of JSP response.addDateHeader("Expires", 0); JSP request.getParameter("color")

Hello World!

int hits = 0; You are visitor number synchronized(this) { out.println(++hits); } since the last time the service was restarted.

This page was last updated: new java.util.Date().toLocaleString()

JSP Color

Hello World!

You are visitor number since the last time the service was restarted.

This page was last updated:

ƒ This page generates HTML, not XHTML ƒ is not well-formed XML An Introduction to XML and Web Technologies

22

An Introduction to XML and Web Technologies

23

An Introduction to XML and Web Technologies

• Uses • No schema seems to be available • No validation of the output • No validation of Java code • but it’s there... 24

6

The Expression Language

An Expression Example

ƒ We want to avoid explicit Java code in JSP templates

Addition The sum of ${param.x} and ${param.y} is ${param.x+param.y}

ƒ The syntax ${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 25

An Introduction to XML and Web Technologies

Tag Files

26

Content as a Value: A New Image Tag

Define abstractions as new tags

image.tag:

wrap.tag: ${title} The sum of ${param.x} and ${param.y} is ${param.x+param.y}

An Introduction to XML and Web Technologies

An Introduction to XML and Web Technologies

widget.jpg

27

An Introduction to XML and Web Technologies

28

7

Declaring Variables: A Date Context Tag

Using the Date Context

date.tag: An Introduction to XML and Web Technologies

In the US today is ${month}/${date}/${year}, but in Europe it is ${date}/${month}/${year}.

29

Quick Poll Tags (1/2)

An Introduction to XML and Web Technologies

30

Quick Poll Tags (2/2)

The question has been set to "${question}". ${question}? yes no

You have voted ${vote}. In favor: ${yes}
Against: ${no}
Total: ${total} Sorry, the polls have closed.

See the tag files in the book... An Introduction to XML and Web Technologies

31

An Introduction to XML and Web Technologies

32

8

Tag Libraries

JSTL 1.1

ƒ Libraries of tags capturing common patterns: • • • • • • • • • •

ƒ JSP Standard Tag Library covers:

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

An Introduction to XML and Web Technologies

• • • • • • • • • 33

Selecting Some Recipes

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

An Introduction to XML and Web Technologies

34

Using JSTL for the Menu Select Some Recipes


An Introduction to XML and Web Technologies

35

An Introduction to XML and Web Technologies

36

9

Using JSTL for the Table (1/3)

Using JSTL for the Table (2/3)

Nutrition Overview



An Introduction to XML and Web Technologies

37

Using JSTL for the Table (3/3)

38

Evaluation of Tags

Title Calories Fat Carbohydrates Protein Alcohol
0%


An Introduction to XML and Web Technologies

An Introduction to XML and Web Technologies

ƒ 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

39

An Introduction to XML and Web Technologies

40

10

The ModelModel-ViewView-Controller Pattern

The Benefit of MVC

View

Model

Separation of concerns!

provides views to clients

encapsulates data representation and business logic

(high cohesion – low coupling)

Controller

handles interactions with clients An Introduction to XML and Web Technologies

41

42

An Introduction to XML and Web Technologies

Using MVC

Summary

ƒ Controller: one servlet ƒ View: JSP pages ƒ Model: pure Java (e.g. JavaBeans)

ƒ 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

[Example in the book: Business Card Server]

ƒ MVC provides separation of programming and HTML design tasks An Introduction to XML and Web Technologies

43

An Introduction to XML and Web Technologies

44

11

Essential Online Resources ƒ Sun’s home page for JSP: http://java.sun.com/products/jsp/

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

An Introduction to XML and Web Technologies

45

12

Suggest Documents