include header from another server

I want to include .jsp or .shtml page that is a header on one website in another website's index.jsp page. So, if I change the header it would be changed on the other website's index.jsp page as well.

I believe I can't use the jsp's include because the resource I want to use is on another server. I haven't seen any sample codes that made sense to me for this and most importantly I am not a jsp/java programmer (yet).

Can someone post a sample code of how this would be done.

Thx

Mark

[523 byte] By [mraka] at [2007-10-2 14:26:08]
# 1

I won't provide code, because you aren't paying me, but I will point you in the correct direction.

You will have to make a new HTTP request to the other website, read it's content, and copy it to your response.

To do this you would use a java.net.HttpURLConnection object. See the API for that here: http://java.sun.com/j2se/1.5.0/docs/api/java/net/HttpURLConnection.html.

The HttpURLConnection is a subclass of the java.net.URLConnection, so looking at that class will help you understand how to use HttpURLconnection: http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLConnection.html

You will also find it easiest to get the HttpURLConnection from a java.net.URL object. See http://java.sun.com/j2se/1.5.0/docs/api/java/net/URL.html.

So once we have an open connection to the external website, we will use the HttpURLConnection object's Input Stream (stream of data that we can read from the external site) and copy its data to the JSP's output stream.

Since the JSP output is actually a PrintWriter, we could best wrap the Input Stream as a BufferedReader so we can read/write line by line. This requires a, java.io.InputStreamReader and a java.io.BufferedReader: http://java.sun.com/j2se/1.5.0/docs/api/java/io/InputStreamReader.html and http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html

Basically, the steps would probably be

1) Create a new URL to the external website

2) url.openConnection()

3) connection.connect()

4) connection.getInputStream()

5) new InputStreamReader (inputStream)

6) new BufferedReader (inputStreamReader)

7) Read from the bufferedReader and write to the JSP out object until input is empty

String line = null;

while ( (line = bufferedReader.readLine())!=null) {

out.println(line);

}

8) connection.disconnect() so you don't grab too many resources.

stevejlukea at 2007-7-13 12:46:00 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
Thank you on your detailed answer.
mraka at 2007-7-13 12:46:00 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...