Normally, when developing your GWT applications in hosted mode, the internal tomcat server will be used to serve up your application. However, if want to talk to a server-side php script running on your own local web server, you will soon run into issues with the , since hosted mode runs on one port and the php script is running on another. In this tutorial, I will show you how I got around by running my GWT application and the php script on the same local web server. To demonstrate this, I will use the GWT FileUpload widget with a php backend.
Getting started
This tutorial assumes you already have a local web server running that can handle php. I am personally using Apache via MAMP on OS X. XAMPP is also another easy to setup alternative for Windows.
To start, I created a project called FileUploader and imported it into my IDE (Eclipse). The code for the FileUploader module is directly taken from the example code in the FileUpload widget javadoc.
The only modification I made was to the setAction method of the FormPanel object.
()
final FormPanel form = new FormPanel();
form.setAction(GWT.getModuleBaseURL() + "upload.php");
Now when the user hits submit on the form, it will call the php script called upload.php
to handle the file upload.
Using -noserver
To tell hosted mode not to use the internal tomcat server, we will pass the -noserver
argument to the GWTShell. But first we have to perform the following steps:
First, notice that the url of my application is: http://localhost/com.gwtsite.FileUploader/Fileuploader.html
So I created a folder called com.gwtsite.FileUploader
in my web server’s web documents folder. Next, I compiled my application and copied the following files to this new folder:
- FileUploader.html
- gwt.js
- hosted.html
- history.html
- com.gwtsite.FileUploader.nocache.js
Then for the program arguments, i set the -noserver
parameter and since my web server is running on port 80 I also set the -port
parameter to 80.
Finishing up
The upload.php script for handling the upload was taken from the online php manual. I placed it in the same com.gwtsite.FileUploader
folder on my web server. All it does is move the uploaded file from the temp location to the specified directory. Notice that uploadFormElement
matches the name set on the GWT FileUpload widget.
()
$uploaddir = './';
$uploadfile = $uploaddir . basename($_FILES['uploadFormElement']['name']);
echo ''
;
if (move_uploaded_file($_FILES['uploadFormElement']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
...
?>
Once this is all wired up, I can now start up hosted mode from within my IDE and successfully upload files from within my GWT application.
References