tags:

views:

22

answers:

1

I'm writing an application in JSP that needs to reach out to a remote cgi which will feed it some data.

Is there a JSP specific way to do this that is less brute force than simply using the httpConnection library and reading a bitstream?

+1  A: 

You can use JSTL <c:import> tag to import response data from external resources in your JSP page.

<c:import url="http://example.com/some.cgi" />

But if this returns a complete HTML page of which you just need a certain part, then you really need to do a bit more work. Best way would be to create a Servlet class which preprocesses this data before forwarding the request to the JSP page. You can use java.net.URL to get an InputStream from it which you feed to a HTML parser to get the necessary information out of it. Here's a basic example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    InputStream input = new URL("http://example.com/some.cgi").openStream();
    String relevantData = parseHtml(input); // Do your thing here. Maybe with help of jTidy?
    request.setAttribute("data", data);
    request.getRequestDispatcher("page.jsp").forward(request, response);
}

and then in JSP just access the data by EL:

<p>Relevant data: ${data}</p>

Edit: as per the comments, you need the <c:import> in combination with the var attribute. You can then use fn:split() afterwards to split the obtained key:value string.

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

<c:import url="http://example.com/some.cgi" var="result" />
<c:set value="${fn:split(result, ':')}" var="parts" />
key: ${parts[0]}<br>
value: ${parts[1]}<br>
BalusC
the <c:import> looks like it would do the trick. The cgi is, in fact, returning a key:val string. So, the only caveat would be that I would need to be able to load this result into a String that I can then work with... is that doable or is it only willing to print the result to the page?
Dr.Dredel
If you click the `c:import` link in my answer, you'll find the tlddoc which states that you can store this in a string `var`.
BalusC