WEBMATHEMATICA TUTORIAL

Basic Examples

This covers a number of initial examples of webMathematica. Many of these can be copied and used as the basis for your own work.

These examples are a form of JavaServer Pages (JSPs) that use a special library of tags that work with Mathematica. JSPs support the embedding of Java into HTML, and are frequently used with Java Servlets to develop large dynamic websites. The library of tags is called the MSP Taglib and will work on any compliant servlet engine. One advantage of the use of a tag library is that it can completely hide any use of the Java programming language; this is the case with the MSP Taglib.

Here, you can learn the basics of webMathematica scripts. This requires some knowledge of HTML, including form and input elements. A reference to HTML is included at the end of this document. If you have no understanding of form elements, it will be hard to write interactive examples for webMathematica.

The description given here will work through a collection of sample JSPs, each of which will demonstrate some detail or feature. The sources for all these examples are included in the webMathematica web application in the directory Examples (the full path in Tomcat would be webapps/webMathematica/Examples). If you followed the installation steps when you installed your server, you should be able to see these examples running live in your server. Please note that these examples are designed to be simple examples of how to program with webMathematica technology and have not been created for pleasing visual appearance.

These examples can be reached from the webMathematica home page, which you should be able to reach via http://localhost:8080/webMathematica. (You may have some other URL for accessing your server.) The home page shows examples wrapped up in a template that adds more design around the pages to give them a better visual appearance. To study the details of how to program for webMathematica, this extra design may be a distraction and it is also possible to reach the examples without using the template.

When you have finished, you may wish to look at Developing Your Own Pages. This gives some ideas for starting to develop your own site.

Hello.jsp

If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/Hello.jsp. (You may have some other URL for accessing your server.)

This example evaluates the Date[] function of Mathematica. The result changes each time the page is accessed, demonstrating that this really is a dynamic process. The source for this page is in webMathematica/Examples/Hello.jsp.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>    standard jsp headers

<html> standard html tags

<head>
<title>Hello World</title>
</head>

<body>

<h1>Hello World</h1>

<h4>Date[]</h4>
<msp:evaluate>
Date::usage evaluated by Mathematica
</msp:evaluate>

<p>Its current value is:</p>
<msp:evaluate>
Date[] evaluated by Mathematica
</msp:evaluate>

This example shows a basic use of webMathematica.

</body>
</html>

This page uses standard HTML tags as well as special webMathematica tags; these have the form <msp:tag>. The webMathematica tags are executed from the top of the page to the bottom. The contents of the <msp:evaluate> tags are sent to Mathematica for computation with the result inserted into the final page.

Working with Variables: Variables.jsp

If you installed webMathematica as described above, you should be able to connect to this MSP via http://localhost:8080/webMathematica/Examples/Variables.jsp. (You may have some other URL for accessing your server.) It demonstrates how variables are connected to input values. The source for this page is in webMathematica/Examples/Variables.jsp.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>    

<html>

<head>
<title>Assigning Variables</title>
</head>

<body>

<h1>Assigning Variables</h1>

<form action="Variables.jsp" method="post"> html form
Enter something:
<input type="text" name="input" size="10" value=" field for user input
<msp:evaluate>MSPValue[$$input, "foo"]</msp:evaluate>"
/> <br/>
<input type="image" button for activating form
src="../Resources/Images/Buttons/evaluate.gif"
alt="Evaluate"/>
</form>

<msp:evaluate>$$input</msp:evaluate> evaluated by Mathematica

This example shows how to use form variables with webMathematica.

</body>
</html>

This page is more elaborate because it contains form and input elements. These are important ways for allowing interaction from the client.

A form element is a block of HTML that may contain input elements. A form may be activated with an input of type submit; this sends the name and value associated with each input tag to the server. Here, the opening tag of the form element contains two attributes. The action attribute refers to a URL that is accessed when the form is activated. In this case, it is a relative URL that refers to the original Variables script. The method attribute tells the browser what HTTP method to use, in this case, a post method. (It is very common to use post methods.)

This example has two input tags: the first allows the user of the page to enter text, and the second specifies a button that, when pressed, will submit the form. When the form is submitted, it will send information from input elements to the URL specified by the action attribute (in this case, the same JSP). Text entered into the input tag, which uses the name input, will be assigned to the input variable $$input.

The first time the page is accessed there is no value for $$input. When a value is entered in the text field and the Evaluate button pressed, $$input gets a value that is displayed. Note that the value is a Mathematica stringif you try and enter a computation such as "5+7", no computation is actually done. If you want the input to be interpreted and evaluated by Mathematica, you need to use one of the MSP functions.

Note that the $$ prefix is used to label input variables; these are variables that are sent with the HTTP request. The use of variables is discussed further in Tips and Tricks: Variables.

MSP Functions: Expand.jsp

If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/Expand.jsp. (You may have some other URL for accessing your server.)

When the submit button is pressed, the polynomial is raised to the power and expanded, and an HTML page that contains the result is returned. The source for this page is in webMathematica/Examples/Expand.jsp. A section that shows the form tag is shown below.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>    

<html>

<head>
<title>Expanding Polynomials</title>
</head>

<body>

<h1>Expanding Polynomials</h1>

<form action="Expand.jsp" method="post">
Enter a polynomial (e.g. x+y): <br/>
<input type="text" name="expr" size="10" value="
<msp:evaluate>MSPValue[ $$expr, "x+y"]</msp:evaluate>"
/>
Enter a positive integer (e.g. 4): <br/>
<input type="text" name="num" size="3" value="
<msp:evaluate>MSPValue[ $$num, "4"]</msp:evaluate>"
/>
<input type="image"
src="../Resources/Images/Buttons/evaluate.gif" alt="Evaluate">
</form>

<msp:evaluate>
MSPBlock[{$$expr,$$num}, secure computation with input variables
Expand[$$expr^$$num]]
</msp:evaluate>

This example demonstrates expaning polynomials.

</body>
</html>

This page contains form and input tags as described in the previous example. Additionally, the msp:evaluate tag refers to the MSP function MSPBlock.

When the form is submitted, the server connects to a Mathematica kernel, in which two symbols, $$expr and $$num, are assigned to the text from the two input elements. If no text is entered, the symbols will not have any definition.

Mathematica now evaluates the contents of the msp:evaluate tag. The MSPBlock command is a programming construct, which here inspects two input variables, $$expr and $$num. If either of these has no value, MSPBlock returns a null string, which is why the first time you access the page, you do not see a result. The values of both variables are then interpreted by Mathematica. If successful, the results of interpretation are substituted into the second argument or body of MSPBlock. In this example all instances of $$expr are substituted with the parsed value of $$expr, and the same is done for $$num. The result is then evaluated, formatted, and placed in the HTML page, which is returned to the client.

Interpretation of the variables by Mathematica can fail in two ways: the input might not be valid Mathematica input (for example, f[}), or it might be dangerous input (such as ReadList["/etc/passwd"]). In both cases, the inputs are rejected and an error message generated. This demonstrates some of the security features of the system, which the Security section documents in detail. The use of variables is discussed further in Tips and Tricks: Variables.

The formatting of the result of an msp:evaluate tag is discussed in more details in Advanced Topics: Evaluation Formatting.

Graphics: Plot.jsp

If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/Plot.jsp. (You may have some other URL for accessing your server.)

This example generates a plot. The source for this page is in webMathematica/Examples/Plot.jsp. A section that shows the form tag is shown below.

<form action="Plot.jsp" method="post">
Enter a function:
<input type="text" name="fun" size="24" value="
${msp:evaluate('MSPValue[$$fun, "Sin[x]^2"]')}"/> remember input settings from one call to the next
Enter a number:
<input type="text" name="x1" size="24" value="
${msp:evaluate('MSPValue[$$x1, "10"]')}"/>
<input type="image"
src="../Resources/Images/Buttons/plot.gif" alt="Plot">
</form>

The example shows the use of the MSP functions MSPBlock and MSPShow. MSPBlock is a programming construct introduced in the previous section. MSPShow takes the Mathematica graphics object from the Plot command and generates a GIF image, which is stored on the server, returning an <img> tag. A further discussion on formatting mathematics and graphics is given in the section on Displaying Mathematics and Graphics. Note how the page uses MSPValue to keep the user input each time the page is used.

Typeset Images: Integrate.jsp

If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/Integrate.jsp. (You may have some other URL for accessing your server.)

This example allows the user to enter a function to be integrated. The result is then formatted by the typesetting system and saved as an image. The source for this page is in webMathematica/Examples/Integrate.jsp. A section that shows the form tag is shown below.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

<head>
<title>Integrate A Function</title>
</head>

<body>

<h1>Integrate A Function</h1>

<form action="Integrate.jsp" method="post">

<msp:evaluate>
integrand = Null; kernel request variable to hold the integrand
If[ MSPValueQ[ $$expr],
integrand = MSPToExpression[$$expr]]; interpret input with secure conversion
</msp:evaluate>

Input:<br/>
<input type="text" name="expr" size="24"
value="<msp:evaluate>MSPValue[ $$expr, "Sin[x]^2"]</msp:evaluate>"/>

<input type="image"
src="../Resources/Images/Buttons/evaluate.gif" alt="Evaluate">
</form>

<msp:evaluate>
If[integrand =!= Null,
MSPFormat[Integrate[integrand,x], StandardForm]] carry out the integration
</msp:evaluate>
This example shows how to generate typeset output with webMathematica.

</body>
</html>

In this example, an msp:evaluate tag integrates an expression and uses MSPFormat to format the result with StandardForm. This generates an image and returns a reference to the image. For this to work, it is necessary to use the Mathematica front end.

The example also demonstrates the use of page variables with MSPToExpression. This is an alternative to using MSPBlock suitable in certain constructions, for example, when the input will be used in a number of computations. The page variable integrand is initialized to Null and later, if its value has been modified, the integration is carried out. It is assigned to the interpreted value of $$expr only if this input variable actually has a value. Note that if an error, such as a security error, is encountered in interpreting $$expr, an exception will be thrown and integrand will remain assigned to Null.

Note that MSPToExpression applies a security check to the input variable. You should be aware that input variables are a major source of danger and always use the secure conversion functions MSPBlock and MSPToExpression. In particular, you should never use ToExpression on an input variable. The Security section documents the security system in more detail.

It is also possible to return the result using MathML; this is described in greater detail in the section on MathML. A further discussion on formatting mathematics and graphics is given in the section on Displaying Mathematics and Graphics.

An interesting point about the first msp:evaluate tag is that it contains two Mathematica commands. To use two commands in the same tag, they can be separated with a semicolon ';'. In addition, the last command is also followed by a semicolon. This makes sure that no output from the tag is inserted into the output page. More information on adding code into webMathematica pages is given in Tips and Tricks: Coding in Pages.

Live 3D Plotting: Plot3DLive.jsp

If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/Plot3DLive.jsp. (You may have some other URL for accessing your server.) It allows the user to enter a function to be plotted by the LiveGraphics3D applet. The source for this page is in webMathematica/Examples/Plot3DLive.jsp.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

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

<body>

<h1>Live 3D Plotting</h1>

<form action="Plot3DLive.jsp" method="post">
Plot3D of
<input type="text" name="fun" size="22" value="
${msp:evaluate('MSPValue[ $$fun, "Sin[x y]^2"]')}"/> <br/>
x from:
<input type="text" name="x0" size="10" value="
${msp:evaluate('MSPValue[ $$x0, "-2"]')}"/>
to:
<input type="text" name="x1" size="10" value="
${msp:evaluate('MSPValue[ $$x1, "2"]')}"/> <br/>
y from:
<input type="text" name="y0" size="10" value="
${msp:evaluate('MSPValue[ $$y0, "-2"]')}"/>
to:
<input type="text" name="y1" size="10" value="
${msp:evaluate('MSPValue[ $$y1, "2"]')}"/> <br/>
Number of points to plot:
<input type="text" name="pts" size="5" value="
${msp:evaluate('MSPValue[ $$pts, "20"]')}"/> <br/>
<input type="image"
src="../Resources/Images/Buttons/evaluate.gif" alt="Evaluate">
</form>

<msp:evaluate>
$ImageBackground = "#ffffff";
$ImageSize = {300,300};
</msp:evaluate>

<msp:evaluate>
MSPBlock[{$$fun, $$x0, $$x1, $$y0, $$y1, $$pts},
MSPLive3D[
Plot3D[$$fun, {x, $$x0, $$x1}, {y, $$y0, $$y1}, PlotPoints -> $$pts]]
]
</msp:evaluate>

This example shows how to use live three-dimensional graphics with webMathematica.

</body>
</html>

This example uses a number of evaluations to set up parameters. The last evaluation takes the values of these parameters and uses them in a call to Plot3D. The result of this goes to MSPLive3D, which calls the LiveGraphics3D applet. This gives a real-time rotation of the three-dimensional graphics object. More information is found in the section Mathematics and Graphics: LiveGraphics3D.

Getting Messages: Messages.jsp

This example demonstrates how messages and print output generated by Mathematica can be returned in the web page. If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/Messages.jsp. (You may have some other URL for accessing your server.) The source for this page is in webMathematica/Examples/Messages.jsp.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

<head>
<title>Message and Print</title>
</head>

<body>

<h1>Message and Print</h1>

<h4>
Input is 1/0
</h4>

<msp:evaluate>
1/0
</msp:evaluate>

<h4>
Input is Sin[x,1]
</h4>

<msp:evaluate>
Sin[x,1]
</msp:evaluate>

<h4>Input is Print["The result is ", x^2];5.6</h4>

<msp:evaluate>
Print["The result is ", x^2];5.6
</msp:evaluate>

The messages were:

<msp:evaluate>
ColumnForm[MSPGetMessages[]] messages displayed here
</msp:evaluate>

<p>The print output was:</p>

<msp:evaluate>
ColumnForm[MSPGetPrintOutput[]] print output displayed here
</msp:evaluate>

These are some evaluations that will cause messages to be
generated by Mathematica. There is also a Mathematica print
statement.

</body>
</html>

The contents are very simple; there are two evaluations that cause messages to be generated. These are followed by uses of MSPGetMessages and MSPGetPrintOutput, both of which are formatted by ColumnForm. The messages that were generated are displayed in the resulting page.

Returning General Content: Content.jsp

If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/Content.jsp. (You may have some other URL for accessing your server.)

All of the examples up to this point return HTML to the browser, but the web can work with general content involving many different formats. MSPReturn is provided to allow an MSP to return arbitrary content. Here is an example that demonstrates how different formats can be returned. The source is in webMathematica/Examples/Content.jsp and webMathematica/WEB-INF/Applications/ExampleUtilities/Content.m.

First, here is the source.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

<head>
<title>General Content</title>
</head>

<body>

<h1>General Content</h1>

<table class="formLayout">
<tr>
<td colspan="4">
Please select a format:
</td>
</tr>
<tr>
<td>
<form action="Content.jsp" method="post" style="display: inline;">
<input type="image" src="../Resources/Images/Buttons/notebook.gif" alt="Notebook"/>
<input type="hidden" name="button" value="Notebook"/>
</form>
</td>
<td>
<form action="Content.jsp" method="post" style="display: inline;">
<input type="image" src="../Resources/Images/Buttons/pdf.gif" alt="PDF"/>
<input type="hidden" name="button" value="PDF"/>
</form>
</td>
<td>
<form action="Content.jsp" method="post" style="display: inline;">
<input type="image" src="../Resources/Images/Buttons/postscript.gif" alt="PostScript"/>
<input type="hidden" name="button" value="PostScript"/>
</form>
</td>
<td>
<form action="Content.jsp" method="post" style="display: inline;">
<input type="image" src="../Resources/Images/Buttons/gif.gif" alt="GIF"/>
<input type="hidden" name="button" value="GIF"/>
</form>
</td>
</tr>
</table>

<msp:evaluate>
    Needs["ExampleUtilities`Content`"]
</msp:evaluate>

<msp:evaluate>
If[MSPValueQ[$$button],
    MSPReturn @@ GeneralContent[$$button]
]
</msp:evaluate>

This example takes a format type and converts a notebook into
this format type. It returns the converted notebook.

</body>
</html>

Here is the Mathematica source.

MakeNotebook[fmt_] :=
Developer`UseFrontEnd[
Module[{nb, nbobj},
nb = NotebookCreate[];
NotebookWrite[nb, Cell["A Dynamically Created Notebook", "Title"]];
NotebookWrite[nb, Cell["Converted to " <> fmt, "Subtitle"]];
NotebookWrite[nb, Cell["The date is " <> ToString[Date[]], "Text"]];
SetOptions[nb, WindowSize -> {400,500}];
nbobj = NotebookGet[nb];
NotebookClose[nb];
nbobj
]
]

GeneralContent[fmt_] :=
Module[{nbobj},
nbobj = MakeNotebook[fmt];
Developer`UseFrontEnd[
AbortProtect[
Switch[fmt,
"Notebook",
{ToString[nbobj, InputForm], "application/mathematica", "Content.nb"}
,
"PostScript",
{ExportString[nbobj, "EPS"], "application/eps", "Content.eps"}
,
"PDF",
{ExportString[nbobj, "PDF"], "application/pdf", "Content.pdf"}
,
"GIF",
{ExportString[nbobj, "GIF"], "image/gif", "Content.gif"}
,
_,
"Unknown format"
]
]
]
]

In this example, one evaluation tests the variable $$button. If it has a value from activating one of the buttons in the form, this is used to specify a return format type and passed to a function, GeneralContent. The Mathematica code for this function is placed into a separate package to be loaded when the variable is set. GeneralContent calls a function that creates a very simple notebook, MakeNotebook. MakeNotebook generates a notebook using the Mathematica Notebook API and the function Developer`UseFrontEnd. In a real life situation a more interesting notebook would probably be generated. MSPReturn returns the representation of the notebook to the server with the content type. This is then returned to the browser, which, if suitably configured, will deploy the necessary helper application.

In a more advanced example, the dynamically generated notebook would probably use information sent with the request from the client.

If you wish to return special content and also set a filename to be used with this content, then you may wish to use the three-argument form of MSPReturn.

Another way to set the content returned from an MSP script is to use MSPPageOptions. The topic of returning general content is discussed later.

Interactive Web: SliderPlot.jsp

This example demonstrates webMathematica interactive web technology.

If you installed webMathematica as described above, you should be able to connect to this page via http://localhost:8080/webMathematica/Examples/Manipulate/SliderPlot.jsp. (You may have some other URL for accessing your server.) The source for this page is in webMathematica/Examples/Manipulate/SliderPlot.jsp.

First, here is the source.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

<head>
<title>Manipulate Example: Slider, Checkbox, and Plot</title>
</head>

<body>

<h1>
<span class="hm">Manipulate Example:</span><br/>
Slider, Checkbox, and Plot</h1>

<msp:evaluate>
Needs["MSPManipulate`"]
</msp:evaluate>

<msp:evaluate>
MSPManipulateHeader[$$updateArgs, $$manipulateNumber]
</msp:evaluate>

<msp:evaluate>
MSPManipulate[ Plot[ Cos[var+x], {x,0,2Pi}, Frame -> frame], {var, 0,20}, {frame, {True,False}}, OutputSize->{621, 384}]
</msp:evaluate>

Slider and Checkbox

</body>
</html>

The example has three key sections. First, the MSPManipulate` package is loaded with the Needs statement. This needs to be done in its own evaluate tag, and at the start of the page. Secondly, a special header is put down with a call to MSPManipulateHeader. This needs to refer to the variables $$updateArgs and $$manipulateNumber exactly as shown (note that you cannot rename these variables). MSPManipulateHeader initializes the interactive features. Thirdly, a particular interactive example is put down with MSPManipulate. This follows the syntax of the Manipulate function, introduced in Mathematica 6. In the example here, a slider and a checkbox are returned in the page.

More information about webMathematica interactive features is found in the section Interactive Web Tools.

Applets: TextApplet.jsp

This example demonstrates how to call on the services of a Mathematica-powered website from an applet. This shows a combination of client and server programming. The section involves some programming in Java.

If you installed webMathematica as described above, you should be able to connect to this page via http://localhost:8080/webMathematica/Examples/TextApplet.jsp. (You may have some other URL for accessing your server.) The source for this page is in webMathematica/Examples/TextApplet.jsp and webMathematica/WEB-INF/src/ExampleApplets/TextApplet.java.

First, here is the JSP source.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

<head>
<title>Text Applet Example</title>
</head>

<body>

<h1>Text Applet Example</h1>

<msp:evaluate>
If[MSPValueQ[$$Compute],
    MSPReturn["Date[] returns " <> ToString[Date[]], "text/plain"]
]
</msp:evaluate>

<applet
code="com/wolfram/msp/example/TextApplet.class"
archive = "${msp:evaluate('$ServletContextPath <> "/Resources/applets/example-applet.jar"')}"
width="400"
height="30" >
<param name="ArgumentURL" value="TextApplet.jsp?Compute=True" />
</applet>

Here is an applet that gets a result from Mathematica.

Hitting refresh will cause the page to update.

</body>
</html>

Here is the source for the applet TextApplet.java.

package com.wolfram.msp.example;

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, 20, 20);
} catch (Exception e) {
System.out.println("Error " + e);
}
}
}

This is a very simple applet; the paint method opens a connection to a URL, the name of which is formed from the document that loaded the applet, and the value of the parameter ArgumentURL, which is passed in from a param tag. This causes the TextApplet JSP to be called and return a computation of the date.

JavaScript: PlotScript.jsp

This example demonstrates how to integrate a Mathematica-powered website with JavaScript. It also demonstrates both client and server programming. The section involves some programming in JavaScript.

Note that JavaScript and Java are different languages. JavaScript is a scripting language that is useful for manipulating documents and other features of browsers. Java is a general purpose programming language that can be used in an HTML document via an applet. The two languages complement each other: JavaScript is useful for manipulating the browser and documents that are open in the browser, while Java has a more sophisticated collection of functions and can draw into the browser window. It is possible for JavaScript and Java to work together.

If you installed webMathematica as described above, you should be able to connect to this MSP via http://localhost:8080/webMathematica/Examples/PlotScript/PlotScript.jsp. (You may have some other URL for accessing your server.) The source for this page is in webMathematica/Examples/PlotScript/PlotScript.jsp and webMathematica/Examples/PlotScript/PlotScript1.jsp.

First, here is the source for PlotScript.jsp.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

<head>
<title>Plotting with JavaScript</title>
<script>
function plot(f) {
win = window.open( "PlotScript1.jsp?fun=" + URLescape(f.fun.value) + "&x1=" +
        URLescape(f.x1.value), "plot", "toolbar=none,resizeable=yes,width=450,height=350");
}
</script>
</head>

<body>

<h1>Plotting with JavaScript</h1>

<form action="Plot" method="post">
Enter a function:
<input type="text" name="fun" size="24" value="<msp:evaluate>MSPValue[ $$fun, "Sin[x]^2"]</msp:evaluate>"/> <br/>
Enter a number:
<input type="text" name="x1" size="24" value="<msp:evaluate>MSPValue[ $$x1, "10"]</msp:evaluate>"/> <br/>
<input type="image" name="button" src="../../Resources/Images/Buttons/plot.gif" onClick="plot(this.form)"/>
</form>

This example shows an example of JavaScript and webMathematica.

</body>
</html>

Second, here is the source for PlotScript1.jsp.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

<head>
<title>Plotting with JavaScript</title>
</head>

<body>

<msp:evaluate>
MSPBlock[ {$$fun, $$x1},
MSPShow[ Plot[$$fun, {x,0,$$x1},ImageSize->400]]]
</msp:evaluate>

<form action="Plot" method="post">
<input type="button" value="Close" onClick="window.close()"/>
</form>

</body>
</html>

This is a simple example given to demonstrate how a JSP can work with JavaScript. The initial page, PlotScript.jsp, puts up a page with a form of two text input elements and one submit button. When the button is clicked, it opens a new window that contains the output of PlotScript1.jsp.

Setting Variables: SetBasic.jsp

If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/SetBasic.jsp. (You may have some other URL for accessing your server.)

This example passes values computed in a JSP into Mathematica where they are used for computation by Mathematica. This example uses the Java programming language making it different from most webMathematica examples, typically these do not require any Java programming. The source for this page is in webMathematica/Examples/SetBasic.jsp and is shown below.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<html>

<head>
<title>&lt;set&gt; Tag Example</title>
</head>

<body>

<h1>&lt;set&gt; Tag Example</h1>

<jsp:useBean id="obj" class="java.lang.Object"/>

<msp:set name="var1" value="${10}"/>
<msp:set name="var2" value="String from Java"/>
<msp:set name="var3" value="${obj}"/>

<msp:evaluate>
Nest[f, x, var1]
</msp:evaluate>

<msp:evaluate>
ToCharacterCode[var2]
</msp:evaluate>

<msp:evaluate>
var3@hashCode[]
</msp:evaluate>

This example shows how a general JSP can set values in webMathematica.

</body>
</html>

In this example, a variable var1, which is an int, var2, which is a String, and var3, which is an Object, are created in the JSP. These are then passed to Mathematica using the msp:set tag. This tag takes two attributes, the name attribute gives the name that the variable will be given in Mathematica, while the value attribute refers to the value. Notice how msp:set sends a Java int as a Mathematica integer and a Java String as a Mathematica string. The Java Object is sent as a Mathematica object reference. The rules that govern how types are sent from Java to Mathematica are exactly those that J/Link uses.

Getting Variables: GetBasic.jsp

If you installed webMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/GetBasic.jsp. (You may have some other URL for accessing your server.)

This example gets values computed in Mathematica into a JSP where they are used for processing by the page. The source for this page is in webMathematica/Examples/GetBasic.jsp, and a selection is shown below.

<msp:evaluate>
num = RandomInteger[{1, 10}];
list = RandomReal[{0, 1}, num];
mean = Mean[list];
</msp:evaluate>

<msp:get name="dArray" value="list" />
<msp:get name="dValue" value="mean" />

<table cellspacing="0" cellpadding="0">
<c:forEach var="d" items="${dArray}">
    <tr><td>${d}</td></tr>
</c:forEach>
</table>

In this example, Mathematica generates a list of random numbers and computes the mean. The JSP obtains these values using the msp:get tag. The setting of the value attribute is used as a Mathematica expression to be evaluated and transmitted to Java. This is stored as a page context variable using the name attribute setting of the tag. The rules for transmission from Mathematica are that the normal J/Link type conversions will be applied, but if none of these applies, then the object will be converted into an object of type com.wolfram.jlink.Expr, a class that is provided by J/Link to represent general Mathematica expressions.

The example also makes use of extended JSP tags. It also requires programming in both Java and Mathematica. It shows how easy it would be to incorporate webMathematica into an existing JSP framework.