SlideShare a Scribd company logo
JSPs Lecture 8 cs193i – Internet Technologies Summer 2004 Stanford University
Administrative Stuff HW#3 due today HW#4 due August 11 All local SCPD students must come to campus for final exam
Why JSPs? Goal: Create dynamic web content (HTML, XML, ...) for a Web Application Goal: Make it easier/cleaner to mix static HTML parts with dynamic Java servlet code JSP specification ver. 2.0 Java Servlet specification ver. 2.4
JSP/ASP/PHP vs CGI/Servlets CGI & Servlets --  Mostly Code  with some HTML via print & out.println JSP/ASP/PHP -- Mostly HTML, with code snippets thrown in No explicit recompile Great for small problems Easier to program Not for large computations
What is JSP? Mostly HTML page , with extension .jsp Include JSP tags  to enable dynamic content creation Translation: JSP -> Servlet class Compiled at Request time (first request, a little slow) Execution: Request -> JSP Servlet's service method
What is a JSP? <html> <body> <jsp:useBean.../> <jsp:getProperty.../> <jsp:getProperty.../> </body> </html>
Advantages Code -- Computation HTML -- Presentation Separation of Roles Developers Content Authors/Graphic Designers/Web Masters Supposed to be cheaper... but not really...
Model-View-Controller A Design Pattern Controller -- receives user interface input, updates data model Model -- represents state of the world (e.g. shopping cart) View -- looks at model and generates an appropriate user interface to present the data and allow for further input
Model-View-Controller Bean JSP Servlet Controller View Model
public class OrderServlet … { public void dogGet(…){ if(isOrderValid(req)){ saveOrder(req); … out.println(“<html><body>”); … } private void isOrderValid(…){ … } private void saveOrder(…){ … } } Public class OrderServlet … { public void doGet(…){ … if(bean.isOrderValid(…)){ bean.saveOrder(req); … forward(“conf.jsp”); } } <html> <body> <c:forEach items=“${order}”> … </c:forEach> </body> </html> isOrderValid() saveOrder() ------------------ private state Pure Servlet Servlet JSP Java Bean
JSP Big Picture Server w/ JSP Container GET /hello.jsp <html>Hello!</html> Hello.jsp HelloServlet.java HelloServlet.class
A JSP File
<%@ Directive %> <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
<%-- JSPComment --> <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
Template Text <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 =   <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
<%= expr > Java expression whose output is spliced into HTML <%= userInfo.getUserName() %> <%= 1 + 1 %> <%= new java.util.Date() %> Translated to out.println(userInfo.getUserName()) ... WARNING: Old School JSP! The new way is introduced after break.... you may use either, but Old School JSP is used sparingly nowadays
<% code %> Scriptlet: Add a whole block of code to JSP...   passed through to JSP's service method
<%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <%@ page import=&quot;java.util.*&quot; %> <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> <% // Create an ArrayList with test data ArrayList list = new ArrayList( ); Map author1 = new HashMap( ); author1.put(&quot;name&quot;, &quot;John Irving&quot;); author1.put(&quot;id&quot;, new Integer(1)); list.add(author1); Map author2 = new HashMap( ); author2.put(&quot;name&quot;, &quot;William Gibson&quot;); author2.put(&quot;id&quot;, new Integer(2)); list.add(author2); Map author3 = new HashMap( ); author3.put(&quot;name&quot;, &quot;Douglas Adams&quot;); author3.put(&quot;id&quot;, new Integer(3)); list.add(author3); pageContext.setAttribute(&quot;authors&quot;, list); %> <html> <head> <title>Search result: Authors</title> </head> <body bgcolor=&quot;white&quot;> Here are all authors matching your search critera: <table> <th>Name</th> <th>Id</th> <c:forEach items=“${ authors }” var=“current”>
<%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <html> <head> <title>Browser Check</title> </head> <body bgcolor=&quot;white&quot;> <% String userAgent = request.getHeader(&quot;User-Agent&quot;); if (userAgent.indexOf(&quot;MSIE&quot;) != -1) { %> You're using Internet Explorer. <% } else if (userAgent.indexOf(&quot;Mozilla&quot;) != -1) { %> You're probably using Netscape. <% } else { %> You're using a browser I don't know about. <% } %> </body> </html>
<%! decl > Turned into an instance variable for the servlet What did I tell you about instance variables & multithreaded servlets? Serious Race Conditions Here!
<%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <%! int globalCounter = 0; %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor=&quot;white&quot;> This page has been visited: <%= ++globalCounter %> times. <p> <% int localCounter = 0; %> This counter never increases its value: <%= ++localCounter %> </body> </html> Declarations have serious multithreading issues!
<%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <%! int globalCounter = 0; %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor=&quot;white&quot;> This page has been visited: <%= ++globalCounter %> times. <p> <% int localCounter = 0; %> This counter never increases its value:  <%= ++localCounter %> </body> </html> Not saved between requests...!
<%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <%@ page import=&quot;java.util.Date&quot; %> <%! int globalCounter = 0; java.util.Date startDate; public void  jspInit ( ) { startDate = new java.util.Date( ); } public void  jspDestroy ( ) { ServletContext context = getServletConfig().getServletContext( ); context.log(&quot;test.jsp was visited &quot; + globalCounter + &quot; times between &quot; + startDate + &quot; and &quot; + (new Date( ))); } %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor=&quot;white&quot;> This page has been visited:  <%= ++globalCounter %>  times since  <%= startDate %> . </body> </html> No real need anymore, since we don't use instance variables!
<jsp:include …> <jsp:include page=&quot;trailer.html“ flush=&quot;true&quot; />
Five Minute Break
Big Picture – Web Apps Database Legacy Applications Java Applications Web Service Other…? End User #1 End User #2 Web Server (Servlets/JSP)
Invoking Dynamic Code (from JSPs) Call Java Code Directly (Expressions, Declarations, Scriptlets) Call Java Code Indirectly (Separate Utility Classes, JSP calls methods) Use Beans (jsp:useBean, jsp:getProperty, jsp:setProperty) Use MVC architecture (servlet, JSP, JavaBean) Use JSP expression Language (shorthand to access bean properties, etc) Use custom tags (Develop tag handler classes; use xml-like custom tags)
Invoking Dynamic Code (from JSPs) Call Java Code Directly (Expressions, Declarations, Scriptlets) Call Java Code Indirectly (Separate Utility Classes, JSP calls methods) Use Beans (jsp:useBean, jsp:getProperty, jsp:setProperty) Use MVC architecture (servlet, JSP, JavaBean) Use JSP expression Language (shorthand to access bean properties, etc) Use custom tags (Develop tag handler classes; use xml-like custom tags) Simple Application or Small Development Team Complex Application or Big Development Team
Servlets and JSPs Core Servlets and JavaServer Pages, 2nd Edition, Volumes 1 & 2. Marty Hall & Larry Brown
Java Beans Purpose: Store Data Simple Object, requires no argument constructor Properties accessible via get & set methods
Java Beans For a &quot;foo&quot; property, a java bean will respond to Type getFoo() void setFoo(Type foo) For a boolean &quot;bar&quot; property, a java bean will respond to boolean isBar() void setBar(boolean bar)
Java Bean int getCount() void setCount(int c) String getS() void setS(String s) int[] getFoo() void setFoo(int[] f) int count; String s; int[] foo;
 
// MagicBean.java /* A simple bean that contains a single * &quot;magic&quot; string. */ public class MagicBean { private String magic; public MagicBean(String string) { magic = string; } public MagicBean() { magic = &quot;Woo Hoo&quot;; // default magic string } public String getMagic() { return(magic); } public void setMagic(String magic) { this.magic = magic; } }
Java Beans <jsp:useBean id=&quot;myBean&quot; class=&quot;com.foo.MyBean“ scope=&quot;request&quot;/> <jsp:getProperty name=&quot;myBean“ property=&quot;lastChanged&quot; /> <jsp:setProperty name=&quot;myBean“ property=&quot;lastChanged&quot; value=&quot;<%= new Date()%>&quot;/> Example <jsp:usebean id=&quot;bean&quot; class=&quot;MagicBean&quot; /> <jsp:getProperty name=&quot;bean&quot; property=&quot;magic&quot; />
<!-- bean.jsp --> <hr> <h3>Bean JSP</h3> <p>Have all sorts of elaborate, tasteful HTML (&quot;presentation&quot;) surrounding the data we pull off the bean. <p> Behold -- I bring forth the magic property from the Magic Bean... <!-- bring in the bean under the name &quot;bean&quot; --> <jsp:usebean id=&quot;bean&quot; class=&quot;MagicBean&quot; /> <table border=1> <tr> <td bgcolor=green><font size=+2>Woo</font> Hoo</td> <td bgcolor=pink> <font size=+3> <td bgcolor=pink> <font size=+3> <!-- the following effectively does bean.getMagic() --> <jsp:getProperty name=&quot;bean&quot; property=&quot;magic&quot; /> </font> </td> <td bgcolor=yellow>Woo <font size=+2>Hoo</font></td> </tr> </table> <!-- pull in content from another page at request time with a relative URL ref to another page -->  <jsp:include page=&quot;trailer.html&quot; flush=&quot;true&quot; />
public class HelloBean extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); String title = &quot;Hello Bean&quot;; out.println(&quot;<title>&quot; + title + &quot;</title>&quot;); out.println(&quot;</head>&quot;); out.println(&quot;<body bgcolor=white>&quot;); out.println(&quot;<h1>&quot; + title + &quot;</h1>&quot;); out.println(&quot;<p>Let's see what Mr. JSP has to contribute...&quot;); request.setAttribute(&quot;foo&quot;, &quot;Binky&quot;); MagicBean bean = new MagicBean(&quot;Peanut butter sandwiches!&quot;); request.setAttribute(&quot;bean&quot;, bean); RequestDispatcher rd = getServletContext().getRequestDispatcher(&quot;/bean.jsp&quot;); rd.include(request, response); rd.include(request, response); out.println(&quot;<hr>&quot;); out.println(&quot;</body>&quot;); out.println(&quot;</html>&quot;); } // Override doPost() -- just have it call doGet() public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }
JSP Tags Found in JSP Pages Look like HTML Tags <blah attr=val>Foo</blah> Single Tag Format <blah attr=val/>
<%-- JSPComment --%> <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
<%@ Directive %> <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
Page Directive <%@ page import=&quot;package.class&quot; %> <%@ page import=&quot;java.util.*&quot; %> <%@ page contentType=&quot;text/html&quot; %> <% response.setContentType(&quot;text/html&quot;); %>
Include Directive <%@ include file=&quot;Relative URL&quot;> Included at Translation time May contain JSP code such as response header settings, field definitions, etc... that affect the main page
<jsp:include …> Include Files at Request Time <jsp:include page=&quot;news/Item1.html&quot;/> page attribute must point to a page that is HTML or a page that produces HTML (via JSP, CGI, etc)...
Scripting Element Tags <%= expr %> <%! decl %> <% code %>
Action Elements Standard Actions JSTL (tag library) Actions Custom Actions
Standard Actions <jsp:useBean> Makes a JavaBeans component available in a page <jsp:getProperty> Gets a property value from a JavaBeans component and adds it to the response <jsp:setProperty> Set a JavaBeans property value <jsp:include> Includes the response from a servlet or JSP page during the request processing phase
Standard Actions <jsp:forward> Forwards the processing of a request to servlet or JSP page <jsp:param> Adds a parameter value to a request handed off to another servlet or JSP page using <jsp:include> or <jsp: forward> <jsp:plugin> Generates HTML that contains the appropriate client browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software
Custom Actions (Tag Libraries) Can Define Your own! Description Define Install Declare Use Details in JavaServer Pages 2nd ed found on Safari Techbooks
JSTL Tags <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> ... <c:out value=&quot;${1 + 2 + 3}&quot; />
JSP Standard Tag Library <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1>   1 + 2 + 3 =  <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html> Built on custom tag infrastructure
JSTL Control Tags <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c “uri=&quot;http://java.sun.com/jstl/core&quot; %> <c:if test=&quot;${2>0}&quot;> It's true that (2>0)! </c:if> <c:forEach items=&quot;${paramValues.food}&quot; var=&quot;current&quot;> <c:out value=&quot;${current}&quot; />&nbsp; </c:forEach>
Expression Language Motivation Limitations of MVC <%= ... %>, <% ... %>, <%! ... %> jsp:useBean, jsp:getProperty verbose clumsy scripting & expression elements to do more complicated Java things With Expression Language ${expression} Short and readable and fluid, like JavaScript
Advantages of Expression Language (EL) Simple & Concise Flexible (use in conjunction with tag libraries & custom tags) Robust against Error
Basic Arithmetic ${1.2 + 2.3} => 3.5 <%= 1.2 + 2.3 %> ${3/0} => Infinity \${1} => ${1} ${10 mod 4} => 2
Basic Comparisons ${4.0 >= 3} => true ${4.0 ge 3} => true   Not in Java ${100.0 == 100} => true ${(10*10) ne 100} => false Not in Java ${'hip' > 'hit'} => false Not in Java ${'a' < 'b'} => true Not in Java
Implicit Objects ${param.foo} => booyah ${param[&quot;foo&quot;]} => booyah \${param[&quot;foo&quot;]} => ${param[&quot;foo&quot;]} ${header[&quot;host&quot;]} => localhost:8080 ${header[&quot;accept&quot;]} => */* ${header[&quot;user-agent&quot;]} => Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125
Functions Implemented by Tag Libraries (Tag Libaries, implemented as Static Methods) ${param[&quot;foo&quot;]} => JSP 2.0 ${my:reverse(param[&quot;foo&quot;])} => 0.2 PSJ ${my:reverse(my:reverse(param[&quot;foo&quot;]))} => JSP 2.0 ${my:countVowels(param[&quot;foo&quot;])} => 0
Conditionals <TD ALIGN=&quot;RIGHT“ BGCOLOR=“ ${(oranges.total < 0) ? &quot;RED&quot; : &quot;WHITE&quot;} &quot;>
package coreservlets; public class  Salesbean  { private double q1, q2, q3, q4; public SalesBean(double q1Sales, double q2Sales, double q3Sales, double  q4Sales) { ... } public double getQ1() {return(q1);} public double getQ2() {return(q2);} ... } }
package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Conditionals extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SalesBean apples = new SalesBean(150.25, -75.25, 22.25, -33.57); SalesBean oranges = new SalesBean(-220.25, -49.57, 138.25, 12.25); request.setAttribute(&quot;apples&quot;, apples); request.setattribute(&quot;oranges&quot;, oranges); RequestDispatcher dispatcher =   request.getRequestDispatcher(&quot;/el/conditionals.jsp&quot;); dispatcher.forward(request, response); } }
package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Conditionals extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SalesBean apples = new SalesBean(150.25, -75.25, 22.25, -33.57); SalesBean oranges = new SalesBean(-220.25, -49.57, 138.25, 12.25); request.setAttribute(&quot;apples&quot;, apples); request.setattribute(&quot;oranges&quot;, oranges); RequestDispatcher dispatcher =   request.getRequestDispatcher(&quot;/el/conditionals.jsp&quot;); dispatcher.forward(request, response); } }
... <TD ALIGN=&quot;RIGHT&quot; BGCOLOR=“ ${(oranges.total < 0) ? &quot;RED&quot; : &quot;WHITE&quot;} &quot;> <TD ALIGN=&quot;RIGHT&quot; BGCOLOR=“ ${(apples.q1 < 0) ? &quot;RED&quot; : &quot;WHITE&quot;} &quot;> ...
EL Examples <input name=&quot;firstName“ value=&quot;${customer.firstName}&quot;> <c:out value=&quot;${order.amount + 5}&quot;/> ${order.amount + 5} {order['amount'] + 5}

More Related Content

PPT
Rich faces
PPT
Unified Expression Language
PPT
Processing XML with Java
ODP
JavaScript and jQuery Fundamentals
PPT
Boston Computing Review - Java Server Pages
PPT
Web Applications and Deployment
PPTX
JSP Directives
PPTX
jQuery from the very beginning
Rich faces
Unified Expression Language
Processing XML with Java
JavaScript and jQuery Fundamentals
Boston Computing Review - Java Server Pages
Web Applications and Deployment
JSP Directives
jQuery from the very beginning

What's hot (20)

PPT
PDF
Html 5 in a big nutshell
PPTX
Servlet and jsp interview questions
PDF
Open Social Summit Korea
PPT
Java Server Faces (JSF) - advanced
PDF
Jsf Ajax
PPT
PPT
Using SVG with Ample SDK cross browser
PPT
JSF 2 and beyond: Keeping progress coming
PPT
Component Framework Primer for JSF Users
PPT
Java presentation
PPT
AK 3 web services using apache axis
PPS
Jsp element
PDF
Introduction to JSP
PPT
Jsp Slides
PPT
Ruby On Rails Tutorial
PPTX
Jsp presentation
PDF
JavaScript Library Overview
PPT
Java Server Pages
PPTX
Web programming
Html 5 in a big nutshell
Servlet and jsp interview questions
Open Social Summit Korea
Java Server Faces (JSF) - advanced
Jsf Ajax
Using SVG with Ample SDK cross browser
JSF 2 and beyond: Keeping progress coming
Component Framework Primer for JSF Users
Java presentation
AK 3 web services using apache axis
Jsp element
Introduction to JSP
Jsp Slides
Ruby On Rails Tutorial
Jsp presentation
JavaScript Library Overview
Java Server Pages
Web programming
Ad

Viewers also liked (20)

PDF
Java Web Programming [4/9] : JSP Basic
PPT
Jsp ppt
PDF
xampp_server
PPTX
4. jsp
PDF
Joomla!: phpMyAdmin for Beginners
DOCX
Using XAMPP
PPT
Jsp Presentation +Mufix "3"
PDF
Lecture03 p1
PDF
phpMyAdmin con Xampp
PPTX
Unit testing
PPT
Introduction to the Servlet / JSP course
PPT
Software quality assurance
PPTX
Web application using JSP
PPTX
Introducing the MySQL Workbench CASE tool
PPT
Jdbc Dao it-slideshares.blogspot.com
PPT
Data Access with JDBC
PPT
PDF
1 intro of data structure course
PPTX
JDBC Driver Types
Java Web Programming [4/9] : JSP Basic
Jsp ppt
xampp_server
4. jsp
Joomla!: phpMyAdmin for Beginners
Using XAMPP
Jsp Presentation +Mufix "3"
Lecture03 p1
phpMyAdmin con Xampp
Unit testing
Introduction to the Servlet / JSP course
Software quality assurance
Web application using JSP
Introducing the MySQL Workbench CASE tool
Jdbc Dao it-slideshares.blogspot.com
Data Access with JDBC
1 intro of data structure course
JDBC Driver Types
Ad

Similar to Jsp (20)

PPT
29 Jsp
PPT
JSP diana y yo
PPT
J2EE - JSP-Servlet- Container - Components
PPT
I Feel Pretty
PPTX
Learning jsp
PPTX
C:\fakepath\jsp01
PPT
Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)
PPT
KMUTNB - Internet Programming 5/7
PPT
KMUTNB - Internet Programming 5/7
PPT
Server-side Technologies in Java
PPTX
JavaServer Pages
PPTX
WT Unit-Vuufvmjn dissimilating Dunkirk k
PPT
Ta Javaserverside Eran Toch
DOCX
PPTX
Java web application development
PPTX
JavaScript, often abbreviated as JS, is a programming language and core techn...
PPT
Servlet/JSP course chapter 1: Introduction to servlets
PDF
J2EE jsp_01
PPTX
JAVA SERVER PAGES
29 Jsp
JSP diana y yo
J2EE - JSP-Servlet- Container - Components
I Feel Pretty
Learning jsp
C:\fakepath\jsp01
Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)
KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7
Server-side Technologies in Java
JavaServer Pages
WT Unit-Vuufvmjn dissimilating Dunkirk k
Ta Javaserverside Eran Toch
Java web application development
JavaScript, often abbreviated as JS, is a programming language and core techn...
Servlet/JSP course chapter 1: Introduction to servlets
J2EE jsp_01
JAVA SERVER PAGES

Recently uploaded (20)

PDF
Updated Idioms and Phrasal Verbs in English subject
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PPTX
Lesson notes of climatology university.
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
01-Introduction-to-Information-Management.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
Updated Idioms and Phrasal Verbs in English subject
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
Lesson notes of climatology university.
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
LDMMIA Reiki Yoga Finals Review Spring Summer
Microbial diseases, their pathogenesis and prophylaxis
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Final Presentation General Medicine 03-08-2024.pptx
Paper A Mock Exam 9_ Attempt review.pdf.
01-Introduction-to-Information-Management.pdf
Supply Chain Operations Speaking Notes -ICLT Program
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
Orientation - ARALprogram of Deped to the Parents.pptx

Jsp

  • 1. JSPs Lecture 8 cs193i – Internet Technologies Summer 2004 Stanford University
  • 2. Administrative Stuff HW#3 due today HW#4 due August 11 All local SCPD students must come to campus for final exam
  • 3. Why JSPs? Goal: Create dynamic web content (HTML, XML, ...) for a Web Application Goal: Make it easier/cleaner to mix static HTML parts with dynamic Java servlet code JSP specification ver. 2.0 Java Servlet specification ver. 2.4
  • 4. JSP/ASP/PHP vs CGI/Servlets CGI & Servlets -- Mostly Code with some HTML via print & out.println JSP/ASP/PHP -- Mostly HTML, with code snippets thrown in No explicit recompile Great for small problems Easier to program Not for large computations
  • 5. What is JSP? Mostly HTML page , with extension .jsp Include JSP tags to enable dynamic content creation Translation: JSP -> Servlet class Compiled at Request time (first request, a little slow) Execution: Request -> JSP Servlet's service method
  • 6. What is a JSP? <html> <body> <jsp:useBean.../> <jsp:getProperty.../> <jsp:getProperty.../> </body> </html>
  • 7. Advantages Code -- Computation HTML -- Presentation Separation of Roles Developers Content Authors/Graphic Designers/Web Masters Supposed to be cheaper... but not really...
  • 8. Model-View-Controller A Design Pattern Controller -- receives user interface input, updates data model Model -- represents state of the world (e.g. shopping cart) View -- looks at model and generates an appropriate user interface to present the data and allow for further input
  • 9. Model-View-Controller Bean JSP Servlet Controller View Model
  • 10. public class OrderServlet … { public void dogGet(…){ if(isOrderValid(req)){ saveOrder(req); … out.println(“<html><body>”); … } private void isOrderValid(…){ … } private void saveOrder(…){ … } } Public class OrderServlet … { public void doGet(…){ … if(bean.isOrderValid(…)){ bean.saveOrder(req); … forward(“conf.jsp”); } } <html> <body> <c:forEach items=“${order}”> … </c:forEach> </body> </html> isOrderValid() saveOrder() ------------------ private state Pure Servlet Servlet JSP Java Bean
  • 11. JSP Big Picture Server w/ JSP Container GET /hello.jsp <html>Hello!</html> Hello.jsp HelloServlet.java HelloServlet.class
  • 13. <%@ Directive %> <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
  • 14. <%-- JSPComment --> <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
  • 15. Template Text <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=http://java.sun.com/jstl/core %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
  • 16. <%= expr > Java expression whose output is spliced into HTML <%= userInfo.getUserName() %> <%= 1 + 1 %> <%= new java.util.Date() %> Translated to out.println(userInfo.getUserName()) ... WARNING: Old School JSP! The new way is introduced after break.... you may use either, but Old School JSP is used sparingly nowadays
  • 17. <% code %> Scriptlet: Add a whole block of code to JSP... passed through to JSP's service method
  • 18. <%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <%@ page import=&quot;java.util.*&quot; %> <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> <% // Create an ArrayList with test data ArrayList list = new ArrayList( ); Map author1 = new HashMap( ); author1.put(&quot;name&quot;, &quot;John Irving&quot;); author1.put(&quot;id&quot;, new Integer(1)); list.add(author1); Map author2 = new HashMap( ); author2.put(&quot;name&quot;, &quot;William Gibson&quot;); author2.put(&quot;id&quot;, new Integer(2)); list.add(author2); Map author3 = new HashMap( ); author3.put(&quot;name&quot;, &quot;Douglas Adams&quot;); author3.put(&quot;id&quot;, new Integer(3)); list.add(author3); pageContext.setAttribute(&quot;authors&quot;, list); %> <html> <head> <title>Search result: Authors</title> </head> <body bgcolor=&quot;white&quot;> Here are all authors matching your search critera: <table> <th>Name</th> <th>Id</th> <c:forEach items=“${ authors }” var=“current”>
  • 19. <%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <html> <head> <title>Browser Check</title> </head> <body bgcolor=&quot;white&quot;> <% String userAgent = request.getHeader(&quot;User-Agent&quot;); if (userAgent.indexOf(&quot;MSIE&quot;) != -1) { %> You're using Internet Explorer. <% } else if (userAgent.indexOf(&quot;Mozilla&quot;) != -1) { %> You're probably using Netscape. <% } else { %> You're using a browser I don't know about. <% } %> </body> </html>
  • 20. <%! decl > Turned into an instance variable for the servlet What did I tell you about instance variables & multithreaded servlets? Serious Race Conditions Here!
  • 21. <%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <%! int globalCounter = 0; %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor=&quot;white&quot;> This page has been visited: <%= ++globalCounter %> times. <p> <% int localCounter = 0; %> This counter never increases its value: <%= ++localCounter %> </body> </html> Declarations have serious multithreading issues!
  • 22. <%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <%! int globalCounter = 0; %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor=&quot;white&quot;> This page has been visited: <%= ++globalCounter %> times. <p> <% int localCounter = 0; %> This counter never increases its value: <%= ++localCounter %> </body> </html> Not saved between requests...!
  • 23. <%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; %> <%@ page import=&quot;java.util.Date&quot; %> <%! int globalCounter = 0; java.util.Date startDate; public void jspInit ( ) { startDate = new java.util.Date( ); } public void jspDestroy ( ) { ServletContext context = getServletConfig().getServletContext( ); context.log(&quot;test.jsp was visited &quot; + globalCounter + &quot; times between &quot; + startDate + &quot; and &quot; + (new Date( ))); } %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor=&quot;white&quot;> This page has been visited: <%= ++globalCounter %> times since <%= startDate %> . </body> </html> No real need anymore, since we don't use instance variables!
  • 24. <jsp:include …> <jsp:include page=&quot;trailer.html“ flush=&quot;true&quot; />
  • 26. Big Picture – Web Apps Database Legacy Applications Java Applications Web Service Other…? End User #1 End User #2 Web Server (Servlets/JSP)
  • 27. Invoking Dynamic Code (from JSPs) Call Java Code Directly (Expressions, Declarations, Scriptlets) Call Java Code Indirectly (Separate Utility Classes, JSP calls methods) Use Beans (jsp:useBean, jsp:getProperty, jsp:setProperty) Use MVC architecture (servlet, JSP, JavaBean) Use JSP expression Language (shorthand to access bean properties, etc) Use custom tags (Develop tag handler classes; use xml-like custom tags)
  • 28. Invoking Dynamic Code (from JSPs) Call Java Code Directly (Expressions, Declarations, Scriptlets) Call Java Code Indirectly (Separate Utility Classes, JSP calls methods) Use Beans (jsp:useBean, jsp:getProperty, jsp:setProperty) Use MVC architecture (servlet, JSP, JavaBean) Use JSP expression Language (shorthand to access bean properties, etc) Use custom tags (Develop tag handler classes; use xml-like custom tags) Simple Application or Small Development Team Complex Application or Big Development Team
  • 29. Servlets and JSPs Core Servlets and JavaServer Pages, 2nd Edition, Volumes 1 & 2. Marty Hall & Larry Brown
  • 30. Java Beans Purpose: Store Data Simple Object, requires no argument constructor Properties accessible via get & set methods
  • 31. Java Beans For a &quot;foo&quot; property, a java bean will respond to Type getFoo() void setFoo(Type foo) For a boolean &quot;bar&quot; property, a java bean will respond to boolean isBar() void setBar(boolean bar)
  • 32. Java Bean int getCount() void setCount(int c) String getS() void setS(String s) int[] getFoo() void setFoo(int[] f) int count; String s; int[] foo;
  • 33.  
  • 34. // MagicBean.java /* A simple bean that contains a single * &quot;magic&quot; string. */ public class MagicBean { private String magic; public MagicBean(String string) { magic = string; } public MagicBean() { magic = &quot;Woo Hoo&quot;; // default magic string } public String getMagic() { return(magic); } public void setMagic(String magic) { this.magic = magic; } }
  • 35. Java Beans <jsp:useBean id=&quot;myBean&quot; class=&quot;com.foo.MyBean“ scope=&quot;request&quot;/> <jsp:getProperty name=&quot;myBean“ property=&quot;lastChanged&quot; /> <jsp:setProperty name=&quot;myBean“ property=&quot;lastChanged&quot; value=&quot;<%= new Date()%>&quot;/> Example <jsp:usebean id=&quot;bean&quot; class=&quot;MagicBean&quot; /> <jsp:getProperty name=&quot;bean&quot; property=&quot;magic&quot; />
  • 36. <!-- bean.jsp --> <hr> <h3>Bean JSP</h3> <p>Have all sorts of elaborate, tasteful HTML (&quot;presentation&quot;) surrounding the data we pull off the bean. <p> Behold -- I bring forth the magic property from the Magic Bean... <!-- bring in the bean under the name &quot;bean&quot; --> <jsp:usebean id=&quot;bean&quot; class=&quot;MagicBean&quot; /> <table border=1> <tr> <td bgcolor=green><font size=+2>Woo</font> Hoo</td> <td bgcolor=pink> <font size=+3> <td bgcolor=pink> <font size=+3> <!-- the following effectively does bean.getMagic() --> <jsp:getProperty name=&quot;bean&quot; property=&quot;magic&quot; /> </font> </td> <td bgcolor=yellow>Woo <font size=+2>Hoo</font></td> </tr> </table> <!-- pull in content from another page at request time with a relative URL ref to another page --> <jsp:include page=&quot;trailer.html&quot; flush=&quot;true&quot; />
  • 37. public class HelloBean extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); String title = &quot;Hello Bean&quot;; out.println(&quot;<title>&quot; + title + &quot;</title>&quot;); out.println(&quot;</head>&quot;); out.println(&quot;<body bgcolor=white>&quot;); out.println(&quot;<h1>&quot; + title + &quot;</h1>&quot;); out.println(&quot;<p>Let's see what Mr. JSP has to contribute...&quot;); request.setAttribute(&quot;foo&quot;, &quot;Binky&quot;); MagicBean bean = new MagicBean(&quot;Peanut butter sandwiches!&quot;); request.setAttribute(&quot;bean&quot;, bean); RequestDispatcher rd = getServletContext().getRequestDispatcher(&quot;/bean.jsp&quot;); rd.include(request, response); rd.include(request, response); out.println(&quot;<hr>&quot;); out.println(&quot;</body>&quot;); out.println(&quot;</html>&quot;); } // Override doPost() -- just have it call doGet() public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }
  • 38. JSP Tags Found in JSP Pages Look like HTML Tags <blah attr=val>Foo</blah> Single Tag Format <blah attr=val/>
  • 39. <%-- JSPComment --%> <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
  • 40. <%@ Directive %> <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of 1 + 2 + 3 dynamically --%> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html>
  • 41. Page Directive <%@ page import=&quot;package.class&quot; %> <%@ page import=&quot;java.util.*&quot; %> <%@ page contentType=&quot;text/html&quot; %> <% response.setContentType(&quot;text/html&quot;); %>
  • 42. Include Directive <%@ include file=&quot;Relative URL&quot;> Included at Translation time May contain JSP code such as response header settings, field definitions, etc... that affect the main page
  • 43. <jsp:include …> Include Files at Request Time <jsp:include page=&quot;news/Item1.html&quot;/> page attribute must point to a page that is HTML or a page that produces HTML (via JSP, CGI, etc)...
  • 44. Scripting Element Tags <%= expr %> <%! decl %> <% code %>
  • 45. Action Elements Standard Actions JSTL (tag library) Actions Custom Actions
  • 46. Standard Actions <jsp:useBean> Makes a JavaBeans component available in a page <jsp:getProperty> Gets a property value from a JavaBeans component and adds it to the response <jsp:setProperty> Set a JavaBeans property value <jsp:include> Includes the response from a servlet or JSP page during the request processing phase
  • 47. Standard Actions <jsp:forward> Forwards the processing of a request to servlet or JSP page <jsp:param> Adds a parameter value to a request handed off to another servlet or JSP page using <jsp:include> or <jsp: forward> <jsp:plugin> Generates HTML that contains the appropriate client browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software
  • 48. Custom Actions (Tag Libraries) Can Define Your own! Description Define Install Declare Use Details in JavaServer Pages 2nd ed found on Safari Techbooks
  • 49. JSTL Tags <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> ... <c:out value=&quot;${1 + 2 + 3}&quot; />
  • 50. JSP Standard Tag Library <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core&quot; %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor=&quot;white&quot;> <h1>JSP is as easy as ...</h1> 1 + 2 + 3 = <c:out value=&quot;${1 + 2 + 3}&quot; /> </body> </html> Built on custom tag infrastructure
  • 51. JSTL Control Tags <%@ page contentType=&quot;text/html&quot; %> <%@ taglib prefix=&quot;c “uri=&quot;http://java.sun.com/jstl/core&quot; %> <c:if test=&quot;${2>0}&quot;> It's true that (2>0)! </c:if> <c:forEach items=&quot;${paramValues.food}&quot; var=&quot;current&quot;> <c:out value=&quot;${current}&quot; />&nbsp; </c:forEach>
  • 52. Expression Language Motivation Limitations of MVC <%= ... %>, <% ... %>, <%! ... %> jsp:useBean, jsp:getProperty verbose clumsy scripting & expression elements to do more complicated Java things With Expression Language ${expression} Short and readable and fluid, like JavaScript
  • 53. Advantages of Expression Language (EL) Simple & Concise Flexible (use in conjunction with tag libraries & custom tags) Robust against Error
  • 54. Basic Arithmetic ${1.2 + 2.3} => 3.5 <%= 1.2 + 2.3 %> ${3/0} => Infinity \${1} => ${1} ${10 mod 4} => 2
  • 55. Basic Comparisons ${4.0 >= 3} => true ${4.0 ge 3} => true Not in Java ${100.0 == 100} => true ${(10*10) ne 100} => false Not in Java ${'hip' > 'hit'} => false Not in Java ${'a' < 'b'} => true Not in Java
  • 56. Implicit Objects ${param.foo} => booyah ${param[&quot;foo&quot;]} => booyah \${param[&quot;foo&quot;]} => ${param[&quot;foo&quot;]} ${header[&quot;host&quot;]} => localhost:8080 ${header[&quot;accept&quot;]} => */* ${header[&quot;user-agent&quot;]} => Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125
  • 57. Functions Implemented by Tag Libraries (Tag Libaries, implemented as Static Methods) ${param[&quot;foo&quot;]} => JSP 2.0 ${my:reverse(param[&quot;foo&quot;])} => 0.2 PSJ ${my:reverse(my:reverse(param[&quot;foo&quot;]))} => JSP 2.0 ${my:countVowels(param[&quot;foo&quot;])} => 0
  • 58. Conditionals <TD ALIGN=&quot;RIGHT“ BGCOLOR=“ ${(oranges.total < 0) ? &quot;RED&quot; : &quot;WHITE&quot;} &quot;>
  • 59. package coreservlets; public class Salesbean { private double q1, q2, q3, q4; public SalesBean(double q1Sales, double q2Sales, double q3Sales, double q4Sales) { ... } public double getQ1() {return(q1);} public double getQ2() {return(q2);} ... } }
  • 60. package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Conditionals extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SalesBean apples = new SalesBean(150.25, -75.25, 22.25, -33.57); SalesBean oranges = new SalesBean(-220.25, -49.57, 138.25, 12.25); request.setAttribute(&quot;apples&quot;, apples); request.setattribute(&quot;oranges&quot;, oranges); RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;/el/conditionals.jsp&quot;); dispatcher.forward(request, response); } }
  • 61. package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Conditionals extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SalesBean apples = new SalesBean(150.25, -75.25, 22.25, -33.57); SalesBean oranges = new SalesBean(-220.25, -49.57, 138.25, 12.25); request.setAttribute(&quot;apples&quot;, apples); request.setattribute(&quot;oranges&quot;, oranges); RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;/el/conditionals.jsp&quot;); dispatcher.forward(request, response); } }
  • 62. ... <TD ALIGN=&quot;RIGHT&quot; BGCOLOR=“ ${(oranges.total < 0) ? &quot;RED&quot; : &quot;WHITE&quot;} &quot;> <TD ALIGN=&quot;RIGHT&quot; BGCOLOR=“ ${(apples.q1 < 0) ? &quot;RED&quot; : &quot;WHITE&quot;} &quot;> ...
  • 63. EL Examples <input name=&quot;firstName“ value=&quot;${customer.firstName}&quot;> <c:out value=&quot;${order.amount + 5}&quot;/> ${order.amount + 5} {order['amount'] + 5}