【问题标题】:Redirecting by setting the location in the header通过在标头中设置位置进行重定向
【发布时间】:2017-09-10 13:54:55
【问题描述】:

我在 REST API 中有一个方法,调用后应该设置转发地址

 UriComponents uriComponents = uriComponentsBuilder.path("/signIn").build();

然而,情况并非如此。这是我的方法

@RestController
@PreAuthorize("permitAll()")
@RequestMapping(value = "/register")
@Api(value = "Register API", description = "Provides a list of methods for registration")
public class RegisterRestController {

     @ApiOperation(value = "Activate the user with token")
     @RequestMapping(value = "/thanks", method = RequestMethod.GET)
     public
     ResponseEntity<?> confirmAccount(
        @RequestParam("token") String token,
        UriComponentsBuilder uriComponentsBuilder
     ) throws URISyntaxException {
          Optional<User> userOptional = userService.findByActivationToken(token);

          if(userOptional.isPresent()) {
             User user = userOptional.get();

             user.setActivationToken(null);
             user.setEnabled(true);

             userService.saveUser(user);
          } else {
             throw new ActivationTokenNotFoundException();
          }

          UriComponents uriComponents = uriComponentsBuilder.path("/signIn").build();

          return ResponseEntity.created(uriComponents.toUri()).build();
    }
}

调用页面地址https://zapodaj.net/fa61bfc5732f3.png.html后没有重定向 我所做的与 Stack Overflow enter link description here 上的这个主题完全相同。地址调用来自邮箱https://zapodaj.net/e0e5eb8ad52bf.png.html的链接。

【问题讨论】:

  • 是控制器还是休息控制器? .用 RequestMapping 试过了吗?
  • 是的。这是一个 RestController。更改为 RequestMapping 没有帮助。
  • 由于您分享的帖子发生了很多变化,最好知道您正在尝试什么以及这里失败了什么?您要转发到登录端点吗?请相应地更新问题
  • 我在编辑..

标签: spring rest spring-mvc spring-boot


【解决方案1】:

浏览器不会在 201 Created 响应时重定向。您应该使用永久重定向 (301 Moved Permanently)。

return ResponseEntity.status(301).location(uriComponents.toUri()).build();

201 响应代码对于 GET 方法也没有多大意义,它通常用作对 API 端点的 Ajax PUT 方法请求的响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2016-12-20
    • 1970-01-01
    • 2012-10-16
    • 2015-11-01
    相关资源
    最近更新 更多