gpt4 book ai didi

java - 如何在 Spring Boot 中重定向单页应用程序?

转载 作者:行者123 更新时间:2023-12-02 13:11:48 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com