You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC(REST API)中Post请求接口带参数URL重定向失败的解决方案咨询

解决RestController中POST接口重定向失败的问题

这个问题的核心原因是你用了@RestController注解——它本质是@Controller + @ResponseBody的组合,默认会把所有方法的返回值序列化成JSON/XML,而不是处理视图跳转(包括RedirectView),所以你的重定向逻辑根本没被Spring当成视图来处理。下面给你两种可行的解决方案,完全兼容你的POST请求+服务层处理需求:

方案一:改用@Controller(推荐)

如果这个接口只需要完成重定向,不需要返回JSON数据,直接把@RestController换成@Controller即可。同时推荐用RedirectAttributes来传递参数,比手动拼接URL更安全(自动处理URL编码):

@Controller
@RequiredArgsConstructor
@Slf4j
public class RestControllerImpl {
    @Value("${uri-root}")
    private String uriRoot;
    private final Service service;

    @PostMapping("/api")
    public String performRequest(@RequestBody Transaction dto, RedirectAttributes redirectAttributes) {
        // 正常处理服务层逻辑
        service.perform(dto);
        
        String referenceToken = "sldflh@2lhf*shdjkla";
        // 用addAttribute自动将参数追加到重定向URL的查询参数中
        redirectAttributes.addAttribute("token", referenceToken);
        
        // 用redirect:前缀告诉Spring这是重定向请求,会自动处理视图跳转
        return "redirect:" + uriRoot;
    }
}

这种方式是Spring处理重定向的标准做法,redirect:前缀会让Spring自动创建RedirectView,RedirectAttributes的参数会被安全编码后拼到URL上,避免手动拼接时的编码问题。

方案二:保留@RestController,用ResponseEntity包裹RedirectView

如果这个接口需要兼顾返回JSON和重定向的场景,可以保留@RestController,但把返回类型改成ResponseEntity<RedirectView>,明确告诉Spring要返回重定向视图:

@RestController
@RequiredArgsConstructor
@Slf4j
public class RestControllerImpl {
    @Value("${uri-root}")
    private String uriRoot;
    private final Service service;

    @PostMapping("/api")
    public ResponseEntity<RedirectView> performRequest(@RequestBody Transaction dto) {
        service.perform(dto);
        
        String referenceToken = "sldflh@2lhf*shdjkla";
        String urlRedirect = uriRoot + "?token=" + referenceToken;
        RedirectView redirectView = new RedirectView(urlRedirect);
        
        return ResponseEntity.ok(redirectView);
    }
}

不过要注意,这种方式下你需要自己处理URL编码(比如你的referenceToken包含@、*这类特殊字符,手动拼接可能会导致URL解析错误),所以还是方案一更推荐。

额外说明

  • 不管用哪种方案,@PostMapping和@RequestBody都能正常接收POST请求的数据,服务层的处理逻辑完全不受影响。
  • 为什么之前看到的ModelAndView或RedirectAttributes在你的代码里不生效?因为@RestController的@ResponseBody会把这些对象直接序列化成JSON返回给前端,而不是作为视图跳转的依据。

内容的提问来源于stack exchange,提问作者skyho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:17:27