Purpose: Most applications use communication to provide function to the user. This may be communicating with a database, a messaging API, or a multitude of other things. It has almost become necessary. To make a truly compelling JavaFX application, chances are you will need some sort of communication layer. This tutorial provides you with that communication by showing you how to connect to a simple servlet and use the data it returns.
End Result:
NOTE: If this says ‘Error connecting to Servlet…that just means I forgot to start up my servlet server.
Servlets have become an extraordinarily popular way to transmit between a client and a server. While they have lost some popularity in the recent years (due to webservices and REST), they are still quite popular, powerful, and perhaps most importantly – simple. JavaFX needs a way to communicate with these. As it turns out, there is a very powerful API built into JavaFX to allow you to do just this.
Before we get into the JavaFX side of things, I should first describe the Servlet that we are going to be working with in this example. It is perhaps as bare bones as you can get. The servlet itself is the following:
public class JavaFXServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public JavaFXServlet()
{
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
try
{
bw.write("Message from Servlet!");
}
finally
{
bw.close();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
}
}
Feel free to download the WAR file (the deploy-able package).
As you can see, this servlet simply writes “Message from Servlet!” to anyone invoking it. This is really about as simple of a servlet as we can get. I deployed this on my web server using Winstone (a bare bones servlet container). If you see the message “Error connecting to servlet!”, that probably means that I restarted my webserver and forgot to start up Winstone again…
JavaFX needs a way to communicate with this servlet. Well, it is pretty easy thanks to the HttpRequest object. This is a very powerful object that lets you connect to a URL and get its content. By combining this with our Servlet, we can get some pretty neat dynamic content.
Using the HttpRequest object is as simple as:
var servletString : String = "Error connecting to servlet!";
def request = HttpRequest {
location: "http://piliq.com/JavaFXServlet";
onInput: function(is: java.io.InputStream) {
var buf : StringBuffer = new StringBuffer();
var reader : BufferedReader = new BufferedReader(new InputStreamReader(is));
var data : String = null;
while ((data = reader.readLine()) != null)
{
buf.append(data);
buf.append("\n");
}
reader.close();
servletString = buf.toString();
}
}
request.enqueue();
We have a variable called servletString, whose purpose is supposed to be the result of the servlet. The HttpRequest object really only requires that the location be set (and probably the onInput). The location needs to be set so that the object knows where to connect to. The onInput is a function that provides an InputStream of the data being returned by that URL. This doesn’t need to be set, but I can’t think of too many situations where you would not want to know the data being returned.
You can see that this ‘onInput’ function is fairly basic. We read in the data from the InputStream into a StringBuffer…and once the InputStream is done, we pass the contents of that buffer into the servletString. Lastly, once we have our HttpRequest defined, we call the ‘enqueue’ method on the object. This tells the object to perform a ‘get’ operation on the location specified (the type of operation can be configured by the attributes if needed).
At this point, the object will connect to our servlet – the servlet will return the string – the onInput method will parse that string out – then the servletString variable has the data.
Notice though, that the servletString is set to be an ‘error’ when it is first invoked. Well, that is because there could be several types of errors with this type of communication. For instance, what if the Servlet was not running? Then that is an error condition. Look at the HttpRequest object though…it can be set up to handle the errors. I choose, for simplicity sake, to ignore them.
Getting the data visible is also easy:
Stage {
title: "Application title"
width: 300
height: 80
scene: Scene {
content: Text {
font: Font {
size: 24
}
x: 10,
y: 30
content: bind servletString;
}
}
}
Communicating with servlets has never been so easy. This is really a good way for your applets to communicate too. For one, it doesn’t require any signing of the jar! That is huge! I hope that this tutorial provides you with a general understanding of how to use the HttpRequest object in JavaFX – it really is powerful. And if nothing else, at least it got you to look at Winstone.
[...] in Java are Servlets. If you want to learn how to integrate Java FX and Servlets, take a look here. It turns out its quite easy – those JavaFX guys really nailed it when they designed these [...]
[...] Connecting to Servlets [...]
Great tutorial! I just wish you included your imports with you FX scripts
Thanks!!! If you download the source, the imports are included there.
How can i pass the var value to servlet ?
like html form to servlet , servlet can get it by “request.getParameter(“xx”);
Lots of ways – unfortunately, none of them are really that great. I prefer to have my servlet invoker switch to a ‘POST’ request (rather than the standard ‘GET’) and push information to the servlet that way. It is a cheap and easy way to send information there…however, I don’t think a lot of people like doing that.
Another way to get parameters off the servlet (by calling request.getParameter(“xx”);) is by putting the parameter in the URL. So something like http://testweb.com/Servlet?parm1=value1;parm2=value2
That URL would connect to the Servlet at path http://testweb.com/Servlet. There would be two parameters attached to the call (parm1 and parm2). Calling request.getParameter(“parm1″) would return “value1″.
The downfall of this is when you want to send lots of information to the servlet (say more than a couple hundred characters). It gets to be really complex. Another idea you could play around with is cookies…
Hope that helps!
A question about using the a Post request. I just started to look at JavaFX and needed just the thing this tutorial showed, so thanks for that.
Is there a way to use the setAttribute-method (as you use in a Servlet) in the JavaFX class? Do you have any links or examples. I would appriciate it!
I would assume that the easiest way to set parameters would be in the servlet url. You could do something like http://server/servlet?parm1=value;parm2=nextValue
That would then come into your servlet as parameters. I don’t see in the JavaFX api though (at least initially) an easy way to do this. Course..you could always just call Java code to do it too
@Drew
Ok, thanks for the answer. I saw in your earlier post that you could send params in the url. I was hoping that there were an other way. But now I know.
Thanks again for a good tutorial!