Search code examples
servletsjava-ee-6requestdispatcher

Servlet's RequestDispatcher.forward() method does not work


I have a Java Application which connects to a servlet using HttpURLConnection. The application embeds the parameters it wants to pass to the servlet in the url while connecting to it.Thus the servlet can access and process these parameters using its doGet(). I am through with this part (I can access the parameters and dispay them in the servlet).

Next what I want to do is pass these parameters from the servlet to a JSP. I'm using request.setAttribute() to do it. But even after RequestDispatcherObj.forward(request, response), the JSP doesn't open. I've even tried response.sendRedirect(url).

However if I run the servlet independently, both the above methods(forward() and sendRedirect()) work fine and the JSP page opens.

I wonder what am I doing wrong.

Thanks in advance for your help.

CODE:

Java App

serverAddress = new URL("http://localhost:8080/WebApp/ServletPath"+"?message1"+"="+message);
(HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset);
connection.setReadTimeout(10000);
connection.connect();

Servlet

message = request.getParameter("message1");//working
request.setAttribute("message1", message);//to be read in the jsp
url="/index.jsp";
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);//Works when servlet is run independently but not when the servlet is called from the App

}


Solution

  • HttpURLConnection is not used to change what the browser connects to and displays. It's used to create a HTTP connection in the Java application itself.

    When a Java program connects to a URL and reads the response, the browser doesn't know about it, and won't magically display anything. By connecting to a URL in your Java app, you do the same thing as what the browser does, but in your own program. So you might read the response from the connection, and display what the webapp has sent.