Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback, please email oracle-forums_moderators_us@oracle.com

RequestDispatcher.forward does not work

Bhautesh VedMay 14 2023

I am trying to create a J2EE application to upload files into the system. My entry page is an UploadFile.html page which allows the user to select the file. The request is forwarded to a UploadServlet Servlet. @MultipartConfig is configured in the web.xml file. The doPost method in the Servlet attempts to upload the file. If the file is uploaded successfully, then one of the attributes of the “request” object is set to “Success”. If not due to reasons such as the file exceeding the size limit, then it is set to “Failure”. The request is then forwarded to ResultPage.jsp where the value of this attribute is displayed.

I am attaching the code for the doPost method.

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		File file;
		
		String contentType=request.getContentType();
		String outputDir=getServletConfig().getInitParameter("file-upload");
		String result="Failure";
		
		if(contentType.indexOf("multipart/form-data")>=0)
		{			
			try
			{
				
				Collection<Part> parts=request.getParts();
				Iterator<Part> iterator=parts.iterator();
				result="Success";
				
				for(Part part:parts)
				{
					part.write(outputDir+part.getSubmittedFileName());
					System.out.println("File uploaded successfully.");
				}
						
			}
				
				catch(Exception ex)
				{
					result="Failure";
					ex.printStackTrace();
				}	
		}

		else
		{
			result="Failure";
			System.out.println("Error");
		}
		
		System.out.println("Debug 1");
		request.setAttribute("Result", result);
		System.out.println("Debug 2");
		RequestDispatcher rd = request.getRequestDispatcher("/ResultPage.jsp");
		System.out.println("Debug 3");
		try
		{
			rd.forward(request, response);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			
		}
	}

My code works successfully when uploading small files. Execution is forwarded to “ResultPage.jsp” where “Success” is displayed. However, when an exception is thrown due to the file size being too large, the rd.forward(request,response) code does not seem to work. I get a “Page cannot be displayed. Internet Connection was lost.” error on Microsoft Edge. I tried adding debugging statements. Debug 1, Debug 2 and Debug 3 prints out correctly. No exception trace is displayed for my final catch block.

Comments
Post Details
Added on May 14 2023
1 comment
257 views