...

View Full Version : How can I include content from a URL, not from a local file?



kathryn
09-21-2004, 09:58 AM
Hi,
I am trying to include content in my jsp file from an external url (probably another servlet/jsp containing html and javascript).
I have been using the include tag with no success ...
any ideas????

Thanks, K

Roy Sinclair
09-21-2004, 04:24 PM
The include is strictly a local use only kind of tag. If you want to use remote content then you should be looking at the <object> tag instead.

jbot
09-28-2004, 11:01 AM
If you want to use remote content then you should be looking at the <object> tag instead.

which is also strictly an HTML issue, not a JSP or JSTL one.

webcomplete
10-26-2004, 12:18 AM
GOOD! a JSP programmer! Too many people dont do JSP. But the answer to your question is simple... You use java.net.URL object which has a OpenStream() method that returns an InputStream which you can use like a text file reading a line at a time and outputting to your own page.

<%@page import="java.io.*" %>
<%@page import="java.net.*" %>

<%
URL l_URL = new URL("http://www.google.com");
BufferedReader l_Reader = new BufferedReader( new InputStreamReader( l_URL.openStream()));

String l_InputLine = null ;
while ((l_InputLine = l_Reader.readLine()) != null)
out.println( l_InputLine );

l_Reader.close();
%>


This code is very useful for 'borrowing' content from another site in server-side processing so that you get the content of the other site but not show any links to it. Furthermore, you can parse the content and pull only what you want. And if you have a firewall at work that restricts you from viewing certain sites or you want to view, you can use this to get the content of that site provided this code is ran from a trusted server that is allowed by your firewall.

Once you have the above code working, you can bring it to the next level and maybe have a form that takes a url as input and get the content. Save the code below as: geturlcontent.jsp

<%@page import="java.io.*" %>
<%@page import="java.net.*" %>

<%
String a_Url = request.getParameter( "url" ) ;
String l_Content = "" ;

if( a_Url!=null && a_Url.length()>0 )
l_Content = GetContent( a_Url ).toString() ;
%>
<%!
StringBuffer GetContent( String a_Url ) throws Exception
{
URL l_URL = new URL(a_Url);
BufferedReader l_Reader = new BufferedReader( new InputStreamReader( l_URL.openStream()));

StringBuffer l_Result = new StringBuffer("") ;
String l_InputLine = null ;
while ((l_InputLine = l_Reader.readLine()) != null)
l_Result.append( l_InputLine );

l_Reader.close();
return( l_Result ) ;
}
%>
<form method="get" action="geturlcontent.jsp">
URL : <input type=text" name="url" value="http://www.google.com"><br>
<input type="submit">
</form>
<hr>
<%=l_Content%>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum