在网页中显示PDF

时间:2013-10-28 00:09:21

标签: spring pdf spring-mvc

我正在使用Spring MVC,我想从我的本地到网页显示PDF文件。我不知道我应该怎么做我的控制器来做这件事。我看到一个类似的问题,答案是在此question中返回ResponseEntity<byte[]>,但如果我没有弄错的话,这个问题适用于ajax,这不是我的要求。

更新

这是我到目前为止所尝试的:

<a href="#" onClick="test();" >test</a>

function test(){
      $.ajax({
    type: "POST",
    url: "../admin/module/id.do",
    data: '{ file_id }',
    success: function(response){
           alert(response);
             }
      });
}

控制器:

@RequestMapping( value = "/admin/module/id", method = RequestMethod.POST )
    public ResponseEntity<byte[]> getPDF( @PathVariable( "id" )
    int id, Model model )
    {
        System.out.println( "test" );
        Path path = Paths.get( "C:/Users/FORSAK~1/AppData/Local/Temp/spring_tutorial.pdf" );
        byte[] contents = null;
        try
        {
            contents = Files.readAllBytes( path );
        }
        catch( IOException e )
        {

            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType( MediaType.parseMediaType( "application/pdf" ) );
        String filename = "spring_tutorial.pdf";
        headers.setContentDispositionFormData( filename, filename );
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>( contents, headers, HttpStatus.OK );
        return response;
    }

alert(response)不起作用,System.out.println( "test" );

也不起作用

来自萤火虫的错误是"NetworkError: 500 Internal Server Error - http://localhost:8080/ThesisProject/admin/module/id.do"

堆栈跟踪:

java.lang.IllegalStateException: Could not find @PathVariable [id] in @RequestMapping
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.resolvePathVariable(AnnotationMethodHandlerAdapter.java:857)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolvePathVariable(HandlerMethodInvoker.java:710)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:360)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:444)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:432)
    ....

1 个答案:

答案 0 :(得分:0)

首先,异常非常简单

java.lang.IllegalStateException: Could not find @PathVariable [id] in @RequestMapping

你有

@RequestMapping( value = "/admin/module/id", method = RequestMethod.POST )

不声明路径变量,只声明特定路径。 id作为请求参数传递

data: '{ file_id }',

这是错误的,我认为它应该是

data: { id: file_id },

使用@RequestParam(value = "id")注释您的参数。