views:

52

answers:

3

Hi people,

i have a problem with implementation of "forwarded" request in java. So i have a servlet, and i want that for request localhost(servlet works on localhost) i receive a page(page defined intern in programm) and can proceed to work with this page using localhost. Example: page defined: stackoverflow.com So if i type in browser url: localhost, i receive content of stackoverflow but url must be localhost, if i than go to localhost/tags i receive content of stackoverflow/tags but url still should be localhost/tags. I hope for your help guys

+1  A: 

Sounds like you may have to implement some kind of tunneling http proxy in your servlet. Fortunately, it's not all that difficult to do and there may even be an open source options available out there.

This link may be useful to you: http://httpd.apache.org/docs/2.0/mod/mod_proxy.html

LoudNPossiblyRight
Exactly, this is more of a networking issue ("how do I make requests to localhost go to www.stackoverflow.com?") than a servlet question per se
matt b
A: 

This cannot be forwarded since it's on a different domain. A forward can only take place to a resource in the same webapplication context.

You need to include the external resource. The JSTL <c:import> may be of use here.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:import url="http://stackoverflow.com" />

That's basically all.

An alternative is the HTML <iframe> element, the difference is that it includes at client-side.

<iframe src="http://stackoverflow.com"&gt;&lt;/iframe&gt;

This only doesn't work flawlessly on certain sites such as Stackoverflow ;) The advantage is however that the parent URL remains the same all the time, regardless of whatever you do on the included site (except from opening links in a new tab/window).

BalusC
A: 

hmm you could use a httpclient to get the complete content of the site and then send this to the user agent using httpcomponents httpclient or the jersey-client package as in:

public void doGet(HttpServletRequest req,HttpServletResponse resp){
    HttpClient client=new HttpClient() // dont instantiate like this it's a heavyweight ;)
    GetMethod get=new GetMethod("http://stackoverflow.com/");
    int status=client.executeMethod(get);
    if (status=200){
        resp.getWriter().write(get.getResponseBodyAsString().getBytes("UTF-8"));
        resp.getWriter().flush();
    }else{
        // handle error
    }
    get.releaseConnection();

}
smeg4brains
what if you have to maintain a session?
LoudNPossiblyRight
youll have to add state to your program then, that saves the session internally and sets it using the httcomponents api when making a call to the third party site. as in get.setRequestHeader("Cookie","JSESSIONID=xxx");
smeg4brains
What kind of HttpClient is it? From apache?
Le_Coeur
example is apache httpclient 3.1: http://hc.apache.org/httpclient-3.x/
smeg4brains