Documentation3. 基本的な例題

 

アプレット:TextApplet.jsp

次の例ではMathematica のパワーを使ったWebサイトをアプレットから呼び出してみます.これはクライアントとサーバプログラミングの組合せで行われます.このセクションにはJavaのプログラミングも出てきます.

前述のようにwebMathematica をインストールするとhttp://localhost:8080/webMathematica/Examples/TextApplet.jspでこのMSPに接続することができます(ご自分のサーバに接続するURLはこれとは多少異なる場合もあります).このページのソースはwebMathematica/Examples/TextApplet.jspとwebMathematica/WEB-INF/src/ExampleApplets/TextApplet.javaにあります.

これがJSPのソースです.

<%@ page language="java" %>
<%@ taglib uri="/webMathematica-taglib" prefix="msp" %>

<html>
<head>
<title>Live 3D Plotting</title>
</head>

<body text="#171717" bgcolor = "#ffffff">
<html>
<title>Applet Test</title>
<body bgcolor="#ffffff">
<p>
Here is an applet that gets a result from Mathematica:
<br>

<msp:allocateKernel>
<msp:evaluate>
   If[ MSPValueQ[ $$Compute],
      MSPReturn[ "Date[] returns " <> ToString[ Date[]], "text/plain"]]
</msp:evaluate>
<applet
   code="TextApplet"
   archive =
      "<msp:evaluate> $WebApplication <> "/Resources/applets/MSPExamples.jar"</msp:evaluate>"
   width="400"
   height="30" >
   <param name="ArgumentURL" value="TextApplet.jsp?Compute=True">
</applet>
</msp:allocateKernel>

<p>
Hitting refresh will cause the page to update.
</body>
</html>

アプレットのためのソース,TextApplet.javaは次の通りです.

import java.applet.Applet;
import java.awt.*;
import java.net.*;
import java.io.*;
public class TextApplet extends Applet
{
public void paint(Graphics g)
{
super.paint(g);
try {
URL url=new URL(getDocumentBase(), getParameter("ArgumentURL"));
InputStream in=url.openStream();
ByteArrayOutputStream out=new ByteArrayOutputStream();
byte[] b=new byte[1024]; int len;
while((len=in.read(b, 0, 1024)) != -1) {
out.write(b, 0, len);
}
b=out.toByteArray();
g.drawBytes(b, 0, b.length-1, 20, 20);
}
catch (Exception e) {
System.out.println("Error "+e);
}
}
}

これは非常に単純なアプレットです.paintメソッドがURLへの接続を開きます.そのURLはアプレットをロードしたドキュメントとparamタグから渡されたArgumentURLというパラメータの値によって名付けられています.これによってTextApplet JSPが呼ばれ,日付け計算が返されます.