Servlet中字节字符流的输出

public class OutServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//1字节流
ServletOutputStream out = response.getOutputStream();
out.print("Hello1");
//out.print("湖南城院");//不能以这种方式输出中文
out.write("湖南城市学院1".getBytes());


//2字符流
response.setContentType("text/html;charset=utf-8");//该句等价下面两句
//response.setContentType("text/html;");
//response.setCharacterEncoding("utf-8");//对字节流无效
PrintWriter out2 = response.getWriter();
out2.println("Hello2");
out2.println("湖南城市海陆空");


}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1字节流
ServletOutputStream out = response.getOutputStream();
out.print("Hello1");
//out.print("湖南城院");//不能以这种方式输出中文
out.write("湖南城市学院1".getBytes());


//2字符流
response.setContentType("text/html;charset=utf-8");//该句等价下面两句
//response.setContentType("text/html;");
//response.setCharacterEncoding("utf-8");//对字节流无效
PrintWriter out2 = response.getWriter();
out2.println("Hello2");
out2.println("湖南城市海陆空");

}

}

------------------------------------------------------------------------------------------------------------------

<a href="<%=request.getContextPath()%>/servlet/OutServlet">servlet中的两个输出流:字节流和字符流</a>
<form action="<%=request.getContextPath()%>/servlet/OutServlet" method="post">
姓名:<input type="text" name="name"/>
<input type="submit" value="提交">
</form>
<hr/>

--------------------------------------------------------------------------------------------------------------------------

1、servlet中的两个输出流:字节流(response.getOutputStream()) 和字符流(response.getWriter())
1)用字节流输出时,中文要采用out.write("中文".getBytes())。 对于字节流,用response.setCharacterEncoding("utf-8")设了也不行。
2)用字符流输出时,无论中英文都是:out2.print(); //编码用 response.setContentType("text/html;charset=utf-8");
3)※※※两种流不能共存(无论是GET或POST方式提交): 用了字节流就不能同时用字符,反之变然!

转载于:https://www.cnblogs.com/1314wamm/p/5951515.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值