Steven Huwig
Steven Huwig

Reputation: 20774

How do you use the output of one servlet inside another servlet's init() method?

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.

Upvotes: 1

Views: 1067

Answers (3)

duffymo
duffymo

Reputation: 308743

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.

Upvotes: 0

David Z
David Z

Reputation: 131550

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.

Upvotes: 1

airportyh
airportyh

Reputation: 22668

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.

Upvotes: 2

Related Questions