html5-img
1 / 21

Servlet Communication

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)

lucian
Télécharger la présentation

Servlet Communication

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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.

  3. 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");

  4. Parsing a URL • 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.

  5. 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 • . . . • }

  6. 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(); } }

  7. 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(); } }

  8. 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(

  9. 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(); } }

  10. 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.

  11. Using Other Server Resources • Use getRequestDispatcher() to return RequestDispatcher object associated with URL of resource • /servlet/myservlet • /servlet/tests/MyServlet.class • /myinfo.html

  12. 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"); ... } }

  13. Prepare for Errors 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 = ...; if (dispatcher == null) { // No dispatcher means the html file can not be delivered response.sendError(response.SC_NO_CONTENT); } ... } }

  14. Forwarding Request • Resource associated with RequestDispatcher given responsibility for replying to request. • If ServletOutputStream on original, Exception thrown. • If already started reply, use inlcude

  15. 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); ... } }

  16. Include • Calling servlet uses associated resource for part of reply. • Called resource cannot set headers • Caller can use output steams before and after call.

  17. Include Order Summary public 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");

  18. // 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(); }

  19. Sharing Resources • On same server, single applications share resources • Use ServletContext interfaces methods: setAttribute, getAttribute, removeAttribute • Name as with packages • examples.bookstore.database.BookDBFrontEnd

  20. 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()); • } • } • ... • }

  21. Getting an Attribute public 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()); } } ... }

More Related