![](/img/trans.png)
[英]How to use spring redirect if controller method returns ResponseEntity
[英]How to redirect to external url if method return ResponseEntity<Object>
我在控制器中有返回ResponseEntity對象的方法
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Object> processInsert(HttpServletRequest request) {
return insertService.handleInsert(request);
}
public ResponseEntity<Object> handleInsert(HttpServletRequest request) {
Map<String, String[]> params = request.getParameterMap();
User user = createUser(params, request);
return new ResponseEntity<Object>(user, HttpStatus.OK);
}
現在,當執行此命令時,它會在瀏覽器中返回JSON,如果我需要保持此方法返回ResponseEntity對象,如何使其重定向到某些URL,例如www.google.com。
我認為我不完全理解您的問題,如果您希望返回一個ResponseEntity然后重定向到另一個頁面,則此信息將在重定向后丟失。 如果要將端點重定向到另一個頁面,則需要從控制器方法返回String類型,如下所示:
@RequestMapping(path = { "/testRedirect" }, method = { RequestMethod.GET})
public String testRedirect() {
return "redirect:http://www.google.com";
}
如果您想顯示錯誤或某些情況,以防由於輸入數據不正確或其他原因導致程序異常,則可以執行以下操作:
@RequestMapping(path = { "/testRedirect" }, method = { RequestMethod.GET})
public String testRedirect(HttpServletResponse servletResponse) {
// if error occurs
servletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"explained error");
return null; // return null to indicate your program that the request has finished with the error.
// if all works correctly return the redirect String.
return "redirect:http://www.google.com";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.