简体   繁体   English

Spring Web MVC:如何在视图类而不是控制器中使用ResponseEntity?

[英]Spring Web MVC: How to use a ResponseEntity in the view class, not the controller?

Using Spring Web MVC, I would like to use a ResponseEntity to send bytes back to the client. 使用Spring Web MVC,我想使用ResponseEntity将字节发送回客户端。

For example, I could do this: 例如,我可以这样做:

@RequestMapping(value = "/getMyBytes", method = RequestMethod.GET)
public ResponseEntity< byte[] > handleGetMyBytesRequest()
{
    // Get bytes from somewhere...
    byte[] byteData = ....

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType( MediaType.IMAGE_PNG );
    responseHeaders.setContentLength( byteData.length );

    return new ResponseEntity< byte[] >( byteData, 
        responseHeaders, HttpStatus.OK );
}

But now the controller itself decides, how the data will be presented to the client. 但是现在,控制器本身决定如何将数据呈现给客户端。 Shouldn't that not be the job of the view? 这不是视图的职责吗?

So my question is, when I have this view class: 所以我的问题是,当我有这个视图类时:

public class DemoView extends AbstractView
{
    @Override
    protected void renderMergedOutputModel( Map< String, Object > model, 
            HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        bytes[] byteData = model.get( "byteData" );

        // ???
    }
}

How must the view code look like, when I want to use a ResponseEntity there? 当我想在其中使用ResponseEntity时,视图代码应如何显示?

Or does it make no sense to use ResponseEntity in the view class, and if yes, why? 还是在视图类中使用ResponseEntity毫无意义,如果是,为什么?

Thanks a lot for your help! 非常感谢你的帮助!

In your AbstractView you can simply use the HttpServletResponse object to set the HTTP response status and write the byte[] array to the output stream: 在您的AbstractView您可以简单地使用HttpServletResponse对象设置HTTP响应状态,并将byte[]数组写入输出流:

response.setStatus(status);
response.getOutputStream().write(byteData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM