HttpServletResponse 的 sendRedirect 调用无法执行

HttpServletResponse's sendRedirect call could not execute

我正在尝试自动将用户重定向到 url "/timeUp",在通过邮递员 PUT 请求 [=14] 对请求正文 MathsAnswer 进行更新后一分钟=].所以我选择跟踪更新请求发出的时间。用@Scheduled注解的方法delay(),不断地比较请求发出的时间和当前时间分钟数来决定是否发送重定向。但是,堆栈跟踪报告了响应已提交的错误。

控制器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);
    }

堆栈跟踪:

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

这里的问题是您的代码试图修改 /maths/answer 的第一次调用的响应,但您不能这样做。该响应已发送给客户端。

据我了解,您想要这样的东西:

  1. 用户调用 /maths/answer - 响应代码 200
  2. 用户调用 /maths/answer - 响应发送后一分钟 - 重定向到 /timeup

为此,您需要检查 addSolution 中的时间,然后相应地修改响应...这里不需要 cron 作业