Reputation: 917
How to forward after catching exception to the same action which produced exception?
The line getServletContext().getRequestDispatcher("/local.action").forward(request, response);
has 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
}
}
...
Upvotes: 3
Views: 504
Reputation: 3893
This happens because in an HTTP connection the server can only return a response in answer to a browser's request. In this case, the browser is still sending its request, but the server stops accepting it when the exception is thrown. If you attempt to forward or return an error page at this point it does not work because the browser is not yet ready to receive the server's response (it is still in the middle of sending its request). The browser shows its "connection reset" error because from its perspective this is what happened: it was in the middle of sending its request and it was interrupted.
The maximum file size is meant as a safety check so you can abort files that are too large for your server to handle. For example, if a browser started sending a 100 GB file you would not want your application to spend the time reading it and storing it only to have to immediately delete it because it is too big to handle or have it consume all your disk space.
To give a better response to users you can set this limit to the maximum size that your server can reasonably handle. Then, check the file after it has been received and if it is larger than 3 MB delete it and return an error page.
Upvotes: 2