JSPs Lecture 8 cs193i – Internet Technologies Summer 2004 Stanford University.

Slides:



Advertisements
Similar presentations
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
Advertisements

JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Java Servlet & JSP © copyright 2005 SNU OOPSLA Lab.
Using JavaServer Pages Harry R. Erwin, PhD CIT304/CSE301.
An introduction to Java Servlet Programming
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
Introduction to Servlet & JSP
Integrating Servlets and JavaServer Pages Vijayan Sugumaran School of Business Administration Oakland University Parts of this presentation provided by.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
JavaServer Pages TM Introduce by
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
UNIT-V The MVC architecture and Struts Framework.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
Introduction to JSP Based on: Marty Hall, Larry Brown, Core Servlets and JavaServer Pages.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Java Server Pages Lecture July Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java)
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Stanisław Osiński, 2002JSP – A technology for serving dynamic web content Java Server Pages™ A technology for serving dynamic web content Stanisław Osiński,
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Slides © Marty Hall, book © Sun Microsystems Press 1 JSP Scripting Elements Core Servlets & JSP book:
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets & Java Server Pages Lecture July 2013.
SE-2840 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Chapter 2 Web app architecture. High-level web app architecture  When a client request coming in and needs servlet to serve dynamic web content, what.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Java Server Pages (JSP)
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
CSC 2720 Building Web Applications Frameworks for Building Web Applications.
A seminar on j2ee by saritha. s. What is J2EE J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing.
CS-4220 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
 Obtaining a RequestDispatcher Forwarding requests from servlets to dynamic resources  Forwarding requests from servlets to static resources  Using.
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
Java Servlets and Java Server Pages Norman White Stern School of Business.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
Java Servlets and Java Server Pages
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
JSP JavaServer Pages. What is JSP? Java based technology that simplifies the development of dynamic web sites JSP pages are HTML pages with embedded code.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
Apache Struts Technology A MVC Framework for Java Web Applications.
A Presentation Presentation On JSP On JSP & Online Shopping Cart Online Shopping Cart.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Speaker Name Speaker Title Speaker Title Oracle Corporation Olivier Le Diouris Principal Product Manager Oracle Corporation Building Servlet and JSP Applications.
CS3220 Web and Internet Programming Introduction to Java Servlets
COMP9321 Web Application Engineering Semester 2, 2017
Scripted Page Web App Development (Java Server Pages)
Java Server Pages.
Servlets and Java Server Pages
CS3220 Web and Internet Programming Introduction to Java Servlets
Presentation transcript:

JSPs Lecture 8 cs193i – Internet Technologies Summer 2004 Stanford University

Administrative Stuff HW#3 due today HW#3 due today HW#4 due August 11 HW#4 due August 11 All local SCPD students must come to campus for final exam 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?

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(“ ”); … } private void isOrderValid(…){ … } private void saveOrder(…){ … } Public class OrderServlet … { public void doGet(…){ … if(bean.isOrderValid(…)){ bean.saveOrder(req); … forward(“conf.jsp”); } … isOrderValid() saveOrder() private state Pure Servlet Servlet JSP Java Bean

JSP Big Picture Server w/ JSP Container GET /hello.jsp Hello! Hello.jsp HelloServlet.java HelloServlet.class

A JSP File

JSP is Easy JSP is as easy as =

JSP is Easy JSP is as easy as =

Template Text JSP is Easy JSP is as easy as =

Java expression whose output is spliced into HTML 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

Scriptlet: Add a whole block of code to JSP... passed through to JSP's service method

<% // Create an ArrayList with test data ArrayList list = new ArrayList( ); Map author1 = new HashMap( ); author1.put("name", "John Irving"); author1.put("id", new Integer(1)); list.add(author1); Map author2 = new HashMap( ); author2.put("name", "William Gibson"); author2.put("id", new Integer(2)); list.add(author2); Map author3 = new HashMap( ); author3.put("name", "Douglas Adams"); author3.put("id", new Integer(3)); list.add(author3); pageContext.setAttribute("authors", list); %> Search result: Authors Here are all authors matching your search critera: Name Id

Browser Check <% String userAgent = request.getHeader("User-Agent"); if (userAgent.indexOf("MSIE") != -1) { %> You're using Internet Explorer. You're probably using Netscape. You're using a browser I don't know about.

Turned into an instance variable for the servlet What did I tell you about instance variables & multithreaded servlets? Serious Race Conditions Here!

<%! int globalCounter = 0; %> A page with a counter This page has been visited: times. <% int localCounter = 0; %> This counter never increases its value: Declarations have serious multithreading issues!

<%! int globalCounter = 0; %> A page with a counter This page has been visited: times. <% int localCounter = 0; %> This counter never increases its value: Not saved between requests...!

<%! int globalCounter = 0; java.util.Date startDate; public void jspInit( ) { startDate = new java.util.Date( ); } public void jspDestroy( ) { ServletContext context = getServletConfig().getServletContext( ); context.log("test.jsp was visited " + globalCounter + " times between " + startDate + " and " + (new Date( ))); } %> A page with a counter This page has been visited: times since. No real need anymore, since we don't use instance variables!

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 "foo" property, a java bean will respond to Type getFoo() void setFoo(Type foo) For a boolean "bar" 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 * "magic" string. */ public class MagicBean { private String magic; public MagicBean(String string) { magic = string; } public MagicBean() { magic = "Woo Hoo"; // default magic string } public String getMagic() { return(magic); } public void setMagic(String magic) { this.magic = magic; }

Java Beans "/> Example

Bean JSP Have all sorts of elaborate, tasteful HTML ("presentation") surrounding the data we pull off the bean. Behold -- I bring forth the magic property from the Magic Bean... Woo Hoo Woo Hoo

public class HelloBean extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" "); String title = "Hello Bean"; out.println(" " + title + " "); out.println(" "); out.println(" " + title + " "); out.println(" Let's see what Mr. JSP has to contribute..."); request.setAttribute("foo", "Binky"); MagicBean bean = new MagicBean("Peanut butter sandwiches!"); request.setAttribute("bean", bean); RequestDispatcher rd = getServletContext().getRequestDispatcher("/bean.jsp"); rd.include(request, response); out.println(" "); } // 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 Foo Single Tag Format

JSP is Easy JSP is as easy as =

JSP is Easy JSP is as easy as =

Page Directive

Include Directive Included at Translation time May contain JSP code such as response header settings, field definitions, etc... that affect the main page

Include Files at Request Time page attribute must point to a page that is HTML or a page that produces HTML (via JSP, CGI, etc)...

Scripting Element Tags

Action Elements Standard Actions JSTL (tag library) Actions Custom Actions

Standard Actions Makes a JavaBeans component available in a page Gets a property value from a JavaBeans component and adds it to the response Set a JavaBeans property value Includes the response from a servlet or JSP page during the request processing phase

Standard Actions Forwards the processing of a request to servlet or JSP page Adds a parameter value to a request handed off to another servlet or JSP page using or 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="c" uri=" %>...

JSP Standard Tag Library JSP is Easy JSP is as easy as = Built on custom tag infrastructure

JSTL Control Tags 0}"> It's true that (2>0)!

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 ${ } => 3.5 ${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} => falseNot in Java ${'hip' > 'hit'} => falseNot in Java ${'a' trueNot in Java

Implicit Objects ${param.foo} => booyah ${param["foo"]} => booyah \${param["foo"]} => ${param["foo"]} ${header["host"]} => localhost:8080 ${header["accept"]} => */* ${header["user-agent"]} => 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["foo"]} => JSP 2.0 ${my:reverse(param["foo"])} => 0.2 PSJ ${my:reverse(my:reverse(param["foo"]))} => JSP 2.0 ${my:countVowels(param["foo"])} => 0

Conditionals

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, , 22.25, ); SalesBean oranges = new SalesBean( , , , 12.25); request.setAttribute("apples", apples); request.setattribute("oranges", oranges); RequestDispatcher dispatcher = request.getRequestDispatcher("/el/conditionals.jsp"); 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, , 22.25, ); SalesBean oranges = new SalesBean( , , , 12.25); request.setAttribute("apples", apples); request.setattribute("oranges", oranges); RequestDispatcher dispatcher = request.getRequestDispatcher("/el/conditionals.jsp"); dispatcher.forward(request, response); }

......

EL Examples ${order.amount + 5} {order['amount'] + 5}