How to forward after exception?

How do I forward after an exception is thrown from the same activity that caused the exception? The line has getServletContext().getRequestDispatcher("/local.action").forward(request, response);

no effect.

@WebServlet("/FileUploadServlet1")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
        maxFileSize = 1024 * 1024 * 3 ) // 3 MB
public class FileUploadServlet1 extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            ...
            try {
                for (Part part : request.getParts()) {
                    fileName = getFileName(part);               
                    part.write(uploadFilePath + File.separator + fileName);
                }
            } catch (IllegalStateException e) {
                throw new Exception("Image was not uploaded");
            }
            ...
        } catch (Exception ex) {
            request.setAttribute("message", ex.getMessage());
            System.out.println("forward");          
            getServletContext().getRequestDispatcher("/local.action").forward(request, response); // this has no effect

        }
    }
...

      

+3


source to share


1 answer


This is because on an HTTP connection, the server can only return a response in response to a browser request. In this case, the browser still sends its request, but the server stops accepting it when an exception is thrown. If you try to forward or return an error page at this point, it won't work because the browser isn't ready to accept the server's response yet (it's still in the middle of sending its request). The browser displays a "connection reset" error message because from their point of view this is what happened: it was in the middle of sending its request and was interrupted.

The maximum file size is meant as a security check, so you can abort files that are too large for your server. For example, if the browser starts sending a 100GB file, you don't want your application to waste time reading it and save it only to immediately remove it because it is too large to handle or consume all of your disk space.



To give a better answer to your users, you can set this limit to the maximum size that your server can reasonably handle. Then check the file after you receive it and if it is larger than 3MB, delete it and return an error page.

+2


source







All Articles