Servlet response write vs print? Which is better?

一个人想着一个人 提交于 2020-01-11 13:36:31

问题


I am having a string which needs to be sent as response from a servlet & I am having two approaches to send response back from it.

First is using PrintWriter.

response.getWriter().print(responseString);

Second is using OutputStream.

 byte[] byteResponse = responseString.getBytes(Charset.forName("UTF-8"));
 response.getOutputStream().write(byteResponse);

I want to know which is better and efficient way of sending response?

Please suggest.


回答1:


Use an OutputStream for binary data, and a Writer for text.




回答2:


I am having a string specifies that you wish to write a string so i suggest the PrintWriter object

 //prints text data to screen (browser)
 PrintWriter printer = response.getWriter();
 printer.print(string);
 //print again if you wish
 printer.print("Welcome blahblah");
 //close afterwards if you don't mind.
 printer.close();

so if you wish to write text to browser, PrintWriter works just fine, fast and simple.



来源:https://stackoverflow.com/questions/26010650/servlet-response-write-vs-print-which-is-better

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