Chapter 11

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

Distributed Computing, Liu Instructor’s Manual w/ Solutions

Chapter 11
Chapter 11
Internet Applications- Part 2

Lecture Suggestions

 Unless you desire otherwise, focus your students’ attention to the protocols and
APIs introduced rather than to the development of aesthetic web pages.
Students are expected to be able to use HTML to compose basic web pages, but
should be discouraged from spending undue effort in the presentation of web
pages.
 The common thread of the chapter is the HTTP: all the toolkits and protocols
introduced in the chapter are built on top of HTTP.
 Inevitably, you will have some students in your class who have had experience
with Internet programming using Perl, .net, etc. Explain to them that all these
toolkits have correlation with servlets and encourage them to identify the
correlations as they are introduced to servlets.
 Emphasize the availability of session objects as a server-side session state data
repository, as opposed to cookies, which reside on the client-side.
 Encourage your students to write client programs to access as many free SOAP
services as possible (see reference 16.)
 In presenting servlets, run each code samples in-class after going over the code.
 In presenting SOAP services:
o run a client program in-class to access a SOAP service as possible on
xmethod.com (see reference 16.)
o create a simple SOAP service in class and go through the steps of how to
deploy it
o explain that there are two styles of SOAP requests and responses. In the
book, the Remote Procedure Call (RPC) style is presented. An alternate
style encodes the requests and responses as Web documents, so that they
are interpreted just like other web contents.

How This Chapter Fits

This chapter continues where Chapter 9 left off. It introduces the students to Java-
based Internet software development tools: Java applets and Java Servlets, and to
web services by way of the Simple Object Access Protocol (SOAP).

Solutions to Chapter Exercises


Applet Exercises
2.
It is permissible for an applet to make a network connection to the same host from which it
was downloaded, hence the applet should successfully make the socket connection.
3.
It is not permissible for an applet to make a network connection to the a host other than the
one from which it was downloaded, hence the applet should fail to make the socket
connection.

©2004 Addison Wesley


1
Distributed Computing, Liu Instructor’s Manual w/ Solutions
Chapter 11

Servlets Exercises
2.

The resulting browser display is shown below:

Behind the scene:


When the browser issues the request to the Tomcat server, it specifies the
servlet as the URI. The Tomcat Server loads the servlet to its servlet engine
and runs it. The servlet’s output, which is an HTML page generated
dynamically, is returned to the browser as the HHTP response.

Yes, it is possible to browse to


http://pilsner:8080/examples/servlet/HelloWorld if the Tomcat server is
running on that machine (pilsner) at the default port (8080)

c.
Compile the Counter1.java file, and install the resulting class file Counter1.class to the
<servlet class file directory>. Then browse to it using the <servlet URL path>. Refresh
the browser repeated to run the Counter1 servlet several times. Describe the counter value
displayed by the browser successively.
The value starts at 1 and is incremented by 1 with each successive refresh of
the page (which causes the servlet to be re-executed).

d.
Open another browser and browse to the Counter1 servlet. Describe the counter value
displayed by the browser.
The increment of the counter value continues. The same servlet is executed
for both browser sessions. As a result, the same counter value is shared.

e.
Close the browser windows. Then reopen a browser window and browse to the Counter1
servlet. Describe the counter value displayed by the browser.
The counter value continues. The same servlet is executed for the new
browser session. The servlet persists once it is initiated, even when no active
browser session calls for it.

f.

©2004 Addison Wesley


2
Distributed Computing, Liu Instructor’s Manual w/ Solutions
Chapter 11
Find the “stopServer” shortcut icon on your desktop. When you click on it, a console
window will open to run a stopServer.bat batch file in the <install_dir>, which stops the
Tomcat servlet engine.
Restart the engine using the startServer desktop shortcut. Then refresh the browser windo
so that the Counter1 servlet is re-executed. Describe the counter value displayed by the
browser.
Based on the experiments with Counter1, describe the lifetime of a servlet in
the environment of the Tomcat Server.
In this environment, a servlet persists once it has been started, until such time
as when the servlet engine is shut down.

h.
Modify Counter1.java so that the counter value is incremented by 2 each time.
Recompile and refile the class file. NOTE: Because a servlet is persistent, you must
shutdown the server and restart it before the new servlet will take effect. Show the
code change.

private synchronized void increment(PrintWriter output){


output.println("This servlet has been" +
" accessed " + counter + " times.");
counter = counter + 2;
} //end increment

j.
Compile GetForm.java and PostForm.java. and install the resulting class files to the
<servlet class file directory>.
Making sure that your servlet engine is active, browse the page GetForm.html then
PostForm.html. Did the servlets run? Compare the outputs – including the URL
displayed in the browser -- with those generated using CGI scripts in the previous
lab.
The outputs are similar. With the GetForm, the URL displayed in the browser
looks like:
http://localhost:8080/examples/servlet/GetForm?
name=john&quest=happy&color=chartreuse&swallow=african&text=Live+o
r+die%21
and the name-value pairs in the query string are displayed in the browser window.

With the PostForm, the URL displayed is


http://localhost:8080/examples/servlet/PostForm
and the name-value pairs in the query string are displayed in the browser
window.
3.
Write an HTML web form and the accompanying servlet for a login
<html>
<head>
<title>Login</title>
</head>
<body bgcolor="#FFFF99">
<form method="post" action="postForm.cgi">
<H2> Please login: </H2>
Name: <input name="name"><P>
Password: <input name="quest"><P>
<input type="submit" value="Submit">
</form>
<hr>
</body> ©2004 Addison Wesley
</html> 3
Distributed Computing, Liu Instructor’s Manual w/ Solutions
Chapter 11

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Login extends HttpServlet {

public void doPost (HttpServletRequest req,


HttpServletResponse res)
throws ServletException, IOException
{
//The content type of the response body
// should be set first
res.setContentType("text/html");

//Get an output stream to write the response body


ServletOutputStream out = res.getOutputStream();
String homepage = "http://www.csc.calpoly.edu/~mliu/",
name = null, password=null;
String theName = "lucky", thePassword="12345";

name = req.getParameter("name").trim( );
password = req.getParameter("password").trim( );

if (name.equals(theName) && password.equals(thePassword))


out.println("<html><head><META HTTP-EQUIV"+
"=\"REFRESH\" CONTENT=\"0;URL=" + homepage
+ "\"></head></html>\n");
else
out.println("<html><h2>Sorry, invalid account "+
" information</h2></html>");

}
} //end class

SOAP Exercises

3. Consider the following HTTP response:


HTTP/1.1 200 OK
Connection: close
Content-Length: 499
Content-Type: text/xml; charset=utf-8
Date: Wed, 28 Mar 2001 05:05:04 GMT
Server: UserLand Frontier/7.0-WinNT
<?xml version="1.0"?>
<SOAP-ENV:Envelope SOAP-ENV:
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"

©2004 Addison Wesley


4
Distributed Computing, Liu Instructor’s Manual w/ Solutions
Chapter 11
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance">
<SOAP-ENV:Body>
<m:getStateNameResponse xmlns:m="http://www.soapware.org/">
<Result xsi:type="xsd:string">South Dakota</Result>
</m:getStateNameResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Mark up the text to identify the SOAP components
in the response.

4. Write a SOAP service (interface and class) which provides two methods: (i) add, which
accepts two integers and return the sum, and (ii) subtract,which accepts two integers
and return the difference. Deploy it. Write a client program which invokes the two
methods and process the outcomes.
The README file
CalService -- a SOAP service sample

1. To make the service available, build CalService.class


and copy the onjava folder to
<TOMCAT_HOME>/webapps/soap/WEB-INF/classes/,
resulting in the files being in the
<TOMCAT_HOME>/webapps/soap/WEB-INF/classes/onjava/ directory.

The rest of the steps are to be run from the folder created above:
2. Run deploy.bat, which contains this command:
java org.apache.soap.server.ServiceManagerClient
http://localhost:8080/soap/servlet/rpcrouter
deploy DeploymentDescriptor.xml
3. Run list.bat, which contains this command:
java org.apache.soap.server.ServiceManagerClient
http://localhost:8080/soap/servlet/rpcrouter list
You should see the service name: urn:onjavaserver, among

©2004 Addison Wesley


5
Distributed Computing, Liu Instructor’s Manual w/ Solutions
Chapter 11
those listed.
Alternatively, You can also view this service from the Web
admin tool. Go to http://localhost:8080/soap/admin/index.html
and select the "List" button.

4. At the end of this exercise, you can undeploy the service by


executing undeploy.bat, which contains this command:
http://localhost:8080/soap/servlet/rpcrouter undeploy urn:onjavaserver

The service:

// A sample SOAP service class


// source: http://www.onjava.com/pub/a/onjava/2002/02/27/tomcat.html

package onjava;
public class CalcService {
public int add(int p1, int p2) {

return p1 + p2;
}

public int subtract(int p1, int p2) {

return p1 - p2;
}
} //end class

The client:

// A sample SOAP client class


// source: http://www.onjava.com/pub/a/onjava/2002/02/27/tomcat.html
package onjava;

import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

public class CalcClient {

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

URL url = new URL ("http://localhost:8080/soap/servlet/rpcrouter");

Integer p1 = new Integer(args[0]);


Integer p2 = new Integer(args[1]);

// Build the call.


Call call = new Call();
call.setTargetObjectURI("urn:onjavaserver");
call.setMethodName("subtract");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
Vector params = new Vector();

©2004 Addison Wesley


6
Distributed Computing, Liu Instructor’s Manual w/ Solutions
Chapter 11
params.addElement(new Parameter("p1", Integer.class, p1, null));
params.addElement(new Parameter("p2", Integer.class, p2, null));
call.setParams (params);

// make the call: note that the action URI is empty because the
// XML-SOAP rpc router does not need this. This may change in the
// future.
Response resp = call.invoke(url, "" );

// Check the response.


if ( resp.generatedFault() ) {

Fault fault = resp.getFault ();


System.out.println("The call failed: ");
System.out.println("Fault Code = " + fault.getFaultCode());
System.out.println("Fault String = " + fault.getFaultString());
}
else {

Parameter result = resp.getReturnValue();


System.out.println(result.getValue());
}
}
} //end class

The deployment descriptor:

<isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment"
id="urn:onjavaserver">
<isd:provider type="java"
scope="Application"
methods="add subtract">
<isd:java class="onjava.CalcService"/>
</isd:provider>
<isd:faultListener>org.apache.soap.server.DOMFaultListener</isd:faultListener>
</isd:service>

©2004 Addison Wesley


7
Distributed Computing, Liu Instructor’s Manual w/ Solutions
Chapter 11

©2004 Addison Wesley


8

You might also like