Web Fundamentals. Typical Current Web Architecture. Web Server HTTP interface. HTML, Images, cookies, JSON, etc.

Similar documents
Session 18. jquery - Ajax. Reference. Tutorials. jquery Methods. Session 18 jquery and Ajax 10/31/ Robert Kelly,

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

Session 8. Introduction to Servlets. Semester Project

Session 7. JavaScript Part 2. W3C DOM Reading and Reference

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Session 9. Introduction to Servlets. Lecture Objectives

Session 11. Ajax. Reading & Reference

Session 17. JavaScript Part 2. W3C DOM Reading and Reference. Background and introduction.

Session 17. jquery. jquery Reading & References

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Session 9. Data Sharing & Cookies. Reading & Reference. Reading. Reference http state management. Session 9 Data Sharing

Chapter 10 Servlets and Java Server Pages

Servlet Basics. Agenda

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

Introduction to JSP and Servlets Training 5-days

AJAX Programming Chris Seddon

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

COMP9321 Web Application Engineering

AJAX: Introduction CISC 282 November 27, 2018

Servlets. An extension of a web server runs inside a servlet container

Chapter 10 Web-based Information Systems

COMP9321 Web Application Engineering

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Java SE7 Fundamentals


Module7: AJAX. Click, wait, and refresh user interaction. Synchronous request/response communication model. Page-driven: Workflow is based on pages

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

Fall Semester (081) Module7: AJAX

Servlets and JSP (Java Server Pages)

Fast Track to Java EE

Introduction. This course Software Architecture with Java will discuss the following topics:

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX

ive JAVA EE C u r r i c u l u m

Stateless -Session Bean

Introduction to Servlets. After which you will doget it

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Session 12. JSP Tag Library (JSTL) Reading & Reference

JAVA SERVLET. Server-side Programming INTRODUCTION

SSC - Web applications and development Introduction and Java Servlet (I)


Java.. servlets and. murach's TRAINING & REFERENCE 2ND EDITION. Joel Murach Andrea Steelman. IlB MIKE MURACH & ASSOCIATES, INC.

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

An Introduction to AJAX. By : I. Moamin Abughazaleh

Session 11. Calling Servlets from Ajax. Lecture Objectives. Understand servlet response formats

Vendor: SUN. Exam Code: Exam Name: Sun Certified Web Component Developer for J2EE 5. Version: Demo

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

CS506 Web Design & Development Final Term Solved MCQs with Reference

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP

Servlet Fudamentals. Celsina Bignoli

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

Handout 31 Web Design & Development

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

Servlet and JSP Review

Web Programming. Lecture 11. University of Toronto

CNIT 129S: Securing Web Applications. Ch 3: Web Application Technologies

Fast Track to Java EE 5 with Servlets, JSP & JDBC

CSC309: Introduction to Web Programming. Lecture 11

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

Java Servlets. Preparing your System

Notes General. IS 651: Distributed Systems 1

Lab session Google Application Engine - GAE. Navid Nikaein

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains 2 components

AJAX: The Basics CISC 282 March 25, 2014

Ajax in Oracle JDeveloper

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

Table of Contents. Introduction... xxi

AJAX: The Basics CISC 282 November 22, 2017

JavaServer Pages. What is JavaServer Pages?

IT2353 WEB TECHNOLOGY Question Bank UNIT I 1. What is the difference between node and host? 2. What is the purpose of routers? 3. Define protocol. 4.

Contents at a Glance

User Interaction: jquery

CS 5142 Scripting Languages

Unit 5 JSP (Java Server Pages)

Module 3 Web Component

Advanced Web Technology

FINALTERM EXAMINATION Spring 2009 CS506- Web Design and Development Solved by Tahseen Anwar

Sun Sun Certified Web Component Developer for J2EE 5 Version 4.0

RKN 2015 Application Layer Short Summary

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

web.xml Deployment Descriptor Elements

Programming for Digital Media. Lecture 7 JavaScript By: A. Mousavi and P. Broomhead SERG, School of Engineering Design, Brunel University, UK

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

The course also includes an overview of some of the most popular frameworks that you will most likely encounter in your real work environments.

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

Courses For Event Java Advanced Summer Training 2018

AJAX ASYNCHRONOUS JAVASCRIPT AND XML. Laura Farinetti - DAUIN

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Developing Applications with Java EE 6 on WebLogic Server 12c

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

UNIT-VI. HttpServletResponse It extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.

NetBeans IDE Field Guide

Introduction to Ajax

CS7026. Introduction to jquery

Transcription:

Web Fundamentals 1 Typical Current Web Architecture Web Container Browser HTML, CSS, MIME Type Display URL / Query string / HTTP data, cookies, etc. HTML, Images, cookies, JSON, etc. Web Server HTTP interface req res Application Server Servlet handler WWW resources, each named with a URL WWW data classes, each with a type Standard content formats (e.g., HTML) Standard network protocols connecting any browser with any server Persistence Layer Database 2 2/19/2018 1

Server Scripting Web Architecture Clients servlet Web Container Bean Session JSP Page JSP Page Bean Other shared objects Web applications are usually constructed with the Model, View, Controller pattern 3 Client Scripting Web Architecture Clients Web Container 1 or more servlets Session Other shared objects JavaScript objects are returned to the client, and JavaScript code is used to update the page 4 2/19/2018 2

Server Scripting Vs. Client Scripting Server scripting advantages Protecting intellectual property Server side libraries and APIs Robust development environments Client scripting advantages More intuitive programming Much better fit with Ajax technology 5 Http HyperText Transfer Protocol defines communications between a browser and a server Defined in 2 specs (http 1.0 and http 1.1) Defines: Types of messages exchanged (request and response) Syntax of the messages Semantics of the message content Rules for determining how and when a process sends and responds to a message 6 2/19/2018 3

Http Hypertext Transfer Protocol Primary Web application layer protocol uses TCP Implemented as Client program in browser (request message formatting) Server program in Web server (parsing the request method and preparing the response message) Http defines the structure of messages sent between the client and the server Http Http Web server 7 Http Protocol HTTP is a request/response (stateless) protocol A client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content The server responds with a status line, including the message's protocol version and a success (or error) code, followed by a MIME-like message containing server information, entity meta-information, and possible entity-body content. 8 2/19/2018 4

Request Message Format The http request is specified by the request line, a variable number of header fields, and the entity body method sp URL sp Version cr lf header field name sp value cr lf header field name sp value cr lf header field name sp value cr lf cr lf request line header lines Entity body 9 Http Methods OPTIONS request for information concerning communications options (e.g., support of http 1.1) GET retrieve information HEAD identical to GET, except the server does not return a message body POST modify a server resource PUT store the enclosed entity DELETE request that the resource be deleted TRACE response contains the entire message request in the response body CONNECT used in SSL tunneling 10 2/19/2018 5

Http Request From Browser Request line contains the method, URL, and http version Header lines contain http data For the POST method, the form data set is transmitted in the Http entity body, not in the URL 11 Http Response From Server Status line contains version, code and code text Response Mime type Http header info 12 2/19/2018 6

Http Request Message Http messages (other than the body) are written in ASCII text Http request messages consist of: Request line (method, URL, version) Header lines (connection, user-agent, accept-language, etc) Entity body Not used for GET requests Used for uploading files (as in WDG HTML validator) 13 Http Request Headers Accept Accept-charset Accept-encoding Accept-language Authorization Cache-control Connection Content-length Content-type Cookie Expect From Host If-match If-modified-since If-none-match If-range If-unmodified-since Pragma Proxy-authorization Range Referer Upgrade User-agent Via 14 2/19/2018 7

Http Response Message Http response messages consist of: Status line (protocol version, status code, status message) Header lines (date, server, last-modified, content-length, content-type) Entity body 15 Http Status Codes Examples: 200 OK 100 Continue 404 Not found You will see this code in your browser if the Web Application cannot find your servlet 16 2/19/2018 8

Http Response Headers Accept-Ranges Age Allow Cache-Control Connection Content-Encoding Content-Language Content-Length Content-MD5 Content-Type Date Etag Expires Last-Modified Location Refresh Server Set-Cookie Via Warning 17 Typical Client/Server Interaction Clients Web Container HTTP 1 or more servlets Session Other shared objects For client side scripting, JavaScript objects (JSON) are returned to the client, for server side scripting, html is usually returned 18 2/19/2018 9

What is a Servlet? A Java class that can be loaded dynamically to expand the capability of the Web server Runs inside the Java Virtual Machine on the server (safe and portable) Tools (e.g., Spring) usually implement a single servlet to respond to user requests 19 Hello WWW Servlet Class package lectures; import java.io.*;import java.net.*;import javax.servlet.*; import javax.servlet.http.*; processrequest is a method used by convention in NetBeans public class HelloWWW extends HttpServlet { protected void processrequest(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doget(httpservletrequest request, HttpServletResponse response) The Web container calls either doget or dopost, which then calls processrequest throws ServletException, IOException { processrequest(request, response); } protected void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { processrequest(request, response); } 20 2/19/2018 10

Web Application Your Web application is stored in a directory (and deployed as a war file) Top level directory of the Web application is the document root of the application, containing JSP pages and static Web resources (or subdirectories of JSP, etc.) Document root contains a sub-directory called WEB-INF, containing web.xml the deployment descriptor classes a directory containing server classes (e.g., servlets) lib a directory that contains JAR archives of libraries Package directories can be either in the document root or the WEB-INF/classes directory Take a look at your Web App in your NetBeans or Eclipse project pane 21 How to Specify the Servlet in Your HTML A URL is used to request that the container run your servlet (in an anchor tag or form tag) URL contains the host name, port (optional), and path In a servlet container, the path can be mapped (what you see is not always what you get) http://localhost:8080/codecse336/hellowww.html There is no hellowww file 22 2/19/2018 11

How URLs Run Servlets http://localhost:8080/codecse336/hellowww.html Context name The servlet container evaluates the URL request to see if the first part of the path matches a context name If the path matches a context name, the context name is mapped to a Web application root directory (using the web.xml deployment descriptor) 23 JavaServer Page (JSP) Used to rapidly create dynamically-generated Web pages Separates web presentation from Web page content (and allows for differing programming skills to work on a project) A JSP is: A text-based document (filename extension of.jsp) that processes a request and constructs a response Translated into a servlet 24 2/19/2018 12

Servlet Vs. JSP JSP (helloworld.jsp) <!DOCTYPE HTML PUBLIC "- //W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>hello WWW</title> </head> <body> <h1>hello WWW</h1> </body> </html> Which one (servlet or JSP) is easier to read and write? Servlet (HelloWorld.java) public class HelloWorld extends HttpServlet { public void doget( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype( "text/html"); PrintWriter out = response.getwriter(); String doctype = "<!DOCTYPE HTML PUBLIC \"- //W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(doctype); out.println("<html>"); out.println("<head><title> Hello WWW</title></head>"); out.println("<body>"); out.println( "<h1>hello WWW</h1>"); out.println("</body></html>")}} 25 JSP Translation The Web container translates the JSP into the equivalent servlet (and compiles it into a servlet class) Can include any MyJSP.jsp static text MyJSP_jsp.java (e.g., XML) html EL scriptlets JSP elements Translation Generated code is placed in a GlassFish sub-directory and available on a NetBeans context menu Java code 26 2/19/2018 13

EL in a Nutshell EL (Expression Language) Resembles Java (but a little different and, of course, much simpler) EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression Fully supported with JSP 2.0 Extended in JSP 2.1 Syntax ${ } The value of an expression in static text is computed and inserted into the current output The EL expression is contained within the brackets 27 Example... <p>the counter is initially: ${b.count} </p> How does EL find the bean? How does EL get the value of count? 28 2/19/2018 14

Abstracting Control Logic from a JSP Clients Web layer Data sources servlet JSP Page JSP Page Bean JSTL Tag Custom Tag XML JDBC EJB 29 Example Form Debug JSP <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>formtester</title> <link rel="stylesheet" type="text/css href="http://www.cs.sunysb.edu/~cse336/cse336.css"/> </head> <body> <h2>testing the Input Form</h2> <table> <tr> <th>parameter Name</th> <th>parameter Value</th></tr> <c:foreach var="p" items="${param}"> <tr> <td> <c:out value="${p.key}"/> </td> <td> <c:out value="${p.value}"/> </td> </tr> </c:foreach> </table> </body> </html> EL expression Declares the JSTL core tag library Variable is a named reference to an object (explicit or implicit) 30 2/19/2018 15

When Do You Need to Share Data on the Server? Among servlets cooperating on an application Among servlets cooperating to satisfy the requests from a single user (e.g., shopping cart) Usually on the same workstation and browser Remember that a Cloud application usually involves multiple simultaneous users in which some data is shared and some data is kept private from other users access 31 Shared Scopes Web components share information through private objects (e.g., JavaBeans components). Attributes of a public scope Database Invoking other web resources Shared scopes setattribute and getattribute ServletContext Session Request Page 32 2/19/2018 16

How Do The Shared Scopes Differ? Visibility Different browsers Different computers Lifetime ServletContext life of the container Request Duration of the request Session until timeout or destroy Page life of the servlet invocation Visibility and lifetime define the scope of the object 33 Server Side Storage request Web Container Servlet 1 Servlet 2 Server object Servlet 3 Data stored on the server is usually contained in an object visible to the servlet To access the shared object, you need to obtain a reference (handle) to the object Objects for sharing ServletContext is the object that acts like HttpServletRequest a global repository ServletContext Session You can invoke a method when the application starts, and Other predefined and private objects place a handle to the objects you need in the ServletContext 34 2/19/2018 17

Shared Objects attribute The shared objects are referred to as scopes The shared scopes are contained in other objects For example, the request object contains the request scope HttpServletRequest contenttype method etc. 35 Why Do We Need a Session? The ServletContext object allows you to store servlet data beyond a single request, but: The life of the ServletContext object is too long for a user transaction You probably want to limit the sharing to one user For example, data for a shopping application (a shopping cart) has a life that is only as long as the user is shopping and you want the shopping cart to only be visible to servlet executions for that user 36 2/19/2018 18

The Web container provides (and manages) session objects Session Object Note that there are many session objects, but only one associated with a single computer/browser You can store information in a session object using name-value pairs, but the session object only exists for the life of the session A session usually corresponds to one user, who may visit a site many times where the interval between visits is small How does the Web Container identify a user? 37 Session Life Cycle API You can set the duration of a session (e.g., 20 minutes) Or you can invalidate the session when you are finished (e.g., when the user logs out) Session invalidate() isnew() getcreationtime() getlastaccessedtime() setmaxinactiveinterval(int) getattribute(string) setattribute(string, Object) getattributenames() removeattribute(string) 38 2/19/2018 19

Steps in Session Management Request a session object. This can be either: A session object that was previously created and may contain data inserted by another servlet A new session object when there is no existing session object matching this user Store information in the session object Invalidate the session - or allow the session to time out when maxinactiveinterval (time in seconds) is exceeded setmaxinactiveinterval(int interval) Objects attached to the session can receive notification when they are unbound through a listener interface 39 What is Ajax? Asynchronous JavaScript Technology and XML Allows incremental update of Web pages within the browser Not dependent on any given language or data exchange format, but works well with Xhtml JavaScript 40 2/19/2018 20

Classic Browser/Server Interaction browser click wait click wait click request request Html page Html page server processing processing 41 Ajax Browser/Server Interaction browser browser UI User events UI updates Ajax engine Client engine is key to Ajax model by allowing asynchronous operation request text request text server processing processing 42 2/19/2018 21

XMLHttpRequest Object Transport object for communication between client and server Methods allow Specify request details Extract response data Subject to some cross-domain limitations 43 Common XMLHttpRequest Properties onreadystatechange - Event handler (function) for an event that fires at every state change readystate -Object status integer: 0 = uninitialized Depends on the 1 = loading content-type of your 2 = loaded response 3 = interactive 4 = complete responsetext - String version of data returned from server process responsexml - DOM-compatible document object of data returned from server process status - Numeric code returned by server (e.g., 404) statustext - String message accompanying the status code 44 2/19/2018 22

Common XMLHttpRequest Methods open("method", "URL"[, asyncflag]) Initializes the request parameters (destination URL, method, and asynchronous flag) send(content) - Transmits the request, optionally with postable string or DOM object data setrequestheader("label", "value") - Assigns a label/value pair to the header to be sent with a request abort() - Stops the current request getallresponseheaders() - Returns complete set of headers (labels and values) as a string getresponseheader("headerlabel") - Returns the string value of a single header label Interaction using XMLHttpRequest is very low-level and complicated 45 Typical Ajax Interaction 1. Client event occurs 2. XMLHttpRequest object is created 3. XMLHttpRequest object calls the server 4. Server request is processed by server code (usually a servlet) 5. Server returns data (usually a text document-html, JSON, or XML) containing the result 6. XMLHttpRequest object calls the callback() function and processes the result 7. The browser document (html) is updated 46 2/19/2018 23

DOM JavaScript begins to be useful when you can access and modify the html in the document DOM can mean different things Approaches Legacy DOM (Document Object Model) Defined by Netscape in the early days of the WWW IE 4 DOM still in use, although Microsoft now supports W3C DOM W3C DOM (level 3) well supported on modern browsers Includes the legacy DOM (known as Level 0 DOM) W3C DOM (level 4) You may see the use of many of the supported DOMs in current code 47 What is DOM? Document Object Model Convention for representing and interacting with objects (HTML, XHTML and XML) Cross platform Binding with various languages Implemented as an API in JavaScript 48 2/19/2018 24

Legacy DOM Does not take full advantage of the tree structure of html documents Tends to reference html elements as members of an array, for example images[], links[] and forms[] Naming document.forms[0] document.forms.f1 document.forms[ f1 ] <form name= f1 > Assuming the order of elements in an html document can cause maintenance problems 49 Defines W3C DOM a standard set of objects (object tree) for an html document Set of methods (language independent) to access the html object Your Java and JavaScript (and other) programs can Access a given node (element) Walk the tree Search for particular nodes or data (e.g., img tags) Modify the nodes and insert sub-trees 50 2/19/2018 25

JavaScript/DOM When a web page is loaded, the browser creates a Document Object Model of the page. With the object model, JavaScript is fully enabled to create dynamic HTML: JavaScript can add, change, and remove all the HTML elements and attributes in the page. JavaScript can change all the CSS styles in the page. JavaScript can react to all existing events in the page. JavaScript can create new events in the page. From WIkipedia DOM Access to html Note that the root of the html document is not the same as the root element 52 2/19/2018 26

Node Object HTML elements are of type Node/Element/HTMLElement (inheritance hierarchy) You can get a handle to a node, and modify its appearance Methods of Document can return An Element object (e.g., getelementbyid) A NodeList object (e.g., getelementsbytagname) Notice whether the method uses singular or plural 53 Example Changing Styles An easy way to change the appearance of an element is to change its class attribute... <style type="text/css">.blue {color:blue;}.red {color:red;} </style> <script> function change() { var y = document.getelementbyid("x4"); y.classname="red"; } </script>... <p id="x4" class="blue">hello World</p> class is a reserved name in JavaScript, so the class property is classname HTMLElement is a subclass of Element 54 2/19/2018 27

Illustrates Response to an event Example Hello DOM Modification of the style property of a node Actions Obtain a handle to an html element Modify the html element 55 Html Hello DOM Example y is a Node object (not an array) <head>... <script> function change() { var y = document.getelementbyid("x1"); y.style.color="red"; } </script> Level 2 CSS2Properties object </head> <body style="color:blue;"> <form method= get" action= HelloDOM > <h2 id="x1" style="color:blue;">hello World</h2> <input type="button" onclick="change()" value="change appearance" /> </form> Clicking the button invokes the change() function </body> Attributes are usually set as properties 56 2/19/2018 28

Example Changing Element Contents function change() { var y = document.getelementbyid("x3"); y.innerhtml="hello Text"; } innerhtml is an element property that corresponds to all the markup and content within the element Setting an innerhtml property parses html text into the html tree Same html as last example Do not use innerhtml when inserting plain text; instead, use node.textcontent innerhtml is a useful relic of older DOM specs DOM-HelloText.html 57 Instantiate a sub-tree Manipulate the sub-tree Insert into the HTML tree Example Insert a Sub-Tree 58 2/19/2018 29

Pure DOM HTML Change DOM provides methods to delete, create, clone, and insert branches within the DOM tree function change() { var y = document.getelementbyid("x6"); var text = document.createtextnode( DOM text"); y.appendchild(text); } p... <p id="x6" class="blue"> Hello World</p> Hello world DOM text DOM-HelloDOMText.html 59 jquery Did you notice that the combination of DOM and JavaScript is not elegant? With the emergence of Ajax, the importance of client side scripting is greatly increased Solution jquery Cross-browser JavaScript library jquery name is misleading it has little to do with queries 60 2/19/2018 30

What is jquery A JavaScript client-side library (most popular) Used by over 72% of the most popular Web sites (over 96% of sites with known JS libraries) Free (MIT license) Open source Provides for plug-ins (many libraries available) 61 jquery Library Options Refer to the latest Web version of the library Refer to a particular library in the same directory as your html Download a copy of the most recent library from the jquery Web site Place the downloaded file in your NetBeans application top-level directory or the directory holding your jquery htm files Reference it in your JSP or htm http://jquery.com/download/ <script src="jquery-2.2.3.min.js"> </script> jquery 2.x may not be compatible with IE 62 2/19/2018 31

Hello jquery World <head> <script src="http://code.jquery.com/jquery-latest.js"> </script> <script> $(document).ready(function() { $("a").click(function() { alert("hello world!"); }); }); </script> </head> <body> <a href="">link</a> </body> Event (e.g., ready) function parameter is typically an anonymous function $ is a valid JavaScript identifier, and represents the jquery function (i.e., $( ) constructs a new jquery object) The jquery ready function provides a handler to execute when the page is ready to be manipulated (although maybe not fully loaded) 63 jquery Versions You can reference the jquery version you have downloaded in a script tag, as in <script </script> src="jquery-2.2.3.min.js"> Alternatively, you can reference the latest jquery version, as in <script src="http://code.jquery.com/jquery-latest.js"> </script> Using the latest version is OK for this class, but not for a production environment (QA before using a new release) 64 2/19/2018 32

A Closer Look <head> <script src=" http://code.jquery.com/jquery-latest.js "></script> <script> $(document).ready( function() { $("a").click(function() { alert("hello world!"); }); }); </script> </head> <body> <a href="">link</a> </body> </html> Anonymous handler function $( ), a jquery selector, constructs a new jquery object that contains html elements: $(document) document object $( a ) - all anchor elements in the page The click() and ready() functions are methods of the jquery object that define events. click() binds a click event to all selected elements The click function replaces the use of the JavaScript onclick event handler (and we do not need onclick for every anchor tag) 65 Binding of Handler to All Selected Elements <script> $(document).ready(function() { $("a").click(function() { alert("hello world!"); }); }); </script> </head> <body> <a href="">link</a> <br /> <a href="">2nd Link</a>... jquery statement binds the alert dialog to a click on any of the anchor tags Clicking on either link results in the dialog box appearing 66 2/19/2018 33

jquery Manipulation A jquery manipulation statement consists of jquery selector jquery manipulation method (usually to manipulate the DOM) $("#orderedlist").addclass("red"); Adds a class attribute to each of the matched elements as in <xxxx class= red > 67 Event Handlers Bound to Events You bind an event handler to a JavaScript event for a collection of elements For every onxxx event, there is a jquery equivalent Check jquery events JavaScript Event jquery Collection of elements JS event Event handler blur change click focus load submit etc. blur() change() click() focus() hover() 2 handlers load() submit() $("a").click(function() { alert("hello world!"); }); 68 2/19/2018 34

Binding Events to Functions $("a").click(function() { alert("hello world!"); }); The example above uses an event helper method (anonymous function) Full syntax (which you would probably not use): $("a").bind( click, function); 69 jquery - AJAX jquery allows easy, browser-consistent use of Ajax Example $('#result').load('test.html'); Fetches data from a server Sets the html contents of the matched element to the return data Optional parameters for 1) data sent to server and 2) callback function Note that the call is asynchronous, and in this case there is an implicit callback function that inserts the result in the selected elements 70 2/19/2018 35

Example Insert the html below (test.html) into the page <br /><h3>this is a test</h3><br /> Access the page and try the example (and look at test.html) Example at: http://www.cs.stonybrook.edu/~cse336/jquery-loadexample.html 71 Example <script> $(document).ready(function() { $("#driver").click(function(event){ $("#stage").load("test.html"); }); }); </script> </head> <body> test.html contains <br /><h3>this is a test</h3><br /> <p id="p1">click on the button to load test.html file:</p> <div id="stage" style="background-color:blue;">stage</div> <input type="button" id="driver" value="load Data" /> </body> 72 2/19/2018 36

jquery load() Method Loads data from a server and puts the returned data into the selected element Syntax: $(selector).load(url, [data], [callback]); URL - the URL you wish to load (required) data - a set of query string key/value pairs to send with the request (optional) callback - name of a function to be executed after the load() method is completed (optional) You may not need the callback function if you are just loading an error message into a component Some filtering of the returned data might be done (e.g., remove <html> tag 73 Callback Function The optional callback parameter to the load function specifies a callback function to run when the load() method is completed Callback function parameters: responsetxt - contains the resulting content if the call succeeds statustxt - contains the status of the call xhr - contains the XMLHttpRequest object 74 2/19/2018 37

jquery Ajax Style Note that the jquery handler can (and usually does) include an anonymous function that also includes more jquery $(document).ready(function() { $("#driver").click(function(event){ $("#stage").load("test.html"); }); }); Event object 75 Let s Try That Example Again <script> $(document).ready(function() { $("#driver").click(function(event){ $("#stage").load("http://www.stonybrook.edu/"); }); }); </script> </head> <body> <p id="p1">click on the button to load the html file:</p> <div id="stage" style="background-color:blue;">stage</div> <input type="button" id="driver" value="load Data" /> </body> The load failed 76 2/19/2018 38

Same Origin Policy The same origin policy is an important security concept for browser-side programming languages, such as JavaScript The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions prevents access to most methods and properties across pages on different sites Reference: http://en.wikipedia.org/wiki/same_origin_policy 77 jquery Same Origin Example <body> URL to load is in the same directory as this html <b>successful Response (should be blank):</b> <div id="success ></div> <b>error Response:</b> <div id="error">no error</div> <script> $("#success").load("test.html", function(response, status, xhr) { XmlHttpRequest object if (status == "error") { var msg = "Sorry but there was an error: "; $("#error").html(msg + "Status:" + xhr.status + " " + "StatusText:"+ xhr.statustext); } }); </script> </body> Result of call to load Callback function invoked after response is inserted http://www.cs.stonybrook.edu/~cse336/ajax-example2.html 78 2/19/2018 39

Same Origin Example <body> http://www.cs.stonybrook.edu/~cse336/ajax-example2.html <b>successful Response (should be blank):</b> <div id="success"></div> <b>error Response:</b> <div id="error"></div> <script> $("#success").load( "http://www3.cs.stonybrook.edu/~cse336/test.html", function(response, status, xhr) { if (status == "error") { var msg = "Sorry but there was an error: "; $("#error").html(msg + "Status:" + xhr.status + " " + "StatusText:"+ xhr.statustext); } }); </script> </body> First, access this page in your browser. Then download and Invoke the html locally to see the error Insert not allowed because inserted html on different site 79 Sample jquery Ajax Methods Approximately equivalent to the load function Method $.get( ) $.post( ) serialize() $.getjson() Description Loads data from a server using an AJAX HTTP GET request Loads data from a server using an AJAX HTTP POST request Encodes a set of form elements as a string for submission (method of the jquery form object) Loads JSON-encoded data from a server using an AJAX HTTP GET request get and post functions include an optional data parameter (2 nd parameter) 80 2/19/2018 40

To request data from the server Sending an Ajax Request Compose a query string Append the query string to the URL or specify the query string as the second parameter to the function (load, get, or post) Ajax request sent when the enclosing event is triggered 81 Example 82 2/19/2018 41

Example JSP AjaxJqueryExample.jsp <script> $(document).ready(function() { $("#driver").click(function(event) { var querystring = $("#i").prop("value"); var url = "http://localhost:8080/cse336-2017/jqueryajaxparameterexample? input=" + querystring; $("#p").load(url); Note the prop method will return the changed value, attr method will not });}); </script> </head> <body> <p id="p1">enter text and click the button</p> <input id="i" type="text" value="default" /> <input type="button" id="driver" value="load Data" /> <br /><div id="p"></div> </body> 83 Example - Servlet JqueryAjaxParameterExample.java... PrintWriter out = response.getwriter(); try { String s2 = request.getparameter("input"); if (s2 == null) { out.println( null ); } else { out.println( The parameter value is + s2); } 84 2/19/2018 42

Sequence Diagram Simplifications Do not show client DOM manipulations in your sequence diagrams 85 2/19/2018 43