java.lang.IllegalStateException:在 or.apache.catalina.connector.ResponseFacade 提交响应后无法调用 sendRedirect()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24510284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:40:37  来源:igfitidea点击:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed at or.apache.catalina.connector.ResponseFacade

javajspservlets

提问by Shylendra Madda

When I am trying to redirect to another page I am getting this exception java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

当我尝试重定向到另一个页面时,我收到此异常 java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

I referred thisand thisbut no specific solution to my problem(code)

我提到了这个这个,但没有具体解决我的问题(代码)

I am unable to redirect to success.jsp at this line resp.sendRedirect("jsp/success.jsp");

我无法在这一行重定向到 success.jsp resp.sendRedirect("jsp/success.jsp");

This is my servlet code:

这是我的 servlet 代码:

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gk.gms.java.EntityManagerProvider;
import com.gk.gms.pojoclasses.Customer;
import com.gk.gms.pojoclasses.Manufacturer;
import com.gk.gms.pojoclasses.ServiceProvider;

public class RegistrationServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.doPost(req, resp);

        String firstName = req.getParameter("firstname");
        String lastName = req.getParameter("lastname");
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        String mailId = req.getParameter("mail");
        String userType = req.getParameter("usertype");

        EntityManager entityManager = EntityManagerProvider.getEntityManager();
        entityManager.getTransaction().begin();

        if (userType.equals("customer")) {
            Customer customer = new Customer();
            customer.setFirstname(firstName);
            customer.setLastname(lastName);
            customer.setUsername(userName);
            customer.setPassword(password);
            customer.setMail(mailId);
            entityManager.persist(customer);

        }
        if (userType.equals("service_provider")) {
            ServiceProvider serviceprovider = new ServiceProvider();
            serviceprovider.setFirstname(firstName);
            serviceprovider.setLastname(lastName);
            serviceprovider.setUsername(userName);
            serviceprovider.setPassword(password);
            serviceprovider.setMail(mailId);
            entityManager.persist(serviceprovider);
        }
        if (userType.equals("manufacturer")) {
            Manufacturer manufacturer = new Manufacturer();
            manufacturer.setFirstname(firstName);
            manufacturer.setLastname(lastName);
            manufacturer.setUsername(userName);
            manufacturer.setPassword(password);
            manufacturer.setMail(mailId);
            entityManager.persist(manufacturer);
        }

        entityManager.getTransaction().commit();
         resp.sendRedirect("jsp/success.jsp"); // problem with this line
    }
}

This is my jsp:

这是我的jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body BACKGROUND="../images/background.jpg">
    <HR COLOR=#BB055E>
    <font color="red" >
    ------------SUCCESSFULLY ADDED------------</marquee> 

    </font>
</body>
</html>

Logcat:

日志猫:

Jul 01, 2014 5:56:12 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jul 01, 2014 5:56:12 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Jul 01, 2014 5:56:12 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: true
Jul 01, 2014 5:56:12 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/gms]
Jul 01, 2014 5:56:12 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****, autocommit=true, release_mode=auto}
Jul 01, 2014 5:56:12 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jul 01, 2014 5:56:12 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
Jul 01, 2014 5:56:12 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: gms.complaint
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [complaintdescription, complaintid, customerid, manufacturerid, soluntiondescription, complainttype]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [manid, custid]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary, complaintid_unique, cusid, manid, custid]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: gms.customer
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [mail, username, lastname, firstname, password, cid]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary, cid_unique]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: gms.customer_info
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [id, serviceproviderid, customerid, productid, manufacturerid]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [serviceproviderfk, manufacturerfk, productfk, customerfk]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [serviceproviderfk, manufacturerfk, productfk, primary, customerfk, id_unique]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: gms.manufacturer
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [mail, username, lastname, firstname, mid, password]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary, mid_unique]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: gms.service_provider
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [mail, sid, username, lastname, firstname, password]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [sid_unique, primary]
Jul 01, 2014 5:56:12 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Jul 01, 2014 5:56:12 PM org.hibernate.ejb.internal.EntityManagerFactoryRegistry addEntityManagerFactory
WARN: HHH000436: Entity manager factory name (gadget) is already registered.  If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name'
Hibernate: 
    insert 
    into
        customer
        (firstname, lastname, mail, password, username) 
    values
        (?, ?, ?, ?, ?)
Jul 01, 2014 5:56:12 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [RegistrationServlet] in context with path [/gadgetmonitoringsystem] threw exception
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
    at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:483)
    at com.gk.gms.servlet.RegistrationServlet.doPost(RegistrationServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

Thanks in advance..

提前致谢..

采纳答案by Shylendra Madda

Simply I resolved it by removing this line super.doPost(req, resp);from my Servlet class.

我只是通过super.doPost(req, resp);从我的 Servlet 类中删除这一行来解决它。

May it helps to any one.

愿它对任何人都有帮助。

回答by Darshan Lila

From the stack trace it seems like you have set up a filter which might be redirecting to response. Check if there is some sort of response being sent from filter if you have set one.

从堆栈跟踪来看,您似乎已经设置了一个可能重定向到响应的过滤器。如果您设置了过滤器,请检查是否有某种类型的响应从过滤器发送。

回答by Nikhil Talreja

Try to switch the last 2 lines and add a return.

尝试切换最后两行并添加一个return.

resp.sendRedirect("jsp/success.jsp");
entityManager.getTransaction().commit();
return;
}

回答by Sanjeev

Culprit in your case is this line:

您的情况的罪魁祸首是这一行:

super.doPost(req, resp);

This is committing the response. Hence the exception.

这是提交响应。因此例外。