Writing a Java Extension
This chapter describes the function of Java classes and Servlet APIs, describes how a Java Extension is used with a Servlet API, how to create TrafficScript functions using Java Extensions, and how to write (compile) and debug Java Extensions.
Java Classes and Servlet APIs
Java Extensions generate server responses, modify requests to backend servers, or alter responses from other servers.
To use the Servlet API, you must create a Java class that extends either the GenericServlet or one of its subclasses, such as the HttpServlet class.
Here’s an example of a simple HTTP Servlet:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
res.setContentType( "text/plain" );
PrintWriter out = res.getWriter();
out.println( "Hello World!" );
}
}
This is a standard Servlet that prints the phrase “Hello World!” whenever the Servlet is used.
The method doGet() is overridden from HttpServlet and is used whenever an HTTP GET request/response (depending if the Java Servlet is called in a TrafficScript response/request rule) is received. An identical function called doPost does the same for HTTP POST messages.
By default, the doGet/doPost methods display the error message “HTTP method POST/GET is not supported by this URL”. To avoid this error, override the doGet/doPost methods.