Creating REST Web Service with webMathematica

After @Hans comment, get much more clear how to do it in webMathematica. It could't be simpler.

IMO, the best way to see how it works, after install webMathematica, is going into: tomcatDirectory\webapps\webMathematica\Examples\AJAX. Let's see for example the ReturnDate.jsp file:

<msp:evaluate>
If[ $$fullDate === "true",
    DateString[],
    DateString@{"Hour", ":","Minute",":","Second"}
]
</msp:evaluate>

Now if you call the address:

http:\\localhost:8080\webMathematica\Examples\AJAX\ReturnDate.jsp?fullDate=true

we get:

enter image description here

So, our service is created.

See how simple is to set the variables using $$ syntax, as we see in $$fullDate


If you have a look at the "webMathematica/Examples/PlotScript/PlotScript.jsp" example :

    <%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>
<html>
<head>
<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>
<form action="Plot" method="post">
<input type="text" name="fun"   size="24" value="<msp:evaluate>MSPValue[ $$fun,  "Sin[x]^2"]</msp:evaluate>"/> <br/> 
<input type="text" name="x1"   size="24" value="<msp:evaluate>MSPValue[ $$x1,  "10"]</msp:evaluate>"/>
<button type="submit" onClick="plot(this.form)"/>
</form>

</body>
</html>

The link generated is http://localhost:8080/webMathematica/Examples/PlotScript/PlotScript.jsp?fun=Sin[x]^2&x1=10

This is something similar to REST API. The link passes the values of "fun" and "x1" to PlotScript1.jsp. If you look at the code of PlotScript1.jsp then its nothing but plotting based on the POSTed values.

    <%@ 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>

Offcourse now you could use the same pattern and create a more complicated code in PlotScript1.jsp.

I use nodejs extensively to write REST API's and I can do the same within WebMathematica JSP page. Someone explained using mathematica function to connect and query MongoDB (Check here). I could just use the variables defined within my JSP to query the database, pass the obtained relevant JSON objects to a mathematica code (maybe another JSP) that generates some result (Like plot etc) and lastly use MSPShow[] to render the result.

The tricker part is the web based authentication just by using mathematica (Not the HTTP Basic or digest auth methods but form based). Would appreciate any good design patterns.