Skip to content

Calling one servlet from another

So, I’m building a RESTful web service for a client, which is going to accept a large (60 mbish) file and a set of parameters that are attributes of the file, using the multipart/form-data enctype. The idea is to have this service be available for external programs to post to, but to also provide a nice web interface. I built another servlet which generates the usable user interface (the UI servlet), and am now having trouble pushing the data over to the RESTful servlet. After the RESTful service is called, the UI servlet needs to ensure that any errors are understandable to the user.

It looks like there are a couple of options:

1. Use RequestDispatcher to hand the request entirely over to the service. This is easy, but it means that the service now needs to return a human readable response, or you need to insert a filter to provide one.

1a. Have the RESTful service take a parameter which indicates whether its caller is another program or a human being, and use the RequestDispatcher from the UI servlet.

1b. Have no UI servlet at all, but just have the RESTful servlet be able to generate a nice user interface (or redirect to a pleasant looking JSP) via a given parameter.

2. Use the URL and HttpURLConnection objects to have the UI servlet post to the RESTful servlet just as you’d post to any other remote resource on the internet with java. This seems to work ok (I think), but requires (I also think) an absolute URL and also requires a bit of I/O to push the stream of bytes from the UI servlet to the RESTful servlet.

I can’t think of any other ways to solve this problem, and the only other solution that searching turned up is a no-no in modern servlet engines.