Does spring mvc have response.write to output to the browser directly?

心不动则不痛 提交于 2020-01-09 09:03:57

问题


I am using spring mvc with freetemplate.

In asp.net, you can write straight to the browser using Response.Write("hello, world");

Can you do this in spring mvc?


回答1:


You can either:

  • get the HttpServletResponse and print to its Writer or OutputStream (depending on whether you want to send textual or binary data)

    @RequestMapping(value = "/something")
    public void helloWorld(HttpServletResponse response)  {
      response.getWriter().println("Hello World")
    }
    
  • Use @ResponseBody:

    @RequestMapping(value = "/something")
    @ResponseBody
    public String helloWorld()  {
      return "Hello World";
    }
    

Thus your Hello World text will be written to the response stream.




回答2:


If you use an annotated controller (or non-annotated for that matter I believe...), you can use the method argument HttpServletResponse in your controller to get the output stream and then write to the screen - see http://download.oracle.com/docs/cd/E17410_01/javaee/6/api/javax/servlet/ServletResponse.html#getOutputStream%28%29

For more information about the parameters you can use in your controllers/handlers, see http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html (section 13.11.4)




回答3:


I'm sure it is possible in some contexts. For example, if you have the HttpServletResponse object available to you (as you do in a Controller, or if you write your own View), then you can call getWriter() or getOutputStream() and write to that.

But you need to be careful to make sure that what you are doing doesn't interfere with your use of FreeMarker templates. And I'm not sure if you could manage it from within a FreeMarker template.




回答4:


If you want to send something to OutputStream, even if you are using Freemaker, just use @ResponseBody

example:

    @RequestMapping(value = "report1", method = RequestMethod.GET, produces = "application/pdf")
    @ResponseBody
    public void getReport1(OutputStream out) {


来源:https://stackoverflow.com/questions/3146461/does-spring-mvc-have-response-write-to-output-to-the-browser-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!