如何使用Spring RestController返回FileSystemResource或json?

时间:2015-09-21 10:16:16

标签: java json spring api rest

我有一个下载zip文件的方法,目前我使用FileSystemResource来完成它。问题在于扩展控制器,如果文件确实是zip文件,我会查看,如果不是,则抛出异常。 此异常创建一个带有错误详细信息的Json对象并将其返回。 问题是Rest api的类型,因为现在我有:

@RequestMapping(value = "/zipDownload", produces="application/zip", method = RequestMethod.GET)
public FileSystemResource getZip(@RequestParam(value="filePath", required=true) String filePath ) throws FileExtensionException{
    return file.getZipFile(filePath);
}

和服务:

public FileSystemResource getZipFile(String fileName) throws FileExtensionException {
    String ext=FilenameUtils.getExtension(fileName);
    if (!ext.equals("zip"))
        throw new FileExtensionException(ext + " and not zip");
    return new FileSystemResource(new File(fileName));
}

例外

public class FileExtensionException extends Exception {

    private static final long serialVersionUID = 1L;

    public FileExtensionException(String message){
        super("The selected file has a different extension:" + message);
    }
}

和异常控制器

@ControllerAdvice 
public class ErrorController {

    /**
     * 
     * @param e: exception thrown
     * @return ErroreResponse
     */
     @ExceptionHandler(value = Exception.class)
    public @ResponseBody ErrorResponse errorHandler(Exception e){   
        //Make the exception by buildErrorResponse
        return ErrorResponseBuilder.buildErrorResponse(e);
    }
}

Spring发布的另一个异常覆盖我的问题:

  

2015-09-21 09:09:05.197 ERROR 7500 --- [nio-8080-exec-2] .m.m.a.ExceptionHandlerExceptionResolver:无法调用   @ExceptionHandler方法:public matlab.ErrorResponse   matlab.ErrorController.errorHandler(java.lang.Exception的)

     

org.springframework.web.HttpMediaTypeNotAcceptableException:无法   找到可接受的代表   org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:173)   在   org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)   在   org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:185)   在   org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)   在   org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)   在   org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:362)   在   org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:60)   在   org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:138)   在   org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74)   在   org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1183)   在   org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1020)   在   org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)   在   org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)   在   org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)   在   org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)   在javax.servlet.http.HttpServlet.service(HttpServlet.java:622)at   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)   在javax.servlet.http.HttpServlet.service(HttpServlet.java:729)at   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)   在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)   在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)   在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)   在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)   在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:116)   在   org.springframework.boot.context.web.ErrorPageFilter.access $ 000(ErrorPageFilter.java:60)   在   org.springframework.boot.context.web.ErrorPageFilter $ 1.doFilterInternal(ErrorPageFilter.java:91)   在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)   在   org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:109)   在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)   在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)   在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)   在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)   在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)   在   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)   在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)   在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)   在   org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)   在   org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:673)   在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1526)   在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1482)   在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)   在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:617)   在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)   在java.lang.Thread.run(Thread.java:745)

     

2015-09-21 09:09:05.201 ERROR 7500 --- [nio-8080-exec-2]   o.s.boot.context.web.ErrorPageFilter:转发到错误页面   请求[/ ManagmentFile / zipDownload]由于异常[已选中   文件有不同的扩展名:xlsx而不是zip]

     

matlab.FileExtensionException:所选文件有不同   扩展名:xlsx而不是拉链   matlab.FileServices.getZipFile(FileServices.java:46)at   matlab.ws.FileManagerImpl.getZip(FileManagerImpl.java:38)at   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)   在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)   在java.lang.reflect.Method.invoke(Method.java:497)at   org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)   在   org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)   在   org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)   在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)   在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)   在   org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)   在   org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)   在   org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)   在   org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)   在   org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)   在javax.servlet.http.HttpServlet.service(HttpServlet.java:622)at   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)   在javax.servlet.http.HttpServlet.service(HttpServlet.java:729)at   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)   在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)   在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)   在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)   在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)   在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:116)   在   org.springframework.boot.context.web.ErrorPageFilter.access $ 000(ErrorPageFilter.java:60)   在   org.springframework.boot.context.web.ErrorPageFilter $ 1.doFilterInternal(ErrorPageFilter.java:91)   在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)   在   org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:109)   在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)   在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)   在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)   在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)   在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)   在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)   在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)   在   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)   在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)   在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)   在   org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)   在   org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:673)   在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1526)   在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1482)   在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)   在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:617)   在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)   在java.lang.Thread.run(Thread.java:745)

如何以相同的方法返回Zip文件或json消息?问题是,产生=" application / zip",如果没有收到正确的错误json但它没有下载文件,否则反之亦然 感谢

1 个答案:

答案 0 :(得分:1)

修改

您可以保持控制器中的ConsoleKeyInfo不变,只需按照这种方式更改getZip

@ExceptionHandler

这里我只修改请求并重置@ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public @ResponseBody ErrorResponse errorHandler(Exception e, HttpServletRequest request) { request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.APPLICATION_JSON)); return ErrorResponseBuilder.buildErrorResponse(e); } 参数,以明确告诉Spring我想要使用哪种表示。