【发布时间】:2021-12-15 19:52:12
【问题描述】:
在通过邮递员 PUT 请求 "/maths/answer" 对请求正文 MathsAnswer 进行更新后一分钟,我正在尝试自动将用户重定向到 URL "/timeUp"。所以我选择跟踪更新请求发出的时间。使用@Scheduled 注释的方法delay() 不断比较请求发出的时间和当前时间分钟,以决定是否发送重定向。但是,堆栈跟踪报告了响应已提交的错误。
控制器类:
@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
【问题讨论】:
标签: java spring-boot rest servlets cron