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

Post on 13-Jan-2016

233 views 2 download

transcript

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.

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

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

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

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

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

• 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(•

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

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.

Using Other Server Resources

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

• /servlet/myservlet

• /servlet/tests/MyServlet.class

• /myinfo.html

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

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);

} ... }}

Forwarding Request

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

• If ServletOutputStream on original, Exception thrown.

• If already started reply, use inlcude

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);

... }}

Include

• Calling servlet uses associated resource for part of reply.

• Called resource cannot set headers

• Caller can use output steams before and after call.

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

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

Sharing Resources

• On same server, single applications share resources

• Use ServletContext interfaces methods: setAttribute, getAttribute, removeAttribute

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

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

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