我有一个 Spring Boot 应用程序的注册端点。 UI 是一个 React 单页应用程序。
我想让 SPA 应用重定向到“/login”(发出 GET 请求)。
我应该怎么做?
我尝试了以下两种方法:
第一种方法不起作用,因为 postman 中的响应 http 代码是 200 并且正文仅包含“redirect:/login”
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signup(@RequestBody CustomUserDetails user, HttpServletResponse response) {
String userName = user.getUsername();
logger.debug("User signup attempt with username: " + userName);
try{
if(customUserDetailsService.exists(userName))
{
logger.debug("Duplicate username " + userName);
return "redirect:/login";
} else {
customUserDetailsService.save(user);
authenticateUserAndSetSession(user, response);
}
} catch(Exception ex) {
}
return "redirect:/login";
}
我还尝试了以下方法。但它会抛出 Method Not allowed
异常。因为当请求的类型为 POST
login
的 Controller
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public ModelAndView signup(@RequestBody CustomUserDetails user, ModelMap model, HttpServletResponse response) {
String userName = user.getUsername();
logger.debug("User signup attempt with username: " + userName);
try{
if(customUserDetailsService.exists(userName))
{
logger.debug("Duplicate username " + userName);
return new ModelAndView("redirect:/login", model);
} else {
customUserDetailsService.save(user);
authenticateUserAndSetSession(user, response);
}
} catch(Exception ex) {
}
return new ModelAndView("redirect:/redirectedUrl", model);
}
我应该如何处理这个重定向?最佳做法是什么?
最佳答案
最佳实践是您根本不应该在 Spring Boot Controller 中进行重定向。
您需要做的是从 /signup
端点返回状态代码。
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public ResponseEntity<String> signup(@RequestBody CustomUserDetails user, HttpServletResponse response) {
String userName = user.getUsername();
logger.debug("User signup attempt with username: " + userName);
try{
if(customUserDetailsService.exists(userName))
{
logger.debug("Duplicate username " + userName);
return new ResponseEntity<String>(HttpStatus.OK);
} else {
customUserDetailsService.save(user);
authenticateUserAndSetSession(user, response);
}
} catch(Exception ex) {
}
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
因此,当系统中存在具有该用户名的用户时,端点将返回 HTTP 状态 200;当系统中没有找到具有给定用户名的用户时,端点将返回 HTTP 状态 404。您必须使用此信息在前端单页应用程序中进行路由(这就是在 AngularJS 等中完成的方式)
关于java - 如何在 Spring Boot 中重定向单页应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929368/