java - 除了 "dev"之外,Spring redirectAttributes 无法在其他配置文件中工作

标签 java spring spring-boot spring-mvc web

我有一个 Controller ,应该在处理后重定向到另一个端点,但它仅在我将 Activity 配置文件设置为 dev 时才起作用。当配置文件不是 dev 时, Controller 将返回登录页面,而不是重定向到配置文件端点。

这是我的 Controller

public String completeSignUp(
          @RequestParam final String token, @RequestParam final String userId,
          Model model, RedirectAttributes redirectAttributes, HttpServletRequest httpServletRequest) {
    LOG.debug("About to complete the sign-up process with token: {} and userId {}", token, userId);
    try {
      InputValidationUtility.validateInputs(getClass(), token, userId, model);
      UserDto userDto = updateUserAndSendConfirmationEmail(token, userId, model, httpServletRequest);
      if (Objects.isNull(userDto) || model.containsAttribute(SignUpControllerConstant.SIGN_UP_ERROR)) {
        model.addAttribute(UserConstant.USER_MODEL_KEY, new UserRequestModel());
        return SignUpControllerConstant.SIGN_UP_VIEW_NAME;
      }
      // automatically authenticate the userDto since there will be a redirection to profile page
      UserUtility.authenticateUser(userService, userDto.getUsername());
      model.addAttribute(SignUpControllerConstant.SIGN_UP_SUCCESS_KEY, true);
      model.addAttribute(USER_REQUEST_MODEL_KEY_NAME, new UserRequestModel());
      redirectAttributes.addFlashAttribute(ProfileControllerConstant.NEW_PROFILE, true);
      LOG.debug("Redirecting to profile page...");
      return "redirect:/profile";
    } catch (Exception e) {
      LOG.error(SignUpControllerConstant.ERROR_CREATING_USER, e);
      model.addAttribute(SignUpControllerConstant.ERROR, SignUpControllerConstant.ERROR_CREATING_USER);
      return SignUpControllerConstant.SIGN_UP_VIEW_NAME;
    }
  }

配置文件页面需要身份验证并具有端点 /profile

此代码适用于“dev”配置文件

最佳答案

我声明了一个 bean 将 cookie 设置为严格,这有时会干扰重定向。

@Bean
  WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
    return tomcatServletWebServerFactory -> tomcatServletWebServerFactory.addContextCustomizers(context -> {
      Rfc6265CookieProcessor processor = new Rfc6265CookieProcessor();
      processor.setSameSiteCookies("strict");
      context.setCookieProcessor(processor);
    });
  }

删除后重定向就起作用了。

关于java - 除了 "dev"之外,Spring redirectAttributes 无法在其他配置文件中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60358017/

相关文章:

Java 全局异常处理程序

spring - 在 Spring 中使特定方法成为非事务性的

java - 无法访问 camunda 驾驶舱页面

java - 无法获得 JDBC 连接

java - 在 mysql java 中循环 - 搜索模板

java - JPA查询优化

java - 字符串:如何用单个字符替换多个可能的字符?

java - 使用@DirtiesContext BEFORE_CLASS 进行 Spring 启动测试

java - 无法在 JPA 查询中进行投影

Spring 启动 : path to application. 属性