我試圖在 通過郵遞員 PUT 請求"/timeUp"對請求正文MathsAnswer進行更新一分鐘后自動將用戶重定向到一個 url "/maths/answer"。所以我選擇跟蹤發出更新請求的時間。delay()用@Scheduled,注釋的方法不斷將發出請求的時間與當前時間分鐘進行比較,以決定是否發送重定向。但是,堆疊跟蹤報告了一個錯誤,即回應已經提交。
控制器類:
@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
uj5u.com熱心網友回復:
這里的問題是您的代碼試圖修改第一次呼叫 的回應/maths/answer,但您不能這樣做。該回應已經發送給客戶端。
據我了解,您想要這樣的東西:
- 用戶呼叫
/maths/answer- 回應代碼 200 - 用戶呼叫
/maths/answer- 發送回應后一分鐘 - 重定向到/timeup
為了做到這一點,你需要檢查時間addSolution,然后相應地修改回應......這里不需要cron作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344071.html
