jspwriter和printwriter的区别
答案:2 悬赏:80
解决时间 2021-02-03 23:11
- 提问者网友:写不出迷人情诗
- 2021-02-03 20:15
今天查资料的时候看到了jspwriter和printwriter的区别, 但是其中的一部分不是很理解.
<%@page import="java.io.PrintWriter"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JspWriter versus PrintWriter</title>
</head>
<body>
I should be row one.</p>
<%
out.println("
JspWriter said: I should be the second row.</p>");
PrintWriter pw = response.getWriter();
pw.println("
PrintWriter said: I should be the third row.</p>");
%>
I should be the fourth row.</p>
</body>
</html>
输出如下:
PrintWriter said: I should be the third row.
I should be row one.
JspWriter said: I should be the second row.
I should be the fourth row.
后来查了一下, 几乎所有的博客都是这么解释的:
不管JspWriter与PrintWriter在程序中的顺序怎么样,始终先会输出PringWriter中的数据然后再输出JspWriter中的数据.这是因为jsp内置的out对象相当于插入到了PrintWriter前面的缓冲区中.out对象满足一定条件时,才会调用PrintWriter对象的print()方法,把out缓冲区中的内容输出到浏览器端
但是不是很明白什么意思?求大神指点迷津
最佳答案
- 二级知识专家网友:承载所有颓废
- 2021-02-03 21:44
jspwriter和printwriter的区别:
JspWriter是抽象类而PrintWriter不是,也就是说你可以通过new操作来直接新建一个PrintWriter的对象而JspWriter不行,它必须是通过其子类来新建。
但是它们之间又是有关系的,这个关系主要是JspWriter对PrintWriter有依赖。初始化一个JspWriter对象的时候要关联ServletResponse对象的一个PrintWriter类型对象,最终JspWriter对象的输出任务还是通过这个PrintWriter类型对象做的
JspWriter是抽象类而PrintWriter不是,也就是说你可以通过new操作来直接新建一个PrintWriter的对象而JspWriter不行,它必须是通过其子类来新建。
但是它们之间又是有关系的,这个关系主要是JspWriter对PrintWriter有依赖。初始化一个JspWriter对象的时候要关联ServletResponse对象的一个PrintWriter类型对象,最终JspWriter对象的输出任务还是通过这个PrintWriter类型对象做的
全部回答
- 1楼网友:桃花别处起长歌
- 2021-02-03 22:16
你英文好,读懂下面的话,你的问题也就解决了
JspWriter uses a PrintWriter behind the scene, but since by default JSP pages are buffered, the PrintWriter won't be created until the buffer is flushed
This means that what is written to the JspWriter is buffered, and once this buffer is flushed (either because the buffer is full, or because the JSP has reached the end of its execution), the contents is written to the response's PrintWriter.
So the flow of your example is the following one:
static HTML code until the scriptlet: written to the in-memory buffer
out.println(...): written to the in-memory buffer
pw.println(...): written to the response
static HTML code until the end of the JSP: written to the in-memory buffer
flush of the in-memory buffer: all it contains is written to the response
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯