| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB Compiler |
| Contents | Index |
| Learn more about MATLAB Compiler |
| On this page… |
|---|
In order to deploy the Magic Square Calculator application described in Example: The Magic Square Calculator On the Web to the Web, you must build and run your application using Java or .NET.
To create the Magic Square Calculator in Java, you must create:
The MATLAB Builder JA JAR file that is generated by compiling M-code using MATLAB, MATLAB Compiler, and MATLAB Builder JA.
The JSP entry page, responsible for taking in user input, passing it on to the servlet, and displaying the servlet's result on the page.
The servlet, responsible for instantiating the deployed component. When a request comes in, calling the M-function that returns the matrix, the M-function returns the WebFigure. The servlet then binds the WebFigure to the application cache of the server and produces HTML that displays the WebFigure and finally, the matrix.
The following procedure gives you an option to build your example Web component or download it from MATLAB Central. To download the example, go to Quick Start: Building Your Example Component.
Download the application code for this example from MATLAB Centrals File Exchange at http://www.mathworks.com/matlabcentral/fileexchange. Once you open the file exchange, search for "Java Web Example Guide End To End Chapter."
Extract the JavaEndToEnd.zip file into a working folder where you can build the application.
Start Tomcat by changing your folder to tomcat\bin and executing startup.bat.
Copy javabuilder.jar to the tomcat/common/libs folder.
Once Tomcat starts successfully, drag the JavaEndToEnd.war file into the webapps folder under the tomcat folder.
Execute the application by opening a Web browser and pointing to http://localhost:8080/JavaEndToEnd/MagicSquare/ExamplesPage.jsp.
Ensure you have a version of the Java Developer's Kit (JDK) installed that matches the version used by the MCR. See the MATLAB Compiler User's Guide reference pages for details on the mcrversion command.
Ensure you have Tomcat 5 or later on your system (other J2EE Web servers can work also, but the steps in this document have been tested with Tomcat).
Ensure the version of the MCR you have installed is the same version as the MCR running with MATLAB when the application was built. If you are unsure, check with your MATLAB programmer or whoever initially deployed the component. For more information, see Deploying a Component with the Magic Square Example in the MATLAB Builder JA User's Guide.
Make note of the folder where the MCR is installed. It will be used later when starting the applications.
Create the code for the JSP page:
Note This code uses an image resource and a cascading style sheet resource that is included if you download the code from MATLAB Central as in Quick Start: Building Your Example Component. |
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Calculation Services</title>
<%
//This section of code determines if the user has entered
// a number for the square size, if they have it overlays
// the default size which is 5.
String sizeStr = request.getParameter("size");
int size = 5;
if(sizeStr!=null && sizeStr.length()>0)
{
size = Integer.parseInt(sizeStr);
}
%>
<link rel="Stylesheet" type="text/css"
media=all href="file:./StyleSheet.css" />
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form method="get">
<div style="text-align: center">
<table width="760" cellpadding="0" cellspacing="0">
<tr>
<td><img src="header_bg.jpg" alt="Header Image Not Found"
width="779" height="72" /></td>
</tr>
</table>
<br />
<h1> Calculation Services</h1>
Calculate Magic Square
<br>
Size:
<input type="text" name="size" size="8" value="<%=size%>" >
<br>
<input type="submit" value="Calculate">
<br>
<br />
<script type="text/javascript">
try
{
//Sets up an HttpRequest object so we can call our
// servlet and dump the output to the screen
var objXHR = new XMLHttpRequest();
}
catch (e)
{
try
{
var objXHR = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e)
{
try
{
var objXHR = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e)
{
document.write('XMLHttpRequest not supported');
}
}
}
//Call the MagicSquare Servlet and pass it the
// size of the matrix to show
objXHR.open('GET','MagicSquare?size=<%=size%>',false);
objXHR.send(null);
//Display the result of the servlet on the page
document.writeln(objXHR.responseText);
</script>
<br>
</div>
</form>
</body>
</html>
Create the code for the servlet:
Note This code requires that the generated component created earlier and javabuilder.jar must be on the classpath in order to compile. |
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import java.io.IOException;
import examples.*;
import com.mathworks.toolbox.javabuilder.webfigures.WebFigure;
import com.mathworks.toolbox.javabuilder.webfigures.WebFigureHtmlGenerator;
import com.mathworks.toolbox.javabuilder.MWJavaObjectRef;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import com.mathworks.toolbox.javabuilder.MWException;
public class MagicSquareServlet extends HttpServlet
{
private MagicCalc calc;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try
{
//We initialize the deployed component in the init
// method so it doesn't get initialized with each request
calc = new MagicCalc();
}
catch(MWException e)
{
e.printStackTrace();
}
}
public void destroy()
{
super.destroy();
if(calc!=null)
{
//When the servlet gets disposed you can clean
// up the deployed component reference as well.
calc.dispose();
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//If no size has been provided, return.
String sizeStr = request.getParameter("size");
if(sizeStr==null || sizeStr.length()==0)
return;
//Convert the input parameter size to an MWArray for use with our components
MWNumericArray size = new MWNumericArray(Integer.parseInt(sizeStr));
double[][] square = new double[0][];
WebFigure figure = null;
try
{
//Call the getMagicWebFigure method and turn
// the java object reference into a WebFigure object
Object[] results = calc.getMagicWebFigure(1, size);
MWJavaObjectRef ref = (MWJavaObjectRef)results[0];
figure = (WebFigure)ref.get();
//Attach the WebFigure to the Servlets Application cache
getServletContext().setAttribute("UserPlot",figure);
//Call the getMagic method and turn the MWArray into a array of doubles
Object[] result = calc.getMagic(1, size);
MWNumericArray array = (MWNumericArray)result[0];
square = (double[][])array.toArray();
}
catch(MWException e)
{
e.printStackTrace();
}
StringBuffer buffer = new StringBuffer();
//The WebFigureHtmlGenerator class creates an HTML string that
// can be embedded into a web page and will create an iFrame
// that contains the WebFigure.
WebFigureHtmlGenerator webFigureHtmlGen =
new WebFigureHtmlGenerator("WebFigures",getServletContext());
if(figure!=null)
{
try
{
String outputString =
webFigureHtmlGen.getFigureEmbedString(
figure,
"UserPlot",
"application",
"330",
"330",
null);
buffer.append(outputString);
}
catch(Exception e)
{
e.printStackTrace();
}
}
buffer.append("<BR>");
buffer.append("<BR>");
//Step through the matrix and output it to an HTML Table
buffer.append("<TABLE >");
for (double[] row : square)
{
buffer.append("<TR>");
for (double value : row)
{
buffer.append("<TH>");
buffer.append(new Double(value).intValue());
}
}
buffer.append("</TABLE>");
buffer.append("<BR>");
//Write the embeddable html to the response
// output stream for use on the jsp page
response.getOutputStream().print(buffer.toString());
}
}
Copy the javabuilder.jar file (from MCRROOT/toolbox/javabuilder/jar/javabuilder.jar) to the webapp/WEB-INF/lib folder.
Since you a compiling a servlet which has J2EE dependencies, copy servlet-api.jar (the J2EE JAR file that comes with Tomcat) to the current working folder. This file is usually located in the Tomcat common lib folder (a J2EE JAR file can work as well).
From the root of your Projects folder we need to build the component with MATLAB by using the following mcc command:
mcc -W "java:examples,MagicCalc" -d .\scratch -T "link:lib"
-v "class{MagicCalc:.\webapp\WEB-INF\mcode\getMagic.m,
.\webapp\WEB-INF\mcode\getMagicWebFigure.m}"
Copy it from your working folder to the Web applications lib folder by typing:
xcopy /Y .\scratch\examples.jar .\webapp\WEB-INF\lib
Rebuild the servlet by typing the following command:
javac -cp servlet-api.jar;.\webapp\WEB-INF\lib\javabuilder.jar;
.\webapp\WEB-INF\lib\examples.jar;
-d .\webapp\WEB-INF\classes
.\webapp\WEB-INF\src\MagicSquareServlet.java
To rebuild the WAR file, enter:
cd webapp jar -cvf ..\JavaEndToEnd.war . cd ..
To create the Magic Square Calculator using .NET, you must create:
The MATLAB Builder NE DLL file that is generated by compiling M-code using MATLAB, MATLAB Compiler, and MATLAB Builder NE.
The DataTable implementation that converts the magic square output into something that an ObjectDataSource can use in a GridView Control.
The ASPX page and the code behind it. This page is responsible for taking in user input, displaying the controls, and handling page events.
Ensure you have .NET Framework 2.0 or later installed and Visual Studio 2005 or later.
Ensure the version of the MCR you have installed is the same version as the MCR running with MATLAB when the application was built. If you are unsure, check with your MATLAB programmer or whoever initially deployed the components. See the MATLAB Compiler User's Guide reference pages for details on the mcrversion command.
Make note of the folder where the MCR is installed. It will be used later when starting the applications.
Create the code for the DataTable implementation:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Examples;
using MathWorks.MATLAB.NET.Arrays;
public class MagicSquare
{
//This class gets the data from the generated component and loads
// it into a data structure that can be automatically used by an
// ObjectDataSource in a GridView Control
public DataTable getMagicSquare(int size)
{
//Instantiate the deployed component
MagicCalc calc = new MagicCalc();
//Convert the size into an MWArray so it can be passed in
MWArray input = size;
//call the getMagic function to get the matrix
MWNumericArray output = (MWNumericArray)calc.getMagic(input);
//Convert the matrix to a .NET double array
double[,] magicSquare =
(double[,])output.ToArray(MWArrayComponent.Real);
//Create an empty data table to put the matrix data in.
DataTable table = new DataTable();
//Since we know its a square add as many
// columns as there will be rows.
for(int i = 0; i<size; i++)
{
table.Columns.Add();
}
DataRow row;
//Iterate each element in the array creating a row out of each
for(int i = 0; i < size;i++)
{
//create a row from the table to put the data in
row = table.NewRow();
//Iterate each element in the inner array and put them into the row
for (int j = 0; j < size; j++)
{
row[j] = magicSquare[i,j];
}
//Add the row to the table
table.Rows.Add(row);
}
return table;
}
}
Create the code for the ASPX page:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register
Assembly="WebFiguresService, Version=2.8.1.0, Culture=neutral,
PublicKeyToken=e1d84a0da19db86f"
Namespace="MathWorks.MATLAB.NET.WebFigures.Service"
TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Calculation Services</title>
<link rel="Stylesheet" type="text/css"
media=all href="file:./StyleSheet.css" />
<link href="StyleSheet.css"
rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: center">
<table width="760" cellpadding="0" cellspacing="0">
<tr>
<td>
<img
src="header_bg.jpg"
alt="Header Image Not Found"
width="779"
height="72" /></td>
</tr>
</table>
<br />
<h1> Calculation Services</h1>
<asp:Label
ID="Label3"
runat="server"
Text="Calculate Magic Square">
</asp:Label>
<br />
<asp:Label
ID="Label4"
runat="server"
Text="Size: ">
</asp:Label>
<asp:TextBox
ID="TextBox3"
runat="server"
Width="61px">
5
</asp:TextBox>
<br />
<asp:Button
ID="Button2"
runat="server"
OnClick="Button2_Click"
Text="Calculate" />
<br />
<br />
<cc1:WebFigureControl
ID="WebFigureControl1"
runat="server"
Height="330px"
Width="330px" />
<br />
<br />
<asp:ObjectDataSource
ID="ObjectDataSource1"
runat="server"
SelectMethod="getMagicSquare"
TypeName="MagicSquare">
<SelectParameters>
<asp:ControlParameter
ControlID="TextBox3"
DefaultValue="5"
Name="size"
PropertyName="Text"
Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:GridView
ID="GridView1"
runat="server"
DataSourceID="ObjectDataSource1"
ShowHeader="False">
</asp:GridView>
</div>
</form>
</body>
</html>
Create the code behind the ASPX page:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Examples;
using MathWorks.MATLAB.NET.WebFigures;
using MathWorks.MATLAB.NET.Arrays;
public partial class _Default : System.Web.UI.Page
{
private MagicCalc calc = new MagicCalc();
protected void Page_Load(object sender, EventArgs e)
{
MWArray input = Int32.Parse(TextBox3.Text);
WebFigureControl1.WebFigure =
new WebFigure(calc.getMagicWebFigure(input));
}
protected void Button2_Click(object sender, EventArgs e)
{
MWArray input = Int32.Parse(TextBox3.Text);
WebFigureControl1.WebFigure =
new WebFigure(calc.getMagicWebFigure(input));
ObjectDataSource1.Select();
}
}
Build your application and deploy it using the version of IIS built into Microsoft Visual Studio as follows:
From the root of your projects folder, open the WebSite folder.
Build the component in MATLAB using the mcc command:
mcc -W "dotnet:Examples,MagicCalc,0.0,private"
-d ".\mcode\output" -T "link:lib"
-v
"class{MagicCalc:.\mcode\getMagic.m,.\mcode\getMagicWebFigure.m}"
This command creates a file in the WebSite\mcode\output folder called Examples.dll (this will be referenced from the Visual Studio project in the next step).
Open Microsoft Visual Studio 2005 and select File > Open > Web Site.
Browse to the WebSite folder and open it.
Confirm that Examples.dll is added correctly as a reference. If there were any errors or issues adding it, delete it and add a new reference to the DLL you built in the WebSite\mcode\output folder.
Microsoft Visual Studio Designer View of the Magic Square Calculator

Select Build > Build Solution. You should build with no errors. If there are errors, ensure that:
The MCR is installed.
Examples.dll has been added as a reference in your project.
When you have built successfully, select Debug > Start Debugging. A local IIS server starts and opens your page inside of it.
![]() | Example: The Magic Square Calculator On the Web | Sources for More Information | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |