在 Spring MVC 上制作下载控制器的最佳方法是什么?
我有一个使用 Spring Framework 3 构建的系统,现在我必须实现文件下载。 为了执行“下载操作”,我通常获取 HttpServletReponse 对象,设置标头并从中获取用户输出流。
它运作良好,但我想知道是否有更简单/更智能的方法来做到这一点?
非常感谢!
I have a system built with Spring Framework 3 and now I must implement a file download.
To execute the "donwload action" I usually get the HttpServletReponse object, set the headers and get the user outputstream from it.
It works well, but I'd like to know if there's an easier/smarter way to do it?
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
@ResponseBody
并返回byte[]
You can use
@ResponseBody
and return abyte[]
您可以使用 @ResponseBody 或从控制器方法返回 HttpEntity。请参阅http://static.springsource。 org/spring/docs/3.0.x/reference/mvc.html#mvc-ann-responsebody 了解详细信息。
You could use the @ResponseBody or return an HttpEntity from your controller method. See http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-ann-responsebody for details.
使用 spring mvc,您可以将
OutputStream
和HttpEntity
作为参数传递,但将HttpServletResponse
传递给控制器方法是一个非常好的方法。With spring mvc you can pass
OutputStream
andHttpEntity
as parameters, but passing theHttpServletResponse
to a controller method is a perfectly fine approach.还有其他方法,但它们是从架构师/设计师的角度或健全的软件工程原理的角度来看,这可能会或可能不会更容易/更聪明。如果你问设计师,他可能会说控制器不应该知道数据(模型)的下载。有些人甚至可能建议不要在控制器中使用 HttpServletReponse,有些人建议扩展 AbstractView(或选择它的合适子类),以便可以重用它或刷新响应正文中的流以将视图与控制器分开。
也许还有其他方法,但我的建议是保持简单并实施团队中的任何工作——尽管我建议与设计师/建筑师(如果有的话)核实以避免任何返工,因为他们可能有不同的观点。
There are other ways but they are from an architect/designer's point of view or sound software engineering principles point of view, which may or may not be easier/smarter. If you ask a designer, he might say that the controller should not be aware of the download of data (model). Some might even recommend not to use HttpServletReponse in controller and some would recommend to extend AbstractView (or choose a suitable subclass of it) so that it can be reused or flush stream in response body to separate view from controller.
There maybe other ways but my recommendation is to keep it simple and implement whatever works in the team — though I would recommend checking with designer/architect (if you have) to avoid any rework because they may have different perspective.