有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java当metod返回ResponseEntry<Resource>抛出错误时,如何返回ModelandView?

我有以下方法

@GetMapping("/{fileName}")
public Object downloadFile(@PathVariable String fileName) {
    // Load file from database
    errors.clear();

    DBFile dbFile;

    try {
        dbFile = dBFileStorageService.getFileByName(fileName);

    } catch (MyFileNotFoundException ex) {
        logger.info("File has not been found.");
        errors.add(ex.getMessage());

        return new ModelAndView("redirect:/");
    }
    logger.info("Delivering file");
    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(dbFile.getFileType()))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
            .body(new ByteArrayResource(dbFile.getData()));

}

如果可以返回文件,我想返回ResponseEntity<Resource>,而不是返回Object,否则返回ModelAndView("redirect:/")

我试过:

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

但我没有重定向,而是收到一条消息,说我试图下载的文件已损坏。 总结一下,我想将方法签名更改为:

public ResponseEntiry<Resource> downloadFile(@PathVariable String fileName)  

共 (1) 个答案

  1. # 1 楼答案

    关于通过ResponseEntity返回文件的第一个问题,这里已经回答了: Return file from Spring @Controller having OutputStream

    同意wwith@chrylis,正如他所建议的,在发生异常时,最好的方法是抛出异常,并使用@ExceptionHandler方法注释在sprin @ControllerAdvice类中处理它

    @ControllerAdvice
    class GlobalControllerExceptionHandler {
        @ResponseStatus(HttpStatus.CONFLICT)  // 409 or according to your need any code
        @ExceptionHandler(Exception.class)
        protected ModelAndView unhandledExceptionHandler(Exception ex){
            System.out.println("handling exception here!!!");
            ModelAndView mv = new ModelAndView();
            mv.setViewName("errorView");
            mv.addObject("ERROR", "ERROR OCCURRED REDIRECTED "+ex.getMessage());
            return mv;
        }
    }
    

    官方Doc