Developing Tomcat servlets with Oxygene for Java

December 15, 2011 in Elements, Java, Platforms, RemObjects, Tools, Visual Studio

Since Java is strong not only on mobile devices but also on the server, we want to show how easy it is to get started with developing server-based applications with Oxygene for Java. For creating web sites as well as background infrastructure like web services, the Java servlets are the right thing to choose, and those need to be hosted within an application server. One of the most known open source Java application servers is Tomcat from the Apache Foundation. This article is about developing Tomcat servlets with Oxygene for Java.

This is an introduction, so we start from the very beginning. To be able to work with Tomcat, we need to install it. So grab your copy from the official Tomcat web site. In this walkthrough we use Windows to be able to develop and test directly on the same system, but of course the Oxygene for Java .jar files also run on any other platform that runs Java, and our servlet will run everywhere you have a Tomcat set up.

Note: You don’t need to use the official installer, as there are many projects out there that will also set you up with a complete Tomcat environment, like BitNami, but for this article we just go for the simple requirements and install Tomcat from the official installer.

We download the setup package and start it. As a first thing we change the installation type to full. This will install the Tomcat server and additionally the host manager (a web interface to manage the server) and examples, and will also start the Tomcat service when the computer starts to make things easy. On the next page we stick to the default ports but in the lower part we enter a user name and a password for a management user. I’ll go with ‘tomcat’ and ‘tomcat’ for both user name and password in my development environment.

This creates an administration user in all necessary roles to be able to manage our tomcat installation from a web browser. At the end of the installation process the installer will ask you to start the service, and we want to.

Launch a web browser and point it to http://localhost:8080/ (or, if you changed the port information in the installer, to the port you entered there). You should see a web page telling you which version of Tomcat is installed, like this:

For me (on a x64 system) the installer put Tomcat into the directory %ProgramFiles(x86)%\Apache Software Foundation\Tomcat 7.0\, but for Jim (who used BitNami to install his Tomcat) the location was %ProgramFiles%\Apache Software Foundation\Tomcat 7.0\. When you have a x86 system it will be the latter too, so don’t be confused when the path is slighlty different for you. Please locate the folder on your system because we need stuff from there. All following paths in this article will be given relative to this directory.

We are interested in two folders within the ‘Tomcat 7.0′ folder: The first is the /lib directory that should contain a file called ‘servlet-api.jar’. This is the library we need to reference later on when developing against Tomcat.

The second one is the ‘webapps’ folder, where we need to create a new folder hierarchy for our test. We create a directory that names our web application. For this sample we start with ‘Cooper’. In this folder we create a new one called ‘WEB-INF’ and in there a folder called ‘lib’.

So the directory where we want to deploy our test application to is \Tomcat 7.0\webapps\Cooper\WEB-INF\lib.

The following image will show you the locations:
This image shows the paths we need

Note: This is actually a bad thing to do on UAC protected or production systems, because you should avoid writing in the program files directory, but since we don’t want to focus on Tomcat configuration in this post here and concentrate on the actual development with Oxygene for Java, we can live with that for now.

We go back to our browser and start the ‘Manager App’ from the links on the right. We are asked to login with our administration account (tomcat/tomcat) and now we see a ‘Tomcat Web Application Manager’ that should show an application ‘/Cooper’ in the list of applications besides the root application ‘/’ and others like ‘/docs’ and ‘examples’. Just by the way, the latter is a good starting point to see what’s possible with servlets and how to do certain stuff. On the right side there are a few buttons, including one labeled ‘reload’. This is the one we need to hit after every build of our application to have Tomcat reload it.

No we start up the Visual Studio IDE. If your system is UAC protected make sure you fire it up with elevated privileges, because it will require write permissions for the Tomcat folder. Then we create a new project: The template we use is ‘Oxygene for Java’ -> ‘General’ -> ‘Class Library’ to start from scratch.

In the new solution we expand our project and then right-click on references, go ‘Add’ and select the file …\Tomcat 7.0\lib\servlet-api.jar to add this to the referenced libraries. Then we right-click on the project itself and select properties.

We change the Output path of both debug and release configuration to point to the location …\Tomcat 7.0\webapps\Cooper\WEB-INF\lib\ to be able to recompile, reload the app in the manager interface and test without the need to copy around the resulting .jar file to the Tomcat installation after every build.

Now we go to the generated Class1. We add these packages to the uses clause:

uses java.io,
     javax.servlet,
     javax.servlet.http,
     javax.servlet.annotation;

These are the Java namespaces we’re going to use in our first application. The namespace javax.servlet.http contains the base class for our servlet, javax.servlet contains the classes we’re using for reading the input (the request sent to Tomcat) and writing to the output (the response we’re building to send back to the client). In javax.servlet.annotations we will find the required annotations (the attributes we know from .NET and Delphi) to configure our servlet.

Then we change the name of the class to something better, like ‘MyFirstServlet’ and, while we’re at it, derive it from javax.servlet.http.HttpServlet. In the next step we need to tell Tomcat that this class will be our Servlet and where it should configure it. We can do this declaratively using an attribute (or annotation).

This is what we need to put on top of our class:

[WebServlet(name := "MyFirstServlet", urlPatterns := ["/"])]

With this we tell the servlet what its name is (MyFirstServlet) and that it should listen on the root URL of our web application (which we put in the folder Cooper, so the URL will be http://localhost:8080/Cooper/). And now it is time to tell our servlet what it should do, so let’s go in the real code.

For this we override a method on the base class called doGet. This method will be called from the Tomcat infrastructure whenever an HTTP GET request is received and matches a URL that should be handled from our servlet. For POST requests there is another method called doPost from which we can then access the POST data of the request, but we will stick to the doGet for now. The declaration of this public method and the implementation are quite easy for the very first test:

// declaration in our class:
method doGet(req: HttpServletRequest; resp: HttpServletResponse); override;
 
// implementation
method MyFirstServlet.doGet(req: HttpServletRequest; resp: HttpServletResponse);
begin
  resp.getWriter().println('Hello World');
end;

The method will be called from Tomcat whenever there is an HTTP GET request to handle, and it gives the request and a prepared response object to the method on which we do our work. In this case we simply take the response object, get the writer from it (to write directly to the stream that goes back to the browser) and print the string ‘Hello World’ to it. We compile that class library and check that a .jar file is written into our Tomcat Cooper/WEB-INF/lib folder.

We go to the management page, and in the line for our Cooper application we click on reload. No we are ready to test our application. We point a browser to http://localhost:8080/Cooper and should see ‘Hello World’.

Now, answering a request with static content like this is not hard, and we could have achieved this by simply delivering a normal .html file. Now it is time for us to do something with input, so we react on parameters that are passed to our servlet in the URL. For reference I will include the full source of this sample:

namespace TomcatServlet;
 
interface
 
uses
  java.io,
  javax.servlet,
  javax.servlet.http,
  javax.servlet.annotation;
 
type
 
  [WebServlet(name := "MyFirstServlet", urlPatterns := ["/"]]
  MyFirstServlet = public class (HttpServlet)
  public
    method doGet(req: HttpServletRequest; resp: HttpServletResponse); override;
  end;
 
implementation
 
method MyFirstServlet.doGet(req: HttpServletRequest; resp: HttpServletResponse);
begin
  var output: PrintWriter := resp.getWriter();
  var value := if req.ParameterMap.containsKey('test')
    then req.ParameterMap['test'][0]
    else 'No value';
 
  output.println("
<HTML>
  <BODY>
    <H1>Hello Java!</H1>
    <p>This is a Oxygene for Java Tomcat Servlet</p>
    <p>" + value + "</p>
  </BODY>
</HTML>");
end;
 
end.

This will display the value of the parameter ‘test’ when we call it with this URL http://localhost:8080/cooper/?test=hi, just like this:

I hope this article will give you a starting point for servlet development with Oxygene for Java.

Of course you can (and should) use any Java libraries and frameworks you like in addition to the servlet API, for example the Java Spring MVC framework or the Hibernate ORM tooling, that will make creation of web applications based on Tomcat (or JBoss as an alternative application server) easier and faster.

Comments are closed.