SlideShare a Scribd company logo
© 2010 Marty Hall
Controlling the Structureg
of Generated Servlets:
The JSP page DirectiveThe JSP page Directive
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
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.
Developed and taught by well-known author and developer. At public venues or onsite at your location.2
p j p
© 2010 Marty Hall
For live Java EE training, please see training courses
at http://courses.coreservlets.com/.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
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.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Servlets and JSP, and this tutorial. Available at public
venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
Agenda
• Understanding the purpose of the page
di idirective
• Designating which classes are imported
S if i th MIME t f th• Specifying the MIME type of the page
• Generating Excel spreadsheets
P ti i ti i i• Participating in sessions
• Setting the size and behavior of the output
bufferbuffer
• Designating pages to handle JSP errors
• Controlling threading behavior• Controlling threading behavior
4
Purpose of the page Directive
• Give high-level information about the servlet
h ill l f h JSPthat will result from the JSP page
• Can control
Whi h l i d– Which classes are imported
– What class the servlet extends
– What MIME type is generatedWhat 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• Purpose
– Generate import statements at top of servlet definition
• Notes• 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/directoryMatchingPackage
• Always use packages for utilities that will be used by JSP!
6
The Importance of Using
PackagesPackages
• What package will the system think that
S H l Cl d S U ili ClSomeHelperClass and SomeUtilityClass are
in?
...
public class SomeClass {
public String someMethod(...) {p g ( ) {
SomeHelperClass test = new SomeHelperClass(...);
String someString =
SomeUtilityClass.someStaticMethod(...);
...
}}
}
7
The Importance of Using
Packages (Continued)Packages (Continued)
• What package will the system think that
S H l Cl d S U ili ClSomeHelperClass and SomeUtilityClass are
in?
...
<%
SomeHelperClass test = new SomeHelperClass(...);p p ( );
String someString =
SomeUtilityClass.someStaticMethod(...);
%>
8
The import Attribute: Example
(Code)(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 %>.
</BODY></HTML>9
The import Attribute: Example
(Results)(Results)
10
The contentType and
pageEncoding AttributespageEncoding Attributes
• Format
– <%@ page contentType="MIME-Type" %>
– <%@ page contentType="MIME-Type;
charset=Character-Set" %>charset=Character-Set %>
– <%@ page pageEncoding="Character-Set" %>
• Purposep
– 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– 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 comMarty Hall hall@coreservlets.com
Larry Brown brown@coreservlets.com
Steve Balmer balmer@ibm.com
Scott McNealy mcnealy@microsoft comScott McNealy mcnealy@microsoft.com
<%@ page contentType="application/vnd.ms-excel" %>
<%-- There are tabs, not spaces, between cols. --%>
12
Conditionally Generating Excel
SpreadsheetsSpreadsheets
• You cannot use the contentType attribute
f hi k i kfor this task, since you cannot make
contentType be conditional.
The following always results in the Excel MIME type– 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
tC t tTresponse.setContentType
13
Conditionally Generating Excel
Spreadsheets (Code)Spreadsheets (Code)
…
<BODY>
<CENTER>
<H2>Comparing Apples and Oranges</H2>
<%
String format = request getParameter("format");String 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>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)Spreadsheets (Results)
15
The session Attribute
• Format
– <%@ page session="true" %> <%-- Default --%>
– <%@ page session="false" %>
Purpose• Purpose
– To designate that page not be part of a session
• Notes• Notes
– By default, it is part of a session
– Saves memory on server if you have a high-traffic sitey y g
– All related pages have to do this for it to be useful
16
The isELIgnored Attribute
• Format
<%@ i ELI d "f l " %>– <%@ page isELIgnored="false" %>
– <%@ page isELIgnored="true" %>
• Purposep
– To control whether the JSP 2.0 Expression Language
(EL) is ignored (true) or evaluated normally (false).
• Notes• 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• But it is still legal to change the default—you are permitted
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 toIf 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• Purpose
– To give the size of the buffer used by the out variable
• Notes• 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 sizebut 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 JSP th t h ld ti– Specifies a JSP page that should process any exceptions
thrown but not caught in the current page
• NotesNotes
– The exception thrown will be automatically available to
the designated error page by means of the "exception"
variablevariable
– The web.xml file lets you specify application-wide error
pages that apply whenever certain exceptions or certain
HTTP d lHTTP status codes result.
• The errorPage attribute is for page-specific error pages
19
The isErrorPage Attribute
• Format
– <%@ page isErrorPage="true" %>
– <%@ page isErrorPage="false" %> <%-- Default --%>
Purpose• Purpose
– Indicates whether or not the current page can act as the
error page for another JSP pagep 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 possiblemany 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)(Continued)
…<BODY>
<%@ page isErrorPage="true" %><%@ page isErrorPage= true %>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
Error Computing Speed</TABLE>Error Computing Speed</TABLE>
<P>
ComputeSpeed.jsp reported the following error:
<I><%= exception %></I>. This problem occurred in the<I><% exception %></I>. This problem occurred in the
following place:
<PRE>
<%@ page import="java.io.*" %>%@ page 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 if t l f l t th t– To specify parent class of servlet that
will result from JSP page
• NotesNotes
– 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 personalizationfrom 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• Purpose
– To tell the system when your code is not threadsafe, so
that the system can prevent concurrent accessy p
• Normally tells the servlet to implement SingleThreadModel
• Notes
– Avoid this like the plague
• Causes degraded performance in some situations
• Causes incorrect results in othersCauses incorrect results in others
25
Example of Non-Threadsafe
Code (IDs Must Be Unique)Code (IDs Must Be Unique)
• What's wrong with this code?What s wrong with this code?
<%! private int idNum = 0; %>
<%
String userID = "userID" + idNum;
out.println("Your ID is " + userID + ".");out.p 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;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– import
• Changes the packages imported by the servlet that results from
the JSP page
– Always use packages for utility classes!
t tT– contentType
• Specifies MIME type of result
• Cannot be used conditionally
(use <% response.setContentType(...) %> for that)( p yp ( ) )
• Used moderately
– isELIgnored, session, buffer
• Used occasionallyUsed occasionally
– errorPage/isErrorpage
– extends
• Avoid like the plagueAvoid 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.
Developed and taught by well-known author and developer. At public venues or onsite at your location.29

More Related Content

What's hot (20)

Jsp Slides
Jsp SlidesJsp Slides
Jsp Slides
 
Ch. 9 jsp standard tag library
Ch. 9 jsp standard tag libraryCh. 9 jsp standard tag library
Ch. 9 jsp standard tag library
 
Jsp
JspJsp
Jsp
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
19servlets
19servlets19servlets
19servlets
 
Java server pages
Java server pagesJava server pages
Java server pages
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Ch. 8 script free pages
Ch. 8 script free pagesCh. 8 script free pages
Ch. 8 script free pages
 
Jstl
JstlJstl
Jstl
 
Being a jsp
Being a jsp     Being a jsp
Being a jsp
 
Ch. 7 beeing a jsp
Ch. 7 beeing a jsp     Ch. 7 beeing a jsp
Ch. 7 beeing a jsp
 
Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorial
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
T5 Oli Aro
T5 Oli AroT5 Oli Aro
T5 Oli Aro
 
Csajsp Chapter15
Csajsp Chapter15Csajsp Chapter15
Csajsp Chapter15
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 

Viewers also liked

07 cookies
07 cookies07 cookies
07 cookiessnopteck
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPsKind of Digital
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
04 request-headers
04 request-headers04 request-headers
04 request-headerssnopteck
 

Viewers also liked (7)

07 cookies
07 cookies07 cookies
07 cookies
 
03 form-data
03 form-data03 form-data
03 form-data
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPs
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
13 java beans
13 java beans13 java beans
13 java beans
 
04 request-headers
04 request-headers04 request-headers
04 request-headers
 

Similar to 11 page-directive

Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Ayes Chinmay
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server PageVipin Yadav
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
 
Server side development on java server pages
Server side development on java server pagesServer side development on java server pages
Server side development on java server pagesvinitasharma749430
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)Fahad Golra
 
Servlet., tomcat server, implicit jsp object
Servlet., tomcat server, implicit jsp objectServlet., tomcat server, implicit jsp object
Servlet., tomcat server, implicit jsp objectADITYADIXIT974283
 
Core web application development
Core web application developmentCore web application development
Core web application developmentBahaa Farouk
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...MathivananP4
 

Similar to 11 page-directive (20)

JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 
Jsp
JspJsp
Jsp
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
Server side development on java server pages
Server side development on java server pagesServer side development on java server pages
Server side development on java server pages
 
Jsp
JspJsp
Jsp
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
Servlet., tomcat server, implicit jsp object
Servlet., tomcat server, implicit jsp objectServlet., tomcat server, implicit jsp object
Servlet., tomcat server, implicit jsp object
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Jsp
JspJsp
Jsp
 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Core web application development
Core web application developmentCore web application development
Core web application development
 
Jsp basic
Jsp basicJsp basic
Jsp basic
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
 
Jsp
JspJsp
Jsp
 

More from snopteck

08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
01 web-apps
01 web-apps01 web-apps
01 web-appssnopteck
 

More from snopteck (7)

10 jdbc
10 jdbc10 jdbc
10 jdbc
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
14 mvc
14 mvc14 mvc
14 mvc
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
01 web-apps
01 web-apps01 web-apps
01 web-apps
 

Recently uploaded

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Alison B. Lowndes
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...Elena Simperl
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 

11 page-directive

  • 1. © 2010 Marty Hall Controlling the Structureg of Generated Servlets: The JSP page DirectiveThe JSP page Directive Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html 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. Developed and taught by well-known author and developer. At public venues or onsite at your location.2 p j p © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/.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 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. Developed and taught by well-known author and developer. At public venues or onsite at your location. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact hall@coreservlets.com for details.
  • 2. Agenda • Understanding the purpose of the page di idirective • Designating which classes are imported S if i th MIME t f th• Specifying the MIME type of the page • Generating Excel spreadsheets P ti i ti i i• Participating in sessions • Setting the size and behavior of the output bufferbuffer • Designating pages to handle JSP errors • Controlling threading behavior• Controlling threading behavior 4 Purpose of the page Directive • Give high-level information about the servlet h ill l f h JSPthat will result from the JSP page • Can control Whi h l i d– Which classes are imported – What class the servlet extends – What MIME type is generatedWhat 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
  • 3. The import Attribute • Format – <%@ page import="package.class" %> – <%@ page import="package.class1,...,package.classN" %> • Purpose• Purpose – Generate import statements at top of servlet definition • Notes• 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/directoryMatchingPackage • Always use packages for utilities that will be used by JSP! 6 The Importance of Using PackagesPackages • What package will the system think that S H l Cl d S U ili ClSomeHelperClass and SomeUtilityClass are in? ... public class SomeClass { public String someMethod(...) {p g ( ) { SomeHelperClass test = new SomeHelperClass(...); String someString = SomeUtilityClass.someStaticMethod(...); ... }} } 7
  • 4. The Importance of Using Packages (Continued)Packages (Continued) • What package will the system think that S H l Cl d S U ili ClSomeHelperClass and SomeUtilityClass are in? ... <% SomeHelperClass test = new SomeHelperClass(...);p p ( ); String someString = SomeUtilityClass.someStaticMethod(...); %> 8 The import Attribute: Example (Code)(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 %>. </BODY></HTML>9
  • 5. The import Attribute: Example (Results)(Results) 10 The contentType and pageEncoding AttributespageEncoding Attributes • Format – <%@ page contentType="MIME-Type" %> – <%@ page contentType="MIME-Type; charset=Character-Set" %>charset=Character-Set %> – <%@ page pageEncoding="Character-Set" %> • Purposep – 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– See section on response headers for table of the most common MIME types 11
  • 6. Generating Excel Spreadsheets First Last Email Address Marty Hall hall@coreservlets comMarty Hall hall@coreservlets.com Larry Brown brown@coreservlets.com Steve Balmer balmer@ibm.com Scott McNealy mcnealy@microsoft comScott McNealy mcnealy@microsoft.com <%@ page contentType="application/vnd.ms-excel" %> <%-- There are tabs, not spaces, between cols. --%> 12 Conditionally Generating Excel SpreadsheetsSpreadsheets • You cannot use the contentType attribute f hi k i kfor this task, since you cannot make contentType be conditional. The following always results in the Excel MIME type– 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 tC t tTresponse.setContentType 13
  • 7. Conditionally Generating Excel Spreadsheets (Code)Spreadsheets (Code) … <BODY> <CENTER> <H2>Comparing Apples and Oranges</H2> <% String format = request getParameter("format");String 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>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)Spreadsheets (Results) 15
  • 8. The session Attribute • Format – <%@ page session="true" %> <%-- Default --%> – <%@ page session="false" %> Purpose• Purpose – To designate that page not be part of a session • Notes• Notes – By default, it is part of a session – Saves memory on server if you have a high-traffic sitey y g – All related pages have to do this for it to be useful 16 The isELIgnored Attribute • Format <%@ i ELI d "f l " %>– <%@ page isELIgnored="false" %> – <%@ page isELIgnored="true" %> • Purposep – To control whether the JSP 2.0 Expression Language (EL) is ignored (true) or evaluated normally (false). • Notes• 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• But it is still legal to change the default—you are permitted 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 toIf your web.xml specifies servlets 2.4 (corresponding to JSP 2.0) or earlier, the default is false 17
  • 9. The buffer Attribute • Format – <%@ page buffer="sizekb" %> – <%@ page buffer="none" %> Purpose• Purpose – To give the size of the buffer used by the out variable • Notes• 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 sizebut 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 JSP th t h ld ti– Specifies a JSP page that should process any exceptions thrown but not caught in the current page • NotesNotes – The exception thrown will be automatically available to the designated error page by means of the "exception" variablevariable – The web.xml file lets you specify application-wide error pages that apply whenever certain exceptions or certain HTTP d lHTTP status codes result. • The errorPage attribute is for page-specific error pages 19
  • 10. The isErrorPage Attribute • Format – <%@ page isErrorPage="true" %> – <%@ page isErrorPage="false" %> <%-- Default --%> Purpose• Purpose – Indicates whether or not the current page can act as the error page for another JSP pagep 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 possiblemany 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
  • 11. Error Pages: Example (Continued)(Continued) …<BODY> <%@ page isErrorPage="true" %><%@ page isErrorPage= true %> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Error Computing Speed</TABLE>Error Computing Speed</TABLE> <P> ComputeSpeed.jsp reported the following error: <I><%= exception %></I>. This problem occurred in the<I><% exception %></I>. This problem occurred in the following place: <PRE> <%@ page import="java.io.*" %>%@ page po t ja a. o. % <% exception.printStackTrace(new PrintWriter(out)); %> </PRE> </BODY></HTML>/ / 22 Error Pages: Results 23
  • 12. The extends Attribute • Format – <%@ page extends="package.class" %> • Purpose T if t l f l t th t– To specify parent class of servlet that will result from JSP page • NotesNotes – 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 personalizationfrom 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• Purpose – To tell the system when your code is not threadsafe, so that the system can prevent concurrent accessy p • Normally tells the servlet to implement SingleThreadModel • Notes – Avoid this like the plague • Causes degraded performance in some situations • Causes incorrect results in othersCauses incorrect results in others 25
  • 13. Example of Non-Threadsafe Code (IDs Must Be Unique)Code (IDs Must Be Unique) • What's wrong with this code?What s wrong with this code? <%! private int idNum = 0; %> <% String userID = "userID" + idNum; out.println("Your ID is " + userID + ".");out.p 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;idNum = idNum + 1; } %> • Better performance in high-traffic environments • isThreadSafe="false" will totally fail if server uses pool-of-instances approach 27
  • 14. Summary • Used frequently import– import • Changes the packages imported by the servlet that results from the JSP page – Always use packages for utility classes! t tT– contentType • Specifies MIME type of result • Cannot be used conditionally (use <% response.setContentType(...) %> for that)( p yp ( ) ) • Used moderately – isELIgnored, session, buffer • Used occasionallyUsed occasionally – errorPage/isErrorpage – extends • Avoid like the plagueAvoid 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. Developed and taught by well-known author and developer. At public venues or onsite at your location.29