我正在使用彈簧靴構建一個鏈接縮短器。除了將用戶重定向到他們的網址外,一切正常。我已經檢查了有關 stackoverflow 的其他示例,但似乎沒有任何東西對我有用。
請在下面查看我的代碼
public class DosuController {
private final DosuService dosuService;
public DosuController(DosuService dosuService) {
this.dosuService = dosuService;
}
@GetMapping("/{dosu}")
public ResponseEntity<Void> redirect(@PathVariable("dosu") String dosu) {
return dosuService.redirect(dosu);
}
}
//SERVICE
public class DosuService {
private final DosuRepo dosuRepo;
public DosuService(DosuRepo dosuRepo) {
this.dosuRepo = dosuRepo;
}
public ResponseEntity<Void> redirect(String dosu) {
Dosu dosus = dosuRepo.findByDosu(dosu);
if (dosus == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Dosu not found with name: "dosu);
}
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create(dosus.getRedirectUrl())
.build();
}
}
輸出:本地主機:8080/www.google.com
欲望輸出: www.google.com
uj5u.com熱心網友回復:
您可以URI按照以下代碼片段中的描述在位置標頭中設定 。確保您應該添加正確的URI SCHEME(如 uri 中提到的 https)。前任:
public ResponseEntity<Void> redirect() {
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create("https://www.google.com"));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
}
更新服務類方法
public ResponseEntity<Void> redirect(String dosu){
Dosu dosus = dosuRepo.findByDosu(dosu);
if(dosus == null){
throw new ResponseStatusException (HttpStatus.NOT_FOUND,"Dosu not found with name: "dosu);
}
HttpHeaders headers = new HttpHeaders();
// Make sure uri should be valid uri with proper scheme name
headers.setLocation(URI.create(dosus.getRedirectUrl()));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
}
uj5u.com熱心網友回復:
你應該先檢查你的dosus.getRedirectUrl()。這是您期望的實際網址嗎?
然后,重構您的代碼,并嘗試redirect:url從您的控制器回傳一個。
控制器:
@GetMapping("/{dosu}")
public String redirect(@PathVariable("dosu") String dosu) {
Dosu dosus = dosuService.findByDosu(dosu);
if (dosus == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Dosu not found with name: " dosu);
}
return "redirect:" dosus.getRedirectUrl();
}
服務:
public Dosu findByDosu(String dosu) {
return dosuRepo.findByDosu(dosu);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/463676.html
上一篇:同時觸發多個請求
下一篇:java.lang.NoSuchMethodError:org.mockito.Answers.get()Lorg/mockito/stubbing/Answer;
