这两天我一直在尝试找出问题所在。我在这里读到我应该在代码中添加一个返回,我做到了,但我仍然得到 p>
java.lang.IllegalStateException: Cannot call sendRedirect()
after the response has been committed, Error.
我该如何解决这个问题?
每次我连接到数据库时都会发生。这是连接方法:
<%!
public void connect()
{
try {
Class.forName("com.mysql.jdbc.Driver");
String dbURL = "jdbc:mysql://localhost:3306/moti";
String user = "root";
String password = "j3o4h5n6y7";
con = DriverManager.getConnection(dbURL, user, password);
statement = con.createStatement();
}
catch(Exception ex) {
throw new Error(ex);
}
}
%>
就像在这个代码块中:
String post = request.getParameter("send");
if(post != null )
{
connect();
statement.execute(add);
con.close();
response.sendRedirect("fourm.jsp");
return;
}
但在这段代码中,它的工作非常完美:
String back = request.getParameter("retrun");
if(back != null)
{
response.sendRedirect("fourm.jsp");
return;
}
最佳答案
从高层次来看,您的具体问题是因为您错误地使用了 JSP 文件而不是 Servlet。类作为前端 Controller 。
从低级别来看,您的具体问题是由于 JSP 在生成 HTML 代码并将其发送到 HTTP 响应期间作为一种 View 技术发挥作用而引起的。响应缓冲区大小默认为 2KB。一旦代码到达该行,JSP 中的每个 HTML 和其他模板文本都会立即写入响应。因此,当第一次达到响应缓冲区大小限制时,所有 HTTP 响应 header 和到目前为止编写的 HTML 代码将被发送到客户端(网络浏览器)。换句话说,响应已提交。这是一条不归路。根本不可能从客户端取回已发送的字节。
重定向基本上是在 HTTP 响应上设置一个 Location
header 。为了能够正确设置它,响应显然必须尚未提交。如果它们都已被客户端发送和检索,则根本不可能设置新的响应 header 。
从底层来看,您可以通过将所有前端 Controller 和业务逻辑移动到 JSP 文件的最顶端来解决您的具体问题,以便在发送第一个 HTML 代码之前很久就执行它。通过这种方式,您可以消除在前端 Controller 和业务逻辑完成之前提交响应的风险。
<%@page pageEncoding="UTF-8" %>
<%
// Write business code here.
%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Some</title>
</head>
<body>
... (no controller/business logic here! just pure presentation)
</body>
</html>
但是,这是一个bad practice .而是将所有前端 Controller 和业务逻辑移动到 Servlet 中.那么你的方法是从高层次上看是正确的。 Java 代码不属于 JSP 文件,而是属于 Java 类。
关于java.lang.IllegalStateException : Cannot call sendRedirect() after the response has been committed 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12693975/