response向客户机回送数据

本文介绍了如何使用HttpServletResponse向客户端发送字符数据和字节数据,包括getWriter()和getOutputStream()两种方法,并给出了示例代码。需要注意的是这两种方法不能同时使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HttpServletResponse提供了两个方法,用于向客户端回送数据。

getWrite():用于向客户机回送字符数据;

getOutputStream():既可以回送字符数据,也可以回送字节数据(二进制数据);

要特别注意一点:这两个流不能同时调用,否则会运行期报错,如下:

java.lang.IllegalStateException: getOutputStream() has already been called for this response

代码如下:

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

		response.setContentType("text/html");
						
		//不能同时使用
/*		response.setHeader("Content-Disposition", "attachment; filename=1.jpg");
		String path=this.getServletContext().getRealPath("/imgs/1.jpg");
		System.out.println("path="+path);
		FileInputStream fis=new FileInputStream(path);
		byte[] buff=new byte[1024];
		int len=0;
		OutputStream os= response.getOutputStream();
		while ((len=fis.read(buff))>0) {
			os.write(buff, 0, len);	
		}
		os.close();
		fis.close();*/
		
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print( "using" +this.getClass());
		out.println("<br>");
		out.print("i am "+request.getParameter("username")+"密码是:"+request.getParameter("password")+".");
		out.println("<br>");
		out.print("<a href='login.html'>back</a>");
		out.println("<br>");
		out.println("TIME:"+new Date());
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值