Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server...

21
Servlet Communication • Other Servlets, HTML pages, objects shared among servlets on same server • Servlets on another server with HTTP request of the other

Transcript of Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server...

Page 1: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Servlet Communication

• Other Servlets, HTML pages, objects shared among servlets on same server

• Servlets on another server with HTTP request of the other

Page 2: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Using Other Server Resourse

• Have servlet make an HTTP request (working with URL’s)

• Make a request with RequestDispatcher object if resource available on server that is running servlet.

Page 3: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Creating an URL

URL gamelan = new URL("http://www.gamelan.com/pages/");URL gamelanGames = new URL(gamelan, "Gamelan.game.html");URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html");

Page 4: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

getProtocol Returns the protocol identifier component of the URL.

getHost Returns the host name component of the URL.

getPort Returns the port number component of the URL. The getPort method returns an integer that is the port number. If the port is not set, getPort returns -1.

getFile Returns the filename component of the URL.

getRef Returns the reference component of the URL.

Parsing a URL

Page 5: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Working with URL’s

• try {• URL yahoo = new URL("http://www.yahoo.com/");• URLConnection yahooConnection =

yahoo.openConnection();

• } catch (MalformedURLException e) { // new URL() failed

• . . .• } catch (IOException e) { //

openConnection() failed• . . .• }

Page 6: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

import java.net.*;import java.io.*;

public class URLReader { public static void main(String[] args) throws Exception {

URL yahoo = new URL("http://www.yahoo.com/");BufferedReader in = new BufferedReader(

new InputStreamReader(yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

in.close(); }}

Page 7: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

import java.net.*;import java.io.*;

public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine;

while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }}

Page 8: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

• import java.io.*;• import java.net.*;

• public class Reverse {• public static void main(String[] args) throws Exception {

• if (args.length != 1) {• System.err.println("Usage: java Reverse "• + "string_to_reverse");• System.exit(1);• }

• String stringToReverse = URLEncoder.encode(args[0]);

• URL url = new URL("http://java.sun.com/cgi-bin/backwards");• URLConnection connection = url.openConnection();• connection.setDoOutput(true);

• PrintWriter out = new PrintWriter(•

Page 9: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

connection.getOutputStream());out.println("string=" + stringToReverse);out.close();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

in.close(); }}

Page 10: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

RequestDispatcher

• Get a RequestDispatcher for the resource.

• Forward the client request to that resource, having it reply to the user's request.

• Include the resource's response in the servlet's output.

Page 11: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Using Other Server Resources

• Use getRequestDispatcher() to return RequestDispatcher object associated with URL of resource

• /servlet/myservlet

• /servlet/tests/MyServlet.class

• /myinfo.html

Page 12: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

public class BookStoreServlet extends HttpServlet {

public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the dispatcher; it gets the main page to the user RequestDispatcher dispatcher = getServletContext().getRequestDispatcher( "/examples/applications/bookstore/bookstore.html"); ... }}

Page 13: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Prepare for Errorspublic class BookStoreServlet extends HttpServlet {

public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the dispatcher; it gets the main page to the user RequestDispatcher dispatcher = ...;

if (dispatcher == null) { // No dispatcher means the html file can

not be delivered response.sendError(response.SC_NO_CONTENT);

} ... }}

Page 14: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Forwarding Request

• Resource associated with RequestDispatcher given responsibility for replying to request.

• If ServletOutputStream on original, Exception thrown.

• If already started reply, use inlcude

Page 15: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Forwarding a Request

public class BookStoreServlet extends HttpServlet {

public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // Get or start a new session for this user HttpSession session = request.getSession(); // Send the user the bookstore's opening page dispatcher.forward(request, response);

... }}

Page 16: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Include

• Calling servlet uses associated resource for part of reply.

• Called resource cannot set headers

• Caller can use output steams before and after call.

Page 17: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Include Order Summarypublic class ReceiptServlet extends HttpServlet {

public void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ // Process a customer's order ... // Thank the customer for the order res.setContentType("text/html"); PrintWriter toClient = res.getWriter(); ... toClient.println("Thank you for your order!");

// Get the request-dispatcher, to send an order-summary to the client RequestDispatcher summary = getServletContext().getRequestDispatcher( "/OrderSummary");

Page 18: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

// Have the servlet summarize the order; skip summary on error. if (summary != null) try { summary.include(req, res); } catch (IOException e) { } catch (ServletException e) { }

toClient.println("Come back soon!"); toClient.println("</html>"); toClient.close();}

Page 19: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Sharing Resources

• On same server, single applications share resources

• Use ServletContext interfaces methods: setAttribute, getAttribute, removeAttribute

• Name as with packages• examples.bookstore.database.BookDBFrontEnd

Page 20: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Setting an Attribute• In init()• Check for attribute and set if not found.• public class CatalogServlet extends HttpServlet {

• public void init() throws ServletException {• BookDBFrontEnd bookDBFrontEnd = ...

• if (bookDBFrontEnd == null) {• getServletContext().setAttribute(• "examples.bookstore.database.BookDBFrontEnd",• BookDBFrontEnd.instance());• }• }• ...• }

Page 21: Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.

Getting an Attributepublic class CatalogServlet extends HttpServlet {

public void init() throws ServletException { BookDBFrontEnd bookDBFrontEnd = (BookDBFrontEnd)getServletContext().getAttribute( "examples.bookstore.database.BookDBFrontEnd");

if (bookDBFrontEnd == null) { getServletContext().setAttribute( "examples.bookstore.database.BookDBFrontEnd", BookDBFrontEnd.instance()); } }...}