1 Benefits of JSP Although JSP technically can't do anything - - PDF document

1
SMART_READER_LITE
LIVE PREVIEW

1 Benefits of JSP Although JSP technically can't do anything - - PDF document

Introduzione a Java Server Pages Lucidi tratti da www.corewebprogramming.com The Need for JSP With servlets, it is easy to Read form data Read HTTP request headers Set HTTP status codes and response headers Use cookies


slide-1
SLIDE 1

1

Introduzione a Java Server Pages

Lucidi tratti da www.corewebprogramming.com

The Need for JSP

  • With servlets, it is easy to

– Read form data – Read HTTP request headers – Set HTTP status codes and response headers – Use cookies and session tracking – Share data among servlets – Remember data between requests

  • Much more difficult is to

– Use those println statements to generate HTML – Maintain that HTML

The JSP Framework

  • Idea: Turn Code and HTML inside out

– Use regular HTML for most of page – Mark servlet code with special tags – Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invoked (for each request)

  • Example:

– Suppose the following JSP is in OrderConfirmation.jsp

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

– URL

http://host/OrderConfirmation.jsp?title=Core+Web+Programmi ng

– Result:

slide-2
SLIDE 2

2

Benefits of JSP

  • Although JSP technically can't do anything servlets

can't do, JSP makes it easier to:

– Write HTML – Read and maintain the HTML

  • JSP makes it possible to:

– Use standard HTML development tools – Have different members of your team do the HTML layout and the programming

  • JSP encourages you to

– Separate the (Java) code that creates the content from the (HTML) code that presents it

Example

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

Example Result

  • With default setup, if location was

– http://almaak.usc.edu:8821/examples/jsp/Chapt er20/ Expressions.jsp?testParam=some+data

slide-3
SLIDE 3

3

Most Common Misunderstanding:

Forgetting JSP is Server-Side Technology

  • Very common question

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

  • Why doesn't this question make sense?

– JSP runs entirely on server – It doesn’t change content the browser can handle

  • Similar questions

– How do I put an applet in a JSP page? Answer: send an <APPLET…> tag to the client – How do I put an image in a JSP page? Answer: send an <IMG …> tag to the client – How do I use JavaScript/Acrobat/Shockwave/Etc? Answer: send the appropriate HTML tags

2nd Most Common Misunderstanding: Translation/Request Time Confusion

  • What happens at page translation time?

– JSP constructs get translated into servlet code

  • What happens at request time?

– Servlet code gets executed. No interpretation of JSP

  • ccurs at request time. The original JSP page is ignored

at request time; only the servlet that resulted from it is used

  • When does page translation occur?

– Typically, the first time JSP page is accessed after it is

  • modified. This should never happen to real user

(developers should test all JSP pages they install). – Page translation does not occur for each request

Types of Scripting Elements

  • Expressions

– Format: <%= java expression %> – Evaluated and inserted into the servlet’s output. I.e., results in something like out.println(expression)

  • Scriptlets

– Format: <% code %> – Inserted verbatim into the servlet’s _jspService method (called by service)

  • Declarations

– Format: <%! code %> – Inserted verbatim into the body of the servlet class,

  • utside of any existing methods. Globals for the class.
slide-4
SLIDE 4

4

Expressions: <%= Java Expression %>

  • Result

– Expression evaluated, converted to String, and placed into HTML page at the place it occurred in JSP page – That is, expression placed in _jspService inside out.print

  • Examples

Current time: <%= new java.util.Date() %> Your hostname: <%= request.getRemoteHost() %> Note: the variable request above is the same as the parameter to the doGet or doPost servlet routines. More about these variables later.

JSP/Servlet Correspondence

  • Original JSP

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

  • Possible resulting servlet code

public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter();

  • ut.println("<H1>A Random Number</H1>");
  • ut.println(Math.random());

... }

Example Using JSP Expressions

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

slide-5
SLIDE 5

5

Predefined Variables

  • request

– The HttpServletRequest (1st arg to doGet)

  • response

– The HttpServletResponse (2nd arg to doGet)

  • session

– The HttpSession associated with the request

  • out

– The stream (of type JspWriter) used to send

  • utput to the client associated with the response

Scriptlets: <% Java Code %>

  • Result

– Code is inserted verbatim into servlet's _jspService

  • Two Examples

<% String queryData = request.getQueryString();

  • ut.println("Attached GET data: " + queryData);

%> Or: Attached GET data: <%= request.getQueryString() %> <% response.setContentType("text/plain"); %>

JSP/Servlet Correspondence

  • Original JSP

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

  • Possible resulting servlet code

public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter();

  • ut.println(foo());

bar(); ... }

slide-6
SLIDE 6

6

Example Using JSP Scriptlets

<HTML> <HEAD> <TITLE>Color Testing</TITLE> </HEAD> <% String bgColor = request.getParameter("bgColor"); boolean hasExplicitColor; if (bgColor != null) { hasExplicitColor = true; } else { hasExplicitColor = false; bgColor = "WHITE"; } %> <BODY BGCOLOR="<%= bgColor %>"> <% if (hasExplicitColor) out.println(…); %> …

JSP Scriptlets: Results Declarations: <%! Java Declarations %>

  • Result

– Code is inserted verbatim into servlet's class definition, outside of any existing methods

  • Examples

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

slide-7
SLIDE 7

7

JSP/Servlet Correspondence

  • Original JSP

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

JSP/Servlet Correspondence

  • Possible resulting servlet code

public class xxxx implements HttpJspPage { private String randomHeading() { return("<H2>" + Math.random() + "</H2>"); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter();

  • ut.println("<H1>Some Heading</H1>");
  • ut.println(randomHeading());

... }

Example Using JSP Declarations

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD><TITLE>JSP Declarations</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>JSP Declarations</H1> <%! private int accessCount = 0; %> <H2>Accesses to page since server reboot: <%= ++accessCount %></H2> </BODY> </HTML>

slide-8
SLIDE 8

8

JSP Declarations: Result

  • After 15 total visits by an arbitrary number of

different clients

The import Attribute

  • Format

– <%@ page import="package.class" %> – <%@ page import="package.class1,...,package.classN" %>

  • Purpose

– Generate import statements at top of servlet

Example of import Attribute

... <BODY> <H2>The import Attribute</H2> <%-- JSP page directive --%> <%@ page import="java.util.*,cwp.*" %> <%-- JSP Declaration --%> <%! private String randomID() { int num = (int)(Math.random()*10000000.0); return("id" + num); } private final String NO_VALUE = "<I>No Value</I>"; %>

slide-9
SLIDE 9

9

Example of import Attribute (Continued)

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

Example of import Attribute: Result

  • First access
  • Subsequent

accesses

Background: What Are Beans?

  • Classes that follow certain conventions

– Must have a zero-argument (empty) constructor – Should have no public instance variables (fields) – Persistent values should be accessed through methods called getXxx and setXxx

  • If class has method getTitle that returns a String,

class is said to have a String property named title

  • Boolean properties use isXxx instead of getXxx
  • For more on beans, see

http://java.sun.com/beans/docs/

slide-10
SLIDE 10

10

Basic Bean Use in JSP

  • Format

– <jsp:useBean id="name" class="package.Class" />

  • Purpose

– Allow instantiation of classes without explicit Java syntax

  • Notes

– Simple interpretation: JSP action

<jsp:useBean id="book1" class="cwp.Book" />

can be thought of as equivalent to the scriptlet

<% cwp.Book book1 = new cwp.Book(); %>

– But useBean has two additional features

  • Simplifies setting fields based on incoming

request params

  • Makes it easier to share beans

Accessing Bean Properties

  • Format

– <jsp:getProperty name="name" property="property" />

  • Purpose

– Allow access to bean properties (i.e., calls to getXxx methods) without explicit Java programming language code

  • Notes

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

is equivalent to the following JSP expression

<%= book1.getTitle() %>

Setting Bean Properties: Simple Case

  • Format

– <jsp:setProperty name="name" property="property" value="value" />

  • Purpose

– Allow setting of bean properties (i.e., calls to setXxx methods) without explicit Java code

  • Notes

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

is equivalent to the following scriptlet

<% book1.setTitle("Core Servlets and JSP"); %>