我想写这样的东西:
@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"
是String但应该是ResponseEntity
如何解决我的问题?
答案 0 :(得分:14)
如果您不明确需要返回ResponseEntity
,则可以重新声明您的方法,如:
public String handleFileUpload(@RequestParam String url,@RequestParam String fileName, RedirectAttributes redirectAttributes) {
return "Cannot save file " + fileName;
...
return "redirect:/member/uploadImage";
}
但是,如果您需要使用ResponseEntity
,那么您似乎可以按照here所述向ResponseEntity
添加重定向。
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/member/uploadImage");
return new ResponseEntity<String>(headers,HttpStatus.FOUND);
答案 1 :(得分:4)
当您希望控制器的输出由Spring机械进行后处理时,Spring控制器方法返回值只是糖。如果我正确理解你在做什么,你只有两种可能性:
viewController
"Cannot save file " + fileName
。由于Spring为重定向提供了比/member/uploadImage
更多的好东西,我的建议是让你的方法返回一个字符串:
SendError
答案 2 :(得分:2)
可以使用@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);
}
为了让Spring能够处理@ExceptionHandler
方法中的错误,您需要启用org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver
异常解析程序。但是,如果您尚未指定任何自定义异常解析程序,则默认情况下将启用它。