3.8 一般的な内容を返す:Content.jsp
3.8 一般的な内容を返す:Content.jsp
前述 のようにwebMathematica をインストールするとhttp://localhost:8080/webMathematica/Examples/Content.jsp でこのJSPに接続することができます(ご自分のサーバに接続するURLはこれとは多少異なる場合もあります).
今まで見てきた例では,どれもHTMLがブラウザに返されていましたが,いろいろなフォーマットを使った一般的な内容をWebで扱うこともできます.MSPはMSPReturn を使って任意の内容を返すことができます.次はいろいろなフォーマットがどのように返されるかの例です.ソースはwebMathematica/Examples/Content.jsp とwebMathematica/WEB-INF/Applications/ExampleUtilities/Content.m にあります.
次はこのソースです.
<%@ page language="java" %> <%@ taglib uri="/webMathematica-taglib" prefix="msp" %> <html> <head> <title>Live 3D Plotting</title> </head> <body text="#171717" bgcolor = "#ffffff"> <html> <head> <title>General Content</title> </head> <body bgcolor="#ffffff"> <h1>General Content</h1> <form action="Content.jsp" method="post"> This example takes a format type and converts a notebook into this format type. It returns the converted notebook. </p> <msp:allocateKernel> <msp:evaluate> If[ MSPValueQ[ $$button], Get[ "ExampleUtilities`Content`"]; MSPReturn @@ GeneralContent[ $$button]] </msp:evaluate> </msp:allocateKernel> <p> Please select a format: </p> <input type="submit" name="button" value="Notebook"> <input type="submit" name="button" value="PostScript"> <input type="submit" name="button" value="GIF"> </form> </body> </html>
これがMathematica のソースです.
MakeNotebook[] := UseFrontEnd[ Module[ {nb, nbobj}, nb = NotebookCreate[] ; NotebookWrite[ nb, Cell[ "A Dynamically Created Notebook", "Title"]] ; NotebookWrite[ nb, Cell[ "Converted to " <> $$button, "Subtitle"]] ; NotebookWrite[ nb, Cell[ "The date is " <> ToString[ Date[]], "Text"]] ; nbobj = NotebookGet[ nb] ; NotebookClose[ nb] ; nbobj]] GeneralContent[ fmt_] := Module[ {nbobj}, nbobj = MakeNotebook[] ; UseFrontEnd[ Switch[ fmt, "Notebook", {ToString[ nbobj, InputForm], "application/mathematica"}, "PostScript", {DisplayString[ nbobj, "EPS"], "application/eps"}, "GIF", {DisplayString[ nbobj, "GIF"], "image/gif"}, _, "Unknown format"] ]]
この例では1つの評価が変数$$button をテストします.この変数がform のボタンの1つを起動することで値を持つと,それは返すフォーマットタイプを指定するのに使われ,関数GeneralContent に渡されます.この関数のMathematica のコードは,変数が設定されるとロードされるようになっている別のパッケージにあります.GeneralContent は単純なノートブックを生成する関数MakeNotebook を呼び出します.MakeNotebook はMathematica Notebook APIとJ/Link の関数UseFrontEnd を使ってノートブックを生成します.実際にはもっと面白いノートブックが生成されるでしょう.MSPReturn はノートブックの表現形をコンテントタイプと共にサーバに返します.これがブラウザに返されます.ブラウザが適切に設定されていれば,必要なヘルパーアプリケーションが配置されます.
実際の例では,動的に生成されたノートブックがクライアントからのリクエストと共に送られた情報を使います.
特別な内容を返したい,またファイル名をその内容と一緒に使いたいという場合は,MSPReturn の引数が3つあるタイプを使うとよいでしょう.これについては「MSP関数のリファレンス 」セクションをご覧ください.
MSPPageOptions を使うと,これとは別の方法でMSPスクリプトから返される内容を設定することができます.この方法については後 で詳しく説明します.