home client api server api protocol f.a.q. downloads

Programming a PHP/Java Bridge servlet

This guide shows how to create a servlet and how to call it from PHP code.

Create a servlet using the Eclipse IDE

  • Start Eclipse Java EE IDE for Web Developers
  • Click on File/New/Dynamic Web Project
  • Enter Project name: "MyWebApp", Target runtime: "Apache Tomcat v6.0", Configuration: "Default configuration for Apache Tomcat"
  • Click on Finish
  • Open the tree: Project Explorer/MyWebApp/WebContent/WEB-INF so that the lib directory becomes visible
  • Drag and drop JavaBridge.jar and php-servlet.jar to the lib directory.
  • Click on File/New/Servlet
  • Enter Java package: "test", Class name: "Hello"
  • Click Next, Click Next
  • Uncheck "doPost", check "doGet" and "doPut"
  • Click on Finish
  • Add the following code to the doGet method body:
    response.getWriter().write("HelloServlet is running!");
  • Add the following code to the doPut method body (press Control-Shift-o to automatically resolve references):
    RemoteHttpServletContextFactory ctx = new RemoteHttpServletContextFactory(this,
      getServletContext(), request, request, response);

    response.setHeader("X_JAVABRIDGE_CONTEXT", ctx.getId());
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

    try {
      ctx.handleRequests(request.getInputStream(), response.getOutputStream());
    } finally {
  • Add the following method to the servlet:
    public String hello() {return "hello from MyServlet";}
  • Click on the Run button. In the dialog box click on the Finish button. You should see the browser "http://localhost:8080/MyWebApp/Hello" with the message "HelloServlet is running!".

Connect PHP with your servlet

  • Drag and drop Java.inc to a directory and create the following PHP script "test.php":
      define("JAVA_HOSTS", "localhost:8080");
      define("JAVA_SERVLET", "/MyWebApp/Hello");

      echo java_context()->getServlet()->hello();
  • Run the PHP script. For example with the command:
    php -n test.php
    It will invoke the hello() method and display its result.

Please see the Java API documentation for more information.