如何在控制器方法返回响应实体时使用弹簧重定向

2022-09-02 09:08:07

我想写这样的东西:

@RequestMapping(value = { "/member/uploadExternalImage",
            "/member/uploadExternalImage" }, method = RequestMethod.GET)
    public ResponseEntity<String> handleFileUpload(@RequestParam String url,@RequestParam String fileName, RedirectAttributes redirectAttributes) {
        ...
        return new ResponseEntity("Cannot save file " + fileName, HttpStatus.INTERNAL_SERVER_ERROR);
        ...
        return "redirect:/member/uploadImage";
    }

预期行为 - 重定向至控制器:

@RequestMapping(value = { "/member/createCompany/uploadImage",
            "/member/uploadImage" })
    @ResponseBody
    public ResponseEntity<String> handleFileUpload(@Validated MultipartFileWrapper file,
            BindingResult result, Principal principal

但我不能写它,因为它是字符串,但应该是"redirect:/member/uploadImage"ResponseEntity

如何解决我的问题?


答案 1

如果你没有明确需要返回 a,你可以重新声明你的方法,如下所示:ResponseEntity

public String handleFileUpload(@RequestParam String url,@RequestParam String fileName, RedirectAttributes redirectAttributes) {
    return "Cannot save file " + fileName;
    ...
    return "redirect:/member/uploadImage";
}

但是,如果您需要使用 ,那么似乎可以添加重定向到,如此处所述。ResponseEntityResponseEntity

HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/member/uploadImage");    
return new ResponseEntity<String>(headers,HttpStatus.FOUND);

答案 2

当您希望控制器的输出由Spring机械进行后处理时,弹簧控制器方法的返回值只是糖。如果我正确地理解了你在做什么,你只有2种可能性:

  • 发送带有代码 500 和消息的错误响应"Cannot save file " + fileName
  • 重定向到 同一应用程序上下文中。/member/uploadImage

由于Spring为重定向提供了比重定向更多的好东西,我的建议是让你的方法返回一个字符串:SendError

@RequestMapping(value = { "/member/uploadExternalImage",
            "/member/uploadExternalImage" }, method = RequestMethod.GET)
    public String handleFileUpload(@RequestParam String url, @RequestParam String fileName,
            RedirectAttributes redirectAttributes, HttpServletResponse resp) {
        ...
        //return new ResponseEntity("Cannot save file " + fileName, HttpStatus.INTERNAL_SERVER_ERROR);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            "Cannot save file " + fileName); // explicitely put error message in request
        return null;  // return null to inform Spring that response has already be processed
        ...
        return "redirect:/member/uploadImage";
    }