SlideShare a Scribd company logo
1 of 34
Java/J2EE Programming Training
Into to JSP
Page 2Classification: Restricted
Agenda
• The Need for JSP
• The JSP Framework
• Benefits of JSP
• Advantages of JSP Over Competing Technologies
• Setting Up Your Environment
• Invoking Java Code with JSP Scripting Elements
• Uses of JSP Constructs
• Design Strategy: Limit Java Code in JSP Pages
• Basic Syntax
• Types of Scripting Elements
• JSP Expressions
• JSP/Servlet Correspondence
• Predefined Variables
• Controlling the Structure of Generated Servlets
• Purpose of the page Directive
• The import Attribute
• The contentType and page encoding Attributes
Page 3Classification: Restricted
•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
–Get fun, high-paying jobs
•But, it sure is a pain to
–Use those println statements to generate HTML
–Maintain that HTML
The Need for JSP
Page 4Classification: Restricted
•Idea:
–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:
<!DOCTYPE …>
<HTML>
<HEAD>
<TITLE>Order Confirmation</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<H2>Order Confirmation</H2>
Thanks for ordering
<I><%= request.getParameter("title") %></I>!
</BODY></HTML>
The JSP Framework
Page 5Classification: Restricted
•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 tools such as Macromedia DreamWeaver or Adobe GoLive.
–Have different members of your team do the HTML layout than do the Java
programming
•JSP encourages you to
–Separate the (Java) code that creates the content from the (HTML) code that
presents it
Benefits of JSP
Page 6Classification: Restricted
• Versus ASP or ColdFusion
– Better language for dynamic part
– Portable to multiple servers and operating systems
• Versus PHP
– Better language for dynamic part
– Better tool support
• Versus pure servlets
– More convenient to create HTML
– Can use standard tools (e.g., DreamWeaver)
– Divide and conquer
– JSP programmers still need to know
servlet programming
Advantages of JSP Over Competing Technologies
Page 7Classification: Restricted
• Versus Velocity or WebMacro
– Standard
• Versus client-side JavaScript (in browser)
– Capabilities mostly do not overlap with JSP, but
• You control server, not client
• Richer language
• Versus server-side JavaScript
(e.g., LiveWire, BroadVision)
– Richer language
• Versus static HTML
– Dynamic features
– Adding dynamic features no longer
"all or nothing" decision
Advantages of JSP (Continued)
Page 8Classification: Restricted
• Set your CLASSPATH. Not.
• Compile your code. Not.
• Use packages to avoid name conflicts. Not.
• Put JSP page in special directory. Not.
– install_dirwebappsROOT (HTML and JSP -- Tomcat)
install_dirserversdefaultdefault-app (JRun)
• Use special URLs to invoke JSP page. Not.
– Use same URLs as for HTML pages (except for file extensions)
• Caveats
– Previous rules about CLASSPATH, install dirs, etc., still apply to regular
Java classes used by a JSP page
Setting Up Your Environment
Page 9Classification: Restricted
• <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
• <HTML>
• <HEAD>
• <TITLE>JSP Expressions</TITLE>
• <META NAME="keywords"
• CONTENT="JSP,expressions,JavaServer Pages">
• <META NAME="description"
• CONTENT="A quick example of JSP expressions.">
• <LINK REL=STYLESHEET
• HREF="JSP-Styles.css"
• TYPE="text/css">
• </HEAD>
Example
Page 10Classification: Restricted
• <BODY>
• <H2>JSP Expressions</H2>
• <UL>
• <LI>Current time: <%= new java.util.Date() %>
• <LI>Server: <%= application.getServerInfo() %>
• <LI>Session ID: <%= session.getId() %>
• <LI>The <CODE>testParam</CODE> form parameter:
• <%= request.getParameter("testParam") %>
• </UL>
• </BODY></HTML>
Example (Continued)
Page 11Classification: Restricted
• If location was
– C:jakarta-tomcat-xxwebappsROOT
jsp-scriptingExpressions.jsp or
– C:JRun4serversdefaultdefault-eardefault-war
jsp-scriptingExpressions.jsp
• URL would be
– http://localhost/jsp-scripting/Expressions.jsp
Example: Result
Page 12Classification: Restricted
• 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 client (browser) can handle
• Similar questions
– How do I put a normal 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
Most Common Misunderstanding
Forgetting JSP is Server-Side Technology
Page 13Classification: Restricted
• 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 occurs at request
time. The original JSP page is totally 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.
2nd Most Common Misunderstanding
Translation/Request Time Confusion
Invoking Java Code with JSP
Scripting Elements
Page 15Classification: Restricted
• Scripting elements calling servlet code directly
• Scripting elements calling servlet code indirectly (by means of
utility classes)
• Beans
• Servlet/JSP combo (MVC)
• MVC with JSP expression language
• Custom tags
Simple
Application
Complex
Application
Uses of JSP Constructs
Page 16Classification: Restricted
• You have two options
– Put 25 lines of Java code directly in the JSP page
– Put those 25 lines in a separate Java class and put 1 line in the JSP page
that invokes it
• Why is the second option much better?
– Development. You write the separate class in a Java environment (editor
or IDE), not an HTML environment
– Debugging. If you have syntax errors, you see them immediately at
compile time. Simple print statements can be seen.
– Testing. You can write a test routine with a loop that does 10,000 tests
and reapply it after each change.
– Reuse. You can use the same class from multiple pages.
Design Strategy: Limit Java Code in JSP Pages
Page 17Classification: Restricted
• HTML Text
– <H1>Blah</H1>
– Passed through to client. Really turned into servlet code that looks like
• out.print("<H1>Blah</H1>");
• HTML Comments
– <!-- Comment -->
– Same as other HTML: passed through to client
• JSP Comments
– <%-- Comment --%>
– Not sent to client
• To get <% in output, use <%
Basic Syntax
Page 18Classification: Restricted
• Expressions
– Format: <%= expression %>
– Evaluated and inserted into the servlet’s output.
I.e., results in something like out.print(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, outside of any
existing methods
Types of Scripting Elements
Page 19Classification: Restricted
• Format
– <%= 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() %>
• XML-compatible syntax
– <jsp:expression>Java Expression</jsp:expression>
– You cannot mix versions within a single page. You must use XML for entire
page if you use jsp:expression.
JSP Expressions
Page 20Classification: Restricted
• Original JSP
• <H1>A Random Number</H1>
• <%= Math.random() %>
• Representative resulting servlet code
• public void _jspService(HttpServletRequest request,
• HttpServletResponse response)
• throws ServletException, IOException {
• response.setContentType("text/html");
• HttpSession session = request.getSession();
• JspWriter out = response.getWriter();
• out.println("<H1>A Random Number</H1>");
• out.println(Math.random());
• ...
• }
JSP/Servlet Correspondence
Page 21Classification: Restricted
• request
– The HttpServletRequest (1st argument to service/doGet)
• response
– The HttpServletResponse (2nd arg to service/doGet)
• out
– The Writer (a buffered version of type JspWriter) used to send output to
the client
• session
– The HttpSession associated with the request (unless disabled with the
session attribute of the page directive)
• application
– The ServletContext (for sharing data) as obtained via getServletContext().
Predefined Variables
Controlling the Structure of Generated
Servlets: The JSP page Directive
Page 23Classification: Restricted
• Give high-level information about the servlet that will result from the JSP
page
• Can control
– Which classes are imported
– 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
Purpose of the page Directive
Page 24Classification: Restricted
• 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
• Always use packages for utilities that will be used by JSP!
The import Attribute
Page 25Classification: Restricted
• Format
– <%@ page contentType="MIME-Type" %>
– <%@ page contentType="MIME-Type;
charset=Character-Set" %>
– <%@ page pageEncoding="Character-Set" %>
• Purpose
– Specify the MIME type of the page generated by the servlet that results
from the JSP page
• Notes
– Attribute value cannot be computed at request time
– See section on response headers for table of the most common MIME
types
The contentType and page Encoding Attributes
Page 26Classification: Restricted
• 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 you have a high-traffic site
– All related pages have to do this for it to be useful
The session Attribute
Page 27Classification: Restricted
• 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
The buffer Attribute
Page 28Classification: Restricted
• Format
– <%@ page errorPage="Relative URL" %>
• Purpose
– Specifies a JSP page that should process any exceptions 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.
• The errorPage attribute is for page-specific error pages
The error Page Attribute
Page 29Classification: Restricted
• 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
• 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
The is Error Page Attribute
Page 30Classification: Restricted
• …<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>
Error Pages: Example
Page 31Classification: Restricted
• …<BODY>
• <%@ page isErrorPage="true" %>
• <TABLE BORDER=5 ALIGN="CENTER">
• <TR><TH CLASS="TITLE">
• Error Computing Speed</TABLE>
• <P>
• ComputeSpeed.jsp reported the following error:
• <I><%= exception %></I>. This problem occurred in the
• following place:
• <PRE>
• <%@ page import="java.io.*" %>
• <% exception.printStackTrace(new PrintWriter(out)); %>
• </PRE>
• </BODY></HTML>
Error Pages: Example (Continued)
Page 32Classification: Restricted
Error Pages: Results
Page 33Classification: Restricted
• Format
– <%@ page isThreadSafe="true" %> <%-- Default --%>
– <%@ page isThreadSafe="false" %>
• Purpose
– To tell the system when your code is not threadsafe, so that the system
can 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
The isThreadSafe Attribute
Page 34Classification: Restricted
Thank You

More Related Content

What's hot

Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
AkramWaseem
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
Long Nguyen
 

What's hot (20)

Jsp
JspJsp
Jsp
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Web Development Today
Web Development TodayWeb Development Today
Web Development Today
 
Jsp basic
Jsp basicJsp basic
Jsp basic
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
Client and server side scripting
Client and server side scriptingClient and server side scripting
Client and server side scripting
 
Jsp elements
Jsp elementsJsp elements
Jsp elements
 
Client server 01
Client server 01Client server 01
Client server 01
 
A Good PHP Framework For Beginners Like Me!
A Good PHP Framework For Beginners Like Me!A Good PHP Framework For Beginners Like Me!
A Good PHP Framework For Beginners Like Me!
 
Jsp
JspJsp
Jsp
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component DevelopmentEVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
MVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on RailsMVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on Rails
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Metarefresh
MetarefreshMetarefresh
Metarefresh
 
Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.
 

Similar to JSP Part 1

15 expression-language
15 expression-language15 expression-language
15 expression-language
snopteck
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
Adil Jafri
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
divzi1913
 
11 page-directive
11 page-directive11 page-directive
11 page-directive
snopteck
 

Similar to JSP Part 1 (20)

20jsp
20jsp20jsp
20jsp
 
Jsp
JspJsp
Jsp
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Enterprise java unit-3_chapter-1-jsp
Enterprise  java unit-3_chapter-1-jspEnterprise  java unit-3_chapter-1-jsp
Enterprise java unit-3_chapter-1-jsp
 
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...
 
Advance java session 9
Advance java session 9Advance java session 9
Advance java session 9
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Jsp
JspJsp
Jsp
 
servlets and jsp
servlets and jspservlets and jsp
servlets and jsp
 
Project First presentation about introduction to technologies to be used
Project First presentation about introduction to technologies to be usedProject First presentation about introduction to technologies to be used
Project First presentation about introduction to technologies to be used
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
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
 
11 page-directive
11 page-directive11 page-directive
11 page-directive
 
Advance java session 10
Advance java session 10Advance java session 10
Advance java session 10
 
Java .ppt
Java .pptJava .ppt
Java .ppt
 

More from DeeptiJava

More from DeeptiJava (13)

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

JSP Part 1

  • 2. Page 2Classification: Restricted Agenda • The Need for JSP • The JSP Framework • Benefits of JSP • Advantages of JSP Over Competing Technologies • Setting Up Your Environment • Invoking Java Code with JSP Scripting Elements • Uses of JSP Constructs • Design Strategy: Limit Java Code in JSP Pages • Basic Syntax • Types of Scripting Elements • JSP Expressions • JSP/Servlet Correspondence • Predefined Variables • Controlling the Structure of Generated Servlets • Purpose of the page Directive • The import Attribute • The contentType and page encoding Attributes
  • 3. Page 3Classification: Restricted •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 –Get fun, high-paying jobs •But, it sure is a pain to –Use those println statements to generate HTML –Maintain that HTML The Need for JSP
  • 4. Page 4Classification: Restricted •Idea: –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: <!DOCTYPE …> <HTML> <HEAD> <TITLE>Order Confirmation</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <H2>Order Confirmation</H2> Thanks for ordering <I><%= request.getParameter("title") %></I>! </BODY></HTML> The JSP Framework
  • 5. Page 5Classification: Restricted •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 tools such as Macromedia DreamWeaver or Adobe GoLive. –Have different members of your team do the HTML layout than do the Java programming •JSP encourages you to –Separate the (Java) code that creates the content from the (HTML) code that presents it Benefits of JSP
  • 6. Page 6Classification: Restricted • Versus ASP or ColdFusion – Better language for dynamic part – Portable to multiple servers and operating systems • Versus PHP – Better language for dynamic part – Better tool support • Versus pure servlets – More convenient to create HTML – Can use standard tools (e.g., DreamWeaver) – Divide and conquer – JSP programmers still need to know servlet programming Advantages of JSP Over Competing Technologies
  • 7. Page 7Classification: Restricted • Versus Velocity or WebMacro – Standard • Versus client-side JavaScript (in browser) – Capabilities mostly do not overlap with JSP, but • You control server, not client • Richer language • Versus server-side JavaScript (e.g., LiveWire, BroadVision) – Richer language • Versus static HTML – Dynamic features – Adding dynamic features no longer "all or nothing" decision Advantages of JSP (Continued)
  • 8. Page 8Classification: Restricted • Set your CLASSPATH. Not. • Compile your code. Not. • Use packages to avoid name conflicts. Not. • Put JSP page in special directory. Not. – install_dirwebappsROOT (HTML and JSP -- Tomcat) install_dirserversdefaultdefault-app (JRun) • Use special URLs to invoke JSP page. Not. – Use same URLs as for HTML pages (except for file extensions) • Caveats – Previous rules about CLASSPATH, install dirs, etc., still apply to regular Java classes used by a JSP page Setting Up Your Environment
  • 9. Page 9Classification: Restricted • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> • <HTML> • <HEAD> • <TITLE>JSP Expressions</TITLE> • <META NAME="keywords" • CONTENT="JSP,expressions,JavaServer Pages"> • <META NAME="description" • CONTENT="A quick example of JSP expressions."> • <LINK REL=STYLESHEET • HREF="JSP-Styles.css" • TYPE="text/css"> • </HEAD> Example
  • 10. Page 10Classification: Restricted • <BODY> • <H2>JSP Expressions</H2> • <UL> • <LI>Current time: <%= new java.util.Date() %> • <LI>Server: <%= application.getServerInfo() %> • <LI>Session ID: <%= session.getId() %> • <LI>The <CODE>testParam</CODE> form parameter: • <%= request.getParameter("testParam") %> • </UL> • </BODY></HTML> Example (Continued)
  • 11. Page 11Classification: Restricted • If location was – C:jakarta-tomcat-xxwebappsROOT jsp-scriptingExpressions.jsp or – C:JRun4serversdefaultdefault-eardefault-war jsp-scriptingExpressions.jsp • URL would be – http://localhost/jsp-scripting/Expressions.jsp Example: Result
  • 12. Page 12Classification: Restricted • 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 client (browser) can handle • Similar questions – How do I put a normal 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 Most Common Misunderstanding Forgetting JSP is Server-Side Technology
  • 13. Page 13Classification: Restricted • 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 occurs at request time. The original JSP page is totally 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. 2nd Most Common Misunderstanding Translation/Request Time Confusion
  • 14. Invoking Java Code with JSP Scripting Elements
  • 15. Page 15Classification: Restricted • Scripting elements calling servlet code directly • Scripting elements calling servlet code indirectly (by means of utility classes) • Beans • Servlet/JSP combo (MVC) • MVC with JSP expression language • Custom tags Simple Application Complex Application Uses of JSP Constructs
  • 16. Page 16Classification: Restricted • You have two options – Put 25 lines of Java code directly in the JSP page – Put those 25 lines in a separate Java class and put 1 line in the JSP page that invokes it • Why is the second option much better? – Development. You write the separate class in a Java environment (editor or IDE), not an HTML environment – Debugging. If you have syntax errors, you see them immediately at compile time. Simple print statements can be seen. – Testing. You can write a test routine with a loop that does 10,000 tests and reapply it after each change. – Reuse. You can use the same class from multiple pages. Design Strategy: Limit Java Code in JSP Pages
  • 17. Page 17Classification: Restricted • HTML Text – <H1>Blah</H1> – Passed through to client. Really turned into servlet code that looks like • out.print("<H1>Blah</H1>"); • HTML Comments – <!-- Comment --> – Same as other HTML: passed through to client • JSP Comments – <%-- Comment --%> – Not sent to client • To get <% in output, use <% Basic Syntax
  • 18. Page 18Classification: Restricted • Expressions – Format: <%= expression %> – Evaluated and inserted into the servlet’s output. I.e., results in something like out.print(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, outside of any existing methods Types of Scripting Elements
  • 19. Page 19Classification: Restricted • Format – <%= 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() %> • XML-compatible syntax – <jsp:expression>Java Expression</jsp:expression> – You cannot mix versions within a single page. You must use XML for entire page if you use jsp:expression. JSP Expressions
  • 20. Page 20Classification: Restricted • Original JSP • <H1>A Random Number</H1> • <%= Math.random() %> • Representative resulting servlet code • public void _jspService(HttpServletRequest request, • HttpServletResponse response) • throws ServletException, IOException { • response.setContentType("text/html"); • HttpSession session = request.getSession(); • JspWriter out = response.getWriter(); • out.println("<H1>A Random Number</H1>"); • out.println(Math.random()); • ... • } JSP/Servlet Correspondence
  • 21. Page 21Classification: Restricted • request – The HttpServletRequest (1st argument to service/doGet) • response – The HttpServletResponse (2nd arg to service/doGet) • out – The Writer (a buffered version of type JspWriter) used to send output to the client • session – The HttpSession associated with the request (unless disabled with the session attribute of the page directive) • application – The ServletContext (for sharing data) as obtained via getServletContext(). Predefined Variables
  • 22. Controlling the Structure of Generated Servlets: The JSP page Directive
  • 23. Page 23Classification: Restricted • Give high-level information about the servlet that will result from the JSP page • Can control – Which classes are imported – 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 Purpose of the page Directive
  • 24. Page 24Classification: Restricted • 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 • Always use packages for utilities that will be used by JSP! The import Attribute
  • 25. Page 25Classification: Restricted • Format – <%@ page contentType="MIME-Type" %> – <%@ page contentType="MIME-Type; charset=Character-Set" %> – <%@ page pageEncoding="Character-Set" %> • Purpose – Specify the MIME type of the page generated by the servlet that results from the JSP page • Notes – Attribute value cannot be computed at request time – See section on response headers for table of the most common MIME types The contentType and page Encoding Attributes
  • 26. Page 26Classification: Restricted • 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 you have a high-traffic site – All related pages have to do this for it to be useful The session Attribute
  • 27. Page 27Classification: Restricted • 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 The buffer Attribute
  • 28. Page 28Classification: Restricted • Format – <%@ page errorPage="Relative URL" %> • Purpose – Specifies a JSP page that should process any exceptions 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. • The errorPage attribute is for page-specific error pages The error Page Attribute
  • 29. Page 29Classification: Restricted • 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 • 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 The is Error Page Attribute
  • 30. Page 30Classification: Restricted • …<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> Error Pages: Example
  • 31. Page 31Classification: Restricted • …<BODY> • <%@ page isErrorPage="true" %> • <TABLE BORDER=5 ALIGN="CENTER"> • <TR><TH CLASS="TITLE"> • Error Computing Speed</TABLE> • <P> • ComputeSpeed.jsp reported the following error: • <I><%= exception %></I>. This problem occurred in the • following place: • <PRE> • <%@ page import="java.io.*" %> • <% exception.printStackTrace(new PrintWriter(out)); %> • </PRE> • </BODY></HTML> Error Pages: Example (Continued)
  • 33. Page 33Classification: Restricted • Format – <%@ page isThreadSafe="true" %> <%-- Default --%> – <%@ page isThreadSafe="false" %> • Purpose – To tell the system when your code is not threadsafe, so that the system can 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 The isThreadSafe Attribute