Web component development and JSP technology session 18

21
Ver. 1.0 Slide 1 of 21 Web Component Development With Servlet and JSP™ Technologies Objectives In this session, you will learn to: Use the asynchronous servlet mechanism Use JavaScript to send an HTTP request from a client Process an HTTP response entirely in JavaScript Combine these techniques to create the effect of server-push

Transcript of Web component development and JSP technology session 18

Page 1: Web component development and JSP technology session 18

Ver. 1.0 Slide 1 of 21

Web Component Development With Servlet and JSP™ TechnologiesObjectives

In this session, you will learn to:Use the asynchronous servlet mechanismUse JavaScript to send an HTTP request from a clientProcess an HTTP response entirely in JavaScriptCombine these techniques to create the effect of server-push

Page 2: Web component development and JSP technology session 18

Ver. 1.0 Slide 2 of 21

Web Component Development With Servlet and JSP™ Technologies

Java has the option to perform request processing asynchronously.This enables the servlet execution thread to service requests from other clients, and the generation of the response may be performed in another thread.The thread that creates the trigger condition that allows the response to be prepared is an example of asynchronous servlets.

Asynchronous Servlets

Page 3: Web component development and JSP technology session 18

Ver. 1.0 Slide 3 of 21

Web Component Development With Servlet and JSP™ Technologies

The servlet API provides a class called AsyncContext to allow for separation of request from response generation.The AsyncContext object provides access to the original HttpServletRequest and HttpServletResponse objects. This allows processing of the request and generation of the response.

Separating Request Receipt from Response Generation

Page 4: Web component development and JSP technology session 18

Ver. 1.0 Slide 4 of 21

Web Component Development With Servlet and JSP™ Technologies

The following code shows an asynchronous servlet that passes all work immediately to another thread via the handler.addJob(ac) call:protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {AsyncContext ac = request.startAsync();handler.addJob(ac);}

Asynchronous Servlet Example

Page 5: Web component development and JSP technology session 18

Ver. 1.0 Slide 5 of 21

Web Component Development With Servlet and JSP™ Technologies

The following code shows the Handler class that processes asynchronous servlet requests:package service;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import javax.servlet.AsyncContext;import javax.servlet.ServletRequest;public class Handler implements Runnable {private static final Handler self;private static final String[] words = {"long", "short", "big", "small", "clever", "foolish", "tidy","disorganized“};

Asynchronous Servlet Example (Contd.)

Page 6: Web component development and JSP technology session 18

Ver. 1.0 Slide 6 of 21

Web Component Development With Servlet and JSP™ Technologies

private Thread myThread;private boolean stop = false;private List<AsyncContext> queue = newArrayList<AsyncContext>(100);private List<AsyncContext> inProgress = newArrayList<AsyncContext>(100);static {self = new Handler();} private Handler() { } public static Handler getHandler() { return self; } public void stop() { stop = true; }

Asynchronous Servlet Example (Contd.)

Page 7: Web component development and JSP technology session 18

Ver. 1.0 Slide 7 of 21

Web Component Development With Servlet and JSP™ Technologies

public synchronized void addJob(AsyncContext job) { queue.add(job); System.out.println("Added a job, queue length is "

+queue.size()); if (myThread == null) { System.out.println("Started handler thread"); myThread = new Thread(this); myThread.start(); } } public void run() { while (!stop) { System.out.println("Handler loop running"); try {

Thread.sleep(5000 + ((int) (Math.random() * 5000)));}

Asynchronous Servlet Example (Contd.)

Page 8: Web component development and JSP technology session 18

Ver. 1.0 Slide 8 of 21

Web Component Development With Servlet and JSP™ Technologies

catch (InterruptedException ex) { ex.printStackTrace(); } // check the "queue" synchronized (this) { List<AsyncContext> l = inProgress; l.clear(); inProgress = queue; queue = l; } if (!inProgress.isEmpty()) {System.out.println("Queue contains " +inProgress.size() + " elements");// Create the new information

Asynchronous Servlet Example (Contd.)

Page 9: Web component development and JSP technology session 18

Ver. 1.0 Slide 9 of 21

Web Component Development With Servlet and JSP™ Technologies

String value = "The word is: " + words[(int) (Math.random() * words.length)] + " and the number

is: " + Math.random()* 1000000; Iterator<AsyncContext> iac = inProgress.iterator(); while (iac.hasNext()) { // generate responses AsyncContext ac = iac.next(); ServletRequest req = ac.getRequest(); req.setAttribute("value", value); System.out.println("Handler dispatching to a jsp"); ac.dispatch("asyncResponse.jsp"); } }} System.out.println("Stopping handler thread"); } }

Asynchronous Servlet Example (Contd.)

Page 10: Web component development and JSP technology session 18

Ver. 1.0 Slide 10 of 21

Web Component Development With Servlet and JSP™ Technologies

Asynchronous handlers are permitted to dispatch or forward their processing to other servlets or JSPs.Filters can also be invoked on asynchronous invocations. If the AsyncContext.dispatch call is used on a matching URL, the dispatcher type will by ASYNC.

Forwarding and Filtering

Page 11: Web component development and JSP technology session 18

Ver. 1.0 Slide 11 of 21

Web Component Development With Servlet and JSP™ Technologies

You can add one or more listeners to the AsyncContext object, using the addListener(AsyncListener) method.The AsyncListener interface must be implemented by the listener that will be notified when the following situations arise:

Starting and completion of asynchronous processingError situationsTimeout

Asynchronous Listeners

Page 12: Web component development and JSP technology session 18

Ver. 1.0 Slide 12 of 21

Web Component Development With Servlet and JSP™ Technologies

The AsyncListener interface defines the following listener methods:

onComplete(AsyncEvent)onError(AsyncEvent)onTimeout(AsyncEvent)onStartAsync(AsyncEvent)

Asynchronous Listeners (Contd.)

Page 13: Web component development and JSP technology session 18

Ver. 1.0 Slide 13 of 21

Web Component Development With Servlet and JSP™ Technologies

AJAX enables a single page to use JavaScript to fetch elements of data from the server and update the displayed page without fetching or redrawing the whole page. In AJAX, the request and response is formatted as an XML document.The following code is an example of an HTML page with asynchronous JavaScript:<html><head><title>Async JavaScript Page</title></head><body><h1>Hello World!</h1><form>

Asynchronous JavaScript Clients

Page 14: Web component development and JSP technology session 18

Ver. 1.0 Slide 14 of 21

Web Component Development With Servlet and JSP™ Technologies

<input id="inputField" type="text" onkeyup="doUpdate()"></form><div id="wisdom"></div><script type=”text/javascript”>wisdomTag = document.getElementById("wisdom");inputTag = document.getElementById("inputField");function doUpdate() {var req;if (window.XMLHttpRequest) {req = new XMLHttpRequest();} else if (window.ActiveXObject) {

Asynchronous JavaScript Clients (Contd.)

Page 15: Web component development and JSP technology session 18

Ver. 1.0 Slide 15 of 21

Web Component Development With Servlet and JSP™ Technologies

req = new ActiveXObject("Microsoft.XMLHTTP");} else {alert("AJAX not supported");}req.onreadystatechange = function() {if (req.readyState == 4 && req.status == 200) {wisdomTag.innerHTML = req.responseText;}}text = inputTag.value;req.open("GET", "update.jsp?text=" + text,true);req.send(null);}</script></body></html>

Asynchronous JavaScript Clients (Contd.)

Page 16: Web component development and JSP technology session 18

Ver. 1.0 Slide 16 of 21

Web Component Development With Servlet and JSP™ Technologies

You can send response to a request using:XMLJavaScript Object Notation (JSON)

Server Response Content in an AJAX System

Page 17: Web component development and JSP technology session 18

Ver. 1.0 Slide 17 of 21

Web Component Development With Servlet and JSP™ Technologies

Consider a page containing JavaScript code that makes an asynchronous request for update from the server, and a server-side implementation that uses the asynchronous servlet techniques.Now, if the server does not choose to respond for several minutes, the user is not inconvenienced as the body of the page is operating normally.Similarly, the resource load on the server is minimized because of the use of asynchronous servlet execution.Consequently, the response may be sent at a time convenient to the server, and the effect of server-push is achieved in an architecturally manageable way.

Combining Asynchronous Servlets With Asynchronous JavaScript

Page 18: Web component development and JSP technology session 18

Ver. 1.0 Slide 18 of 21

Web Component Development With Servlet and JSP™ Technologies

Create a servlet that generates delayed responses using the asynchronous servlet API and asynchronous JavaScript techniques.

Demo 11-1: Asynchronous Servlets and Clients

Page 19: Web component development and JSP technology session 18

Ver. 1.0 Slide 19 of 21

Web Component Development With Servlet and JSP™ Technologies

Solution:1. Create a new project and asynchronous servlet.2. Create an asynchronous client.3. Test the application.

Demo 11-1: Asynchronous Servlets and Clients (Contd.)

Page 20: Web component development and JSP technology session 18

Ver. 1.0 Slide 20 of 21

Web Component Development With Servlet and JSP™ Technologies

In this session, you learned that:To allow for separation of request from response generation, the servlet API provides a class called AsyncContext.Asynchronous handlers are permitted to dispatch or forward their processing to other servlets or JSPs.One or more listeners can be added to the AsyncContext object by using the addListener(AsyncListener) method.In pure AJAX, the request and response is formatted as an XML document.

Summary

Page 21: Web component development and JSP technology session 18

Ver. 1.0 Slide 21 of 21

Web Component Development With Servlet and JSP™ Technologies

The next session covers Lab@Home. In this session, you need to perform exercises given in the following table.

Ensure to take the required input files from the faculty for performing these exercises.

What’s Next?

Chapter Number Exercise NumberChapter 6 (Book 2) Exercise 2Chapter 7 (Book 2) Exercise 2