Home > Mobile >  HttpServletResponse's sendRedirect call could not execute
HttpServletResponse's sendRedirect call could not execute

Time:11-02

I am trying to automatically redirect a user to a url "/timeUp", a minute after an update was made on a request body MathsAnswer via a postman PUT request "/maths/answer". So I chose to track the time the update request was issued. The method delay() annotated with @Scheduled, constantly compares the time the request was made with the current time minutes to decide if to send a redirect. But, the stack trace reported with an error that response is already commited.

Controller class:

@RestController
        public class MathController {
            
            private MathService service;
            
            public boolean start = false;//checks if PUT request has been made
            
            private int time = 0;
            
               private HttpServletResponse myResponse;
               
               //constructors omitted
             @PutMapping("/maths/answer")
            public ResponseEntity<Object> addSolution(@RequestBody MathsAnswer from, 
                    HttpServletResponse res){
                
                this.myResponse = res;
                
                this.start = true; //PUT request has been made
                
                this.time =  LocalTime.now().getMinute();//request made at 
                
                return new ResponseEntity<Object>(service.addSolution(from), HttpStatus.OK);
            }

      @Scheduled(cron = "* * * * * ?")
    public void delay() throws Exception {
        
        int now = LocalTime.now().getMinute(); 
        
        if(start) {
            if(now - time >= 1 || time - now >= 1) {
                
                callTimeUp(new HttpServletResponseWrapper(myResponse));
            }
        }
        
    }
     public void callTimeUp(HttpServletResponse response) throws Exception{
        System.out.println("Inside calltimeup");
        response.sendRedirect("/timeUp");
    }
    
    
    @GetMapping("/timeup")
    public ResponseEntity<Object>timeUp(){
        return new ResponseEntity<Object>("Your time is up", HttpStatus.GATEWAY_TIMEOUT);
    }

stack trace:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

CodePudding user response:

The problem here is that your code tries to modify the response from the first call of /maths/answer, but you cannot do that. That response was already sent to the client.

From what I understand you want something like this:

  1. User calls /maths/answer - response code 200
  2. User calls /maths/answer - minute after the response was send - redirect to /timeup

In order to do that, you need to check the time in addSolution and then modify response accordingly... No need the cron job for it here

  • Related