need help calling a remote server with JSP
I'm writing an 开发者_StackOverflow中文版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?
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>
精彩评论