Java 如果控制器方法返回 ResponseEntity,如何使用 spring 重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32184175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:07:45  来源:igfitidea点击:

How to use spring redirect if controller method returns ResponseEntity

javaspringspring-mvcredirect

提问by gstackoverflow

I want to write something like this:

我想写这样的东西:

@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";
    }

expected behaviour - redirect to the controller:

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

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

But I cannot write it because "redirect:/member/uploadImage"is String but should be ResponseEntity

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

How can I resolve my problem?

我该如何解决我的问题?

采纳答案by Serge Ballesta

Spring controller method return values are just sugar when you want the output from the controller to be post processed by Spring machinery. If I have correctly understood what you are doing, you have only 2 possibilities:

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

  • send an error response with code 500 and message "Cannot save file " + fileName
  • redirect to /member/uploadImagein the same application context.
  • 发送带有代码 500 和消息的错误响应 "Cannot save file " + fileName
  • 重定向到/member/uploadImage相同的应用程序上下文。

As Spring provides more goodies for redirect than for SendError, my advice would be to have you method return a string:

由于 Spring 为重定向提供了比 for 更多的好处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";
    }

回答by Jordi Castilla

If you don't explicity need to return a ResponseEntityyou can redeclare your method like:

如果您不明确需要返回 aResponseEntity您可以重新声明您的方法,如:

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

But if you need to use ResponseEntity, then it seems you can add a redirect to ResponseEntityas described here.

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

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

回答by JTP

This could be done using the @ExceptionHandlerannotation.

这可以使用@ExceptionHandler注释来完成。

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

@ExceptionHandler(FileUploadException.class)
ResponseEntity<String> handleFileUploadError(final FileUploadException e) {
  return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}

In order for Spring to handle the error in your @ExceptionHandlermethod, it's required that you have the org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolverexception resolver enabled. However, if you haven't specified any custom exception resolvers it will be enabled by default.

为了让 Spring 处理您@ExceptionHandler方法中的错误,您需要org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver启用异常解析器。但是,如果您没有指定任何自定义异常解析器,它将默认启用。