在写servelt实现文件下载的时候,提示如下错误
<span style="white-space:pre"> </span>Cannot forward after response has been committed
从错误的含义上来看是因为重复提交了已经提交的请求,于是回去看代码,发现了如下问题,
catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("errormessage", e.getMessage());
request.getRequestDispatcher("loadinfo.down").forward(request, response);//*****
}
request.getRequestDispatcher("loadinfo.down").forward(request, response);//*****
在一开始编写的时候,我以为在如果在catch里面进行请求的重定向了,就不会执行try-catch 块后面的语句了,其实不然。
解决方法有两种,一种是在catch里面加上return命令。
catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("errormessage", e.getMessage());
request.getRequestDispatcher("loadinfo.down").forward(request,
response);
return ;
}
request.getRequestDispatcher("loadinfo.down").forward(request,
response);
return;
另外一种是把请求重定向放到finally 里面