Hi, this is the Lightweight Front Controller concept in JSP form.
Requirements: Java Container with JSP & JSTL, jquery + jquery ui. A browser. Note that both the Google App Engine and Glassfish should be able to run this out-of-the-box.
What it does: It makes the creation of endpoints easy. You don't have to make a new file. You don't have to modify a configuration file. You can write the client to the endpoint right next to the endpoint definition. Because it's JSP, this means you can add and modify endpoints on-the-fly without a recompile, and without restarting the container.
How to use it: write your HTML as normal. Put the Endpoint class scriptlet at the top, and the Master endpoint at the bottom (see the example file). When you need an endpoint, create a new endpoint class like this:
<%
new Endpoint("happy") {
public void run(){
result = "happy times, the endpoint returned";
}
};
%>
By default the constructor will emit a button into the HTML page. You can turn this off by adding false to the constructor (e.g. "new Endpoint("happy", false)..."). Note the use of "result" to indicate a result. Yes, this is totally ghetto but there are no good interfaces that ship with Java that are like Runnable but return a String, and I wanted zero Java dependencies for the LFC.
The client-code to consume the response is up to you. If you use the emitted button, you can write a JavaScript function with the same name as the Endpoint, which will be executed when the response gets back to the client, like so:
<script>
function happy(response){
alert("Cool, got this from the server: "+response);
}
</script>
How it works: as you may know, a JSP is basically a Servlet with a lot of literal text. Everything that occurs occurs within the doGet method. When the page is entered with no parms, it acts like a normal JSP. When the page is entered with an "exec" parm, it functions like an Ajax endpoint. The line at the end throws away everything the JspWriter has accumulated, and then prints out the result of the named Endpoint. Some of the stuff at the top are just Java-language-lawyer contortions required by the fact that Endpoint is a local class - for example, you can't use statics and you can't refer to non-final local variables in local classes.
TODO: In truth, the example could be substantially cleaned up. Because JSTL is notoriously difficult to install, I should probably remove all of that. But JSTL is really nice for supporting nicely formatted XML and SQL strings. Feel free to remove this. All the jQuery stuff is also not necessary - it just makes things look nicer. I'll pull out the emission into an overridable method and remove the jquery dependencies.