调用另一个站点jsp页面并从该页面获得响应

时间:2012-09-04 12:49:20

标签: jsp servlets

我有一个JSP页面,它有一个表单,在提交时调用一个servlet,它从数据库中获取更多数据。获取所有必需的数据后,我需要构建一个包含所有数据的URL,并从另一个处理数据并返回字符串响应的站点调用JSP页面。然后我必须解析响应并在UI上显示相应的消息。

我尝试使用HTTPUrlConnection从数据访问层调用JSP页面,但我得到HTTP 505 error

try{ 
    URL url = new URL(mainURL+urlSB.toString()); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();
    InputStreamReader isr = new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")); 
    BufferedReader br = new BufferedReader(isr); 
    String htmlText = ""; 
    String nextLine = ""; 
    while ((nextLine = br.readLine()) != null){ 
        htmlText = htmlText + nextLine; 
    } 
    System.out.println(htmlText);
}catch(MalformedURLException murle){ 
    System.err.println("MalformedURLException: "+ murle.getMessage()); 
}catch(IOException ioe){ 
    System.err.println("IOException: "+ ioe.getMessage()); 
}

然后我获得了servlet的URL并使用了request.getRequestDispatcher(url).include(request, response),我得到了javax.servlet.ServletException: File "/http:/xxxx:8090/test/create.jsp" not found

另一个网站正在运行我已确认。我无权访问其他网站,因此无法对其进行调试。

任何人都可以解释错误或错过的内容吗?

1 个答案:

答案 0 :(得分:2)

ServletRequest#getRequestDispatcher()不会使用http://example.com之类的网址,而只会使用相对网络内容路径,例如/WEB-INF/example.jsp

改为使用HttpServletResponse#sendRedirect()

response.sendRedirect(url);

然而,这显示了整个资源。当你使用RequestDispatcher#include()时,你似乎想要包含它的输出(这在这个上下文中没什么意义,但除此之外)。另一种方法是在JSP中使用<c:import>。因此,在您的servlet中:

request.setAttribute("url", url);
request.getRequestDispatcher("/WEB-INF/your.jsp").forward(request, response);

/WEB-INF/your.jsp

<c:import url="${url}" />