Natraj
Natraj

Reputation: 417

Calling another sites jsp page and getting response from that page

I have a JSP page which has a form, which on submit calls a servlet which gets some more data from the database. After fetching all the required data I need to construct a URL with all the data and call a JSP page from another site which process the data and returns a string response. I have to then parse the response and show appropriate message on the UI.

I tried to call the JSP page from data access layer using HTTPUrlConnection but I am getting 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()); 
}

Then I got the URL to servlet and used request.getRequestDispatcher(url).include(request, response) and I am getting javax.servlet.ServletException: File "/http:/xxxx:8090/test/create.jsp" not found

The other site is running that I have confirmed. I do not have access to the other site so I cannot debug it.

Can any one explain what is wrong or what I am missing?

Upvotes: 0

Views: 3645

Answers (1)

BalusC
BalusC

Reputation: 1108722

The ServletRequest#getRequestDispatcher() doesn't take an URL such as http://example.com, but only a relative webcontent path, such as /WEB-INF/example.jsp.

Use HttpServletResponse#sendRedirect() instead:

response.sendRedirect(url);

This however shows the resource in its entirety. As you're using RequestDispatcher#include(), you seem to want to include its output (which makes however little sense in this context, but that aside). An alternative is to use <c:import> in your JSP. Thus, in your servlet:

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

and in /WEB-INF/your.jsp:

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

Upvotes: 2

Related Questions