servlet上的Tomcat错误500:“响应后无法转发”

时间:2013-02-19 14:33:26

标签: java servlets runtime-error

当我尝试验证请求参数时,Tomcat向我显示错误500.

堆栈跟踪:

HTTP Status 500 - Cannot forward after response has been 
type Exception 
message Cannot forward after response has been 
description The server encountered an internal error that prevented it from 
fulfilling this request. exception

java.lang.IllegalStateException: Cannot forward after response has been committed

这是我的servlet片段(没有PrintWriter.flash或类似的东西)。

此代码位于servlet的开头。为什么我在“已经提交”的响应中得到IllegalArgumentException

String login = req.getParameter("login");
String password = req.getParameter("password");

if (login.length() == 0 || password.length() == 0) {
    req.setAttribute("wrong", "Your login or password is empty");

    RequestDispatcher rd = req.getRequestDispatcher("jsp/index.jsp");
    rd.forward(req, resp);
}

1 个答案:

答案 0 :(得分:1)

在发送页面后添加return。这将解决您的异常。

    RequestDispatcher rd = req.getRequestDispatcher("jsp/index.jsp");
    rd.forward(req, resp);
    return;

<强>原因:

当您“forward”或“include”时,相同的requestresponse会传递给该资源。如果关闭输出流,JSP将无法使用它来返回数据。只要将任何数据写入client,响应就已经committed