• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content


Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this document? Why not share!

11 page-directive






Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    11 page-directive 11 page-directive Document Transcript

    • © 2010 Marty Hall Controlling the Structure g of Generated Servlets: The JSP page Directive Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html p j p Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. 2 Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring, g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your Customized Java EE Training: http://courses.coreservlets.com/ organization. Contact hall@coreservlets.com for details. Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
    • Agenda • Understanding the purpose of the page directive di i • Designating which classes are imported • S Specifying the MIME type of the page if i th t f th • Generating Excel spreadsheets • P ti i ti in sessions Participating i i • Setting the size and behavior of the output buffer • Designating pages to handle JSP errors • Controlling threading behavior 4 Purpose of the page Directive • Give high-level information about the servlet that will result f h ill l from the JSP page h • Can control – Which l Whi h classes are imported i d – What class the servlet extends – What MIME type is generated – How multithreading is handled – If the servlet participates in sessions – The size and behavior of the output buffer – What page handles unexpected errors 5
    • The import Attribute • Format – <%@ page import="package.class" %> – <%@ page import="package.class1,...,package.classN" %> • Purpose – Generate import statements at top of servlet definition • Notes – Although JSP pages can be almost anywhere on server, classes used by JSP pages must be in normal servlet dirs – E.g.: …/WEB-INF/classes or …/WEB INF/classes/directoryMatchingPackage /WEB-INF/classes/ • Always use packages for utilities that will be used by JSP! 6 The Importance of Using Packages • What package will the system think that SomeHelperClass and SomeUtilityClass are S H l Cl dS U ili Cl in? ... public class SomeClass { p public String someMethod(...) { g ( ) SomeHelperClass test = new SomeHelperClass(...); String someString = SomeUtilityClass.someStaticMethod(...); ... } } 7
    • The Importance of Using Packages (Continued) • What package will the system think that SomeHelperClass and SomeUtilityClass are S H l Cl dS U ili Cl in? ... <% SomeHelperClass test = new SomeHelperClass(...); p p ( ); String someString = SomeUtilityClass.someStaticMethod(...); %> 8 The import Attribute: Example (Code) …<H2>The import Attribute</H2> <%@ page import="java.util.*,coreservlets.*" %> <%! private String randomID() { int num = (int)(Math.random()*10000000.0); return("id" + num); } private final String NO_VALUE = "<I>No Value</I>"; %> <% String oldID = CookieUtilities.getCookieValue(request, "userID", NO_VALUE); if (oldID.equals(NO_VALUE)) { q String newID = randomID(); Cookie cookie = new LongLivedCookie("userID", newID); response.addCookie(cookie); } %> This page was accessed on <%= new Date() %> with a userID cookie of <%= oldID %>. 9 </BODY></HTML>
    • The import Attribute: Example (Results) 10 The contentType and pageEncoding Attributes • Format – <%@ page contentType="MIME-Type" %> – <%@ page contentType="MIME-Type; charset=Character-Set charset=Character-Set" %> – <%@ page pageEncoding="Character-Set" %> • Purpose p – Specify the MIME type of the page generated by the servlet that results from the JSP page • N t Notes – Attribute value cannot be computed at request time – See section on response headers for table of the most common MIME types 11
    • Generating Excel Spreadsheets First Last Email Address Marty Hall hall@coreservlets.com hall@coreservlets com Larry Brown brown@coreservlets.com Steve Balmer balmer@ibm.com Scott McNealy mcnealy@microsoft com mcnealy@microsoft.com <%@ page contentType="application/vnd.ms-excel" %> <%-- There are tabs, not spaces, between cols. --%> 12 Conditionally Generating Excel Spreadsheets • You cannot use the contentType attribute for hi f this task, since you cannot make k i k contentType be conditional. – The following always results in the Excel MIME type <% boolean usingExcel = checkUserRequest(request); %> <% if (usingExcel) { %> <%@ page contentType="application/vnd.ms-excel" %> <% } %> • Solution: use a regular JSP scriptlet with response.setContentType tC t tT 13
    • Conditionally Generating Excel Spreadsheets (Code) … <BODY> <CENTER> <H2>Comparing Apples and Oranges</H2> <% String format = request getParameter("format"); request.getParameter("format"); if ((format != null) && (format.equals("excel"))) { response.setContentType("application/vnd.ms-excel"); } %> <TABLE BORDER=1> <TR><TH></TH> <TH>Apples<TH>Oranges <TR><TH>First Quarter <TD>2307 <TD>4706 <TR><TH>Second Quarter<TD>2982 <TD>5104 <TR><TH>Third Quarter <TD>3011 <TD>5220 <TR><TH>Fourth Quarter<TD>3055 <TD>5287 </TABLE> / </CENTER></BODY></HTML> 14 Conditionally Generating Excel Spreadsheets (Results) 15
    • The session Attribute • Format – <%@ page session="true" %> <%-- Default --%> – <%@ page session="false" %> • Purpose – To designate that page not be part of a session • Notes – By default, it is part of a session – Saves memory on server if y have a high-traffic site y you g – All related pages have to do this for it to be useful 16 The isELIgnored Attribute • Format – <%@ page i ELI isELIgnored="false" %> d "f l " – <%@ page isELIgnored="true" %> • Purpose p – To control whether the JSP 2.0 Expression Language (EL) is ignored (true) or evaluated normally (false). • Notes – If your web.xml specifies servlets 2.3 (corresponding to JSP 1.2) or earlier, the default is true • But it is still legal to change the default you are permitted default—you to use this attribute in a JSP-2.0-compliant server regardless of the web.xml version. – If your web.xml specifies servlets 2.4 (corresponding to JSP 2.0) or earlier, the default is false 17
    • The buffer Attribute • Format – <%@ page buffer="sizekb" %> – <%@ page buffer="none" %> • Purpose – To give the size of the buffer used by the out variable • Notes – Buffering lets you set HTTP headers even after some page content has been generated (as long as buffer has not filled up or been explicitly flushed) – Servers are allowed to use a larger size than you ask for, but not a smaller size – Default is system-specific, but must be at least 8kb 18 The errorPage Attribute • Format – <%@ page errorPage="Relative URL" %> • Purpose – S ifi a JSP page th t should process any exceptions Specifies that h ld ti thrown but not caught in the current page • Notes – The exception thrown will be automatically available to the designated error page by means of the "exception" variable – The web.xml file lets you specify application-wide error pages that apply whenever certain exceptions or certain HTTP status codes result. d l • The errorPage attribute is for page-specific error pages 19
    • The isErrorPage Attribute • Format – <%@ page isErrorPage="true" %> – <%@ page isErrorPage="false" %> <%-- Default --%> • Purpose – Indicates whether or not the current page can act as the error page for another JSP page p g p g • Notes – A new predefined variable called exception is created and accessible from error pages – Use this for emergency backup only; explicitly handle as many exceptions as possible • Don't forget to always check query data for missing or malformed values 20 Error Pages: Example …<BODY> <%@ page errorPage="/WEB-INF/SpeedErrors.jsp" %> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE">Computing Speed</TABLE> <%! private double toDouble(String value) { return(Double.parseDouble(value)); } %> <% double furlongs = toDouble(request.getParameter("furlongs")); double fortnights = toDouble(request.getParameter("fortnights")); double speed = furlongs/fortnights; %> <UL> <LI>Distance: <%= furlongs %> furlongs. <LI>Time: <%= fortnights %> fortnights. <LI>Speed: <%= speed %> furlongs per fortnight. </UL> </BODY></HTML> 21
    • Error Pages: Example (Continued) …<BODY> <%@ page isErrorPage="true" %> isErrorPage= true <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Error Computing Speed</TABLE> <P> ComputeSpeed.jsp reported the following error: <I><% <I><%= exception %></I>. This problem occurred in the following place: <PRE> <%@ page import="java.io.*" % %@ po t ja a. o. %> <% exception.printStackTrace(new PrintWriter(out)); %> </PRE> </BODY></HTML> / / 22 Error Pages: Results 23
    • The extends Attribute • Format – <%@ page extends="package.class" %> • Purpose – T specify parent class of servlet that To if t l f l t th t will result from JSP page • Notes – Use with extreme caution – Can prevent system from using high-performance custom superclasses – Typical purpose is to let you extend classes that come from the server vendor (e.g., to support personalization features), not to extend your own classes. 24 The isThreadSafe Attribute • Format – <%@ page isThreadSafe="true" %> <%-- Default --%> – <%@ page isThreadSafe="false" %> • Purpose – To tell the system when your code is not threadsafe, so that the system can p y prevent concurrent access • Normally tells the servlet to implement SingleThreadModel • Notes – Avoid this like the plague • Causes degraded performance in some situations • Causes incorrect results in others 25
    • Example of Non-Threadsafe Code (IDs Must Be Unique) • What's wrong with this code? What s <%! private int idNum = 0; %> <% String userID = "userID" + idNum; out.p out.println("Your ID is " + userID + "."); t ( ou s use . ); idNum = idNum + 1; %> 26 Is isThreadSafe Needed Here? • No! It is not needed. Synchronize normally: <%! private int idNum = 0; %> <% synchronized(this) { y ( ) String userID = "userID" + idNum; out.println("Your ID is " + userID + "."); idNum = idNum + 1; } %> • Better performance in high-traffic environments • isThreadSafe="false" will totally fail if server uses pool-of-instances approach 27
    • Summary • Used frequently – import • Changes the packages imported by the servlet that results from the JSP page – Always use packages for utility classes! – contentType t tT • Specifies MIME type of result • Cannot be used conditionally ( (use <% response.setContentType(...) %> for that) p yp ( ) ) • Used moderately – isELIgnored, session, buffer • Used occasionally – errorPage/isErrorpage – extends • Avoid like the plague – isThreadSafe • Always use explicit synchronization instead 28 © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. 29 Developed and taught by well-known author and developer. At public venues or onsite at your location.