44

While doing some operations in my application I got

java.lang.IllegalStateException Cannot call sendError()

When I reload the page again it work some time properly, but after some time again it shows the same exception. How can I overcome this exception?

Below is the exception:

HTTP Status 500 - Cannot call sendError() after the response has been committed
type Exception report
message Cannot call sendError() after the response has been committed
description The server encountered an internal error that prevented it from fulfilling this request.
exception 
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:451)
org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:725)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.40 logs.

Struts.xml

<struts>
    <package name="default" extends="hibernate-default">
        <action name="addUser" method="add" class="com.demo.action.UserAction">
            <result name="input">/register.jsp</result>
            <result name="success" type="redirect">list</result>
        </action>
        <action name="list" method="list" class="com.demo.action.UserAction">
            <interceptor-ref name="basicStackHibernate" />
            <result name="success">/list.jsp</result>
        </action>
    </package>
</struts>
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 1
    Are you by any chance redirecting the user before some additional logic in your sevlet? `response.sendRedirect(SOMEWHERE);` – StoopidDonut Dec 28 '13 at 10:37
  • @PopoFibo I am doing web application in struts2 and I configured redirect attribute because My response will print the user list . Thanking you very much –  Dec 28 '13 at 10:43
  • Could you update your question with the piece of code which includes your redirect statement? – StoopidDonut Dec 28 '13 at 10:55
  • 1
    @PopoFibo sure update now see the updated code. –  Dec 28 '13 at 11:31
  • You should check the Tomcat logs and post full stacktrace with the root cause. – Roman C Dec 29 '13 at 14:55
  • i meet this problem when configuring spring boot with security. In my AuthenticationEventHandler, i was using the method "super." whereas i was sending a response after using it.. – mik3fly-4steri5k Apr 22 '18 at 13:31
  • @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") @JsonIdentityReference(alwaysAsId=true) – Dipen Chawla May 25 '18 at 11:52

15 Answers15

58

I was creating a @ManyToOne and @OneToMany relationship. I added @JsonIgnore above the @ManyToOne and it solved the error.

Asad
  • 930
  • 7
  • 10
35

This error is a symptom of some other problem, not the root cause you're looking for.

This error explains why the user can't be redirected to the error page. (Reason: the server has already flushed part of the response buffer back to the client - it's too late to switch/redirect to the error page.)

As the error message points out, check elsewhere in your Apache Tomcat 7 logs (or debug your app another way) to find what is throwing an exception.

Barett
  • 5,826
  • 6
  • 51
  • 55
  • 1
    About debugging in "another way", it's hard to debug the moment when response is commited because lack of org.apache.coyote.Response class during development, however there's available org.apache.catalina.connector.OutputBuffer where you can put breakpoint in flush() method. – Lukasz Frankowski Jan 04 '18 at 15:39
  • 1
    Appending @LukaszFrankowski 's comment here. To debug and find the actual root cause, follow these steps: 1) Check the top of the full stack trace and find `ResponseFacade.sendError`. If you see this, proceed to the 2nd step. 2) From the top, jump to the first line that doesn't end with `.sendError(...)`, as in, skip anything like `HttpServletResponseWrapper.sendError`, `OnCommittedResponseWrapper.sendError` and so forth. 3) Look up that class you stopped at. This is usually where the actual root cause is located, as it tries to invoke the `HttpServletResponse.sendError` method there. – tom_mai78101 May 19 '21 at 18:29
17

I solved this error by adding @jsonIgnore to all getters for a List of another object

Med Elgarnaoui
  • 1,612
  • 1
  • 18
  • 35
6

For others in my situation--What was happening was that I had two @Entity objects with a many to many relationship causing infinite json to be generated, causing spring security to throw this error. Try adding @JsonIgnore above your hibernate relationships.

FlexEast
  • 317
  • 2
  • 13
5

Note: there are 2 @JsonIgnore dependencies you can import. Make sure it's from Jackson library; that made the difference for me:

import com.fasterxml.jackson.annotation.JsonIgnore;
Druckles
  • 3,161
  • 2
  • 41
  • 65
MonirRouissi
  • 549
  • 8
  • 7
  • Life saver after spending a whole weekend figuring out the problem. Boom! hence the answer. Thanks a lot. – Kasasira Mar 15 '21 at 07:28
5

use @JsonIgnore above @ManyToOne

  • I don't see anything related to JSON or Any ORM mapping in the question. This error can occur due to multiple reasons. Mostly when you try to send something to the client when response has already been sent and committed from the server. – Nitin Zadage Nov 12 '20 at 11:52
3

You can try this Annotation it will help as it fixed my issue.

It will definitely help if it will not be able to help you, then try to modify this as per your requirement.

@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
   @JsonIdentityReference(alwaysAsId=true)
Dipen Chawla
  • 331
  • 2
  • 10
  • 2
    Its worked for me! Thanks if we want ignore all other properties except id then only add @JsonIdentityReference(alwaysAsId=true) otherwise remove @JsonIdentityReference(alwaysAsId=true) – Prabhakaran Ramaswamy Feb 25 '20 at 05:53
2

This is what caused it in my case.

I have 2 filters that both have the capability to send an error through the HttpServletResponse.sendError() method. If Filter A discovered something wrong and called sendError on the HttpServletResponse object, then a second call in the same filter or in filter B will cause the cannot call senderror exception. This is because sendError does not cause the request itself to be aborted. The code in the filter continues to be executed after the sendError method had been called.

Maurice
  • 6,698
  • 9
  • 47
  • 104
2

There are so many answers to use @JsonIgnore annotation. But I will not recommend it. If your parent class has a many-to-one relationship with a single entity then it is fine. But if your parent class has multiple many-to-one relationships then definitely it gives a headache to you.

I will suggest going with a uni-directional approach and implement a separate dto class based on your requirement.

Nafaz M N M
  • 1,558
  • 2
  • 27
  • 41
1

This is a common error and there can be various root cause can be identified. In my case I were opening pdf file from the web service and for this I were performing write operation in file using buffer. So kindly change below:

        File outfile = File.createTempFile("temp", ".pdf");

        OutputStream os=new FileOutputStream(outfile);
        byte[] buffer = new byte[1024];

        int length;
        /*copying the contents from input stream to
         * output stream using read and write methods
         */
        while ((length = is.read(buffer)) > 0){
            os.write(buffer, 0, length);
        }

to

        File outfile = File.createTempFile("temp", ".pdf");
        IOUtils.copy(is, new FileOutputStream(outfile));

and after this I were performing below operation:

    javax.ws.rs.core.Response.ResponseBuilder responseBuilder = javax.ws.rs.core.Response
                .ok(outfile, MediaType.APPLICATION_OCTET_STREAM);
                responseBuilder.header("content-type","application/pdf");

             return responseBuilder.build();

and error get resolved. Cheers!

Aman Goel
  • 3,351
  • 1
  • 21
  • 17
1

@JsonIgnore on the @ManyToOne mapping will resolve it.

stephen
  • 31
  • 1
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30053306) – Flair Oct 12 '21 at 05:30
1

Adding @JsonIgnore solved the current error. However, it cause error when creating entry of entity with @ManyToOne annotation.

Using @JsonBackReference(value = "**") (where ** is the property of the entity with @OneToMany annotation) can also solve this error while not causing other errors!

(in my case, Im using User object with @ManyToOne annotation, but Im using the id of User as a column in sql table)

Xi Cao
  • 11
  • 2
0

if u use annotations like:@WebFilter,@WebServlet...,just add metadata-complete="true" into web.xml e.g

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xmlns:web="http://java.sun.com/xml/ns/javaee" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
         id="WebApp_ID" metadata-complete="true" version="3.0">

Hope this is your need!

Derry
  • 39
  • 3
0

I was using Jersey and I returned the following response

Response.status(HttpStatus.SC_MOVED_TEMPORARILY).header("Location", "https://example.com?param1=foo bar").build()

After URL encoding, the issue was solved

Response.status(HttpStatus.SC_MOVED_TEMPORARILY).header("Location", "https://example.com?param1=foo%20bar").build()
Gaurav Sharma
  • 745
  • 7
  • 23
-2

I have overcome the exception,you may check your table structure.I execute the sql query produced by hibernate in mysql. As excepted,an exception was thrown.

[Err] 1054 - Unknown column 'this_.ID' in 'field list'

I found that a field ID is missing in the table.Add the ID into the table ,it's ok. Hope it's helpful.

young
  • 1