views:

505

answers:

3

Here's what I'm trying to do:

public void init(ServletConfig config) {
    // ...
    URL url = new URL("http://myhost:port/path/to/otherservlet");
    // ... do stuff with contents of url
}

This works fine, but myhost and port are hardcoded and I want to avoid that. I want

URL url = new URL("/path/to/otherservlet");

but that's not valid. I've also tried

config.getServletContext().getResource("/path/to/otherservlet");

but that only works on static files.

How can I use the result of getting one servlet to initialize another? I don't want to use RequestDispatcher's forward() or include() methods -- the results of otherservlet are intended for use in the init() method, not to be sent in the response.

+2  A: 

If possible, I think the better approach is to refactor the code for the other servlet into a class somewhere that can be called directly for the output that you need.

toby
Let's say that's not possible.
Steven Huwig
+1  A: 

I wouldn't be surprised to find that it can't be done. I think toby's answer (split the code out into a common class) is the best approach, but if that's really not possible, try encoding the host and port to be used for local requests as context parameters in the server's web.xml file:

<context-param>
    <param-name>localhost</param-name>
    <param-value>localhost</param-value>
</context-param>
<context-param>
    <param-name>localport</param-name>
    <param-value>8080</param-value>
</context-param>

and get the values with context.getInitParameter("localhost") etc. You could also try to determine the values dynamically, but you might have to wait for a request to come in so you can use something like HttpUtils.getRequestURL(req) - I don't know any other way to do it.

David Zaslavsky
That's kind of the conclusion I was reaching as well, but I was hoping it wouldn't be so.
Steven Huwig
A: 

Maybe it'd work if you prepend that URL with the servlet context.

I agree that a refactoring sounds like a better idea. If it's an init operation, and both servlets are in the same context, perhaps the parameters can be externalized to a file or database in such a way that both can pick them up.

I wouldn't like an init to be too extensive.

duffymo