out对象是通过调用pageContext对象的getOut方法返回的,其作用和用法与ServletResponse.getWriter方法返回的PrintWriter对象非常相似。
JSP页面中的out隐式对象的类型为JspWriter,JspWriter相当于一种带缓存功能的PrintWriter,设置JSP页面的page指令的buffer属性可以调整它的缓存大小,甚至关闭它的缓存。
只有向out对象中写入了内容,且满足如下任何一个条件时,out对象才去调用ServletResponse.getWriter方法,并通过该方法返回的PrintWriter对象将out对象的缓冲区中的内容真正写入到Servlet引擎提供的缓冲区中:
设置page指令的buffer属性关闭了out对象的缓存功能
out对象的缓冲区已满
整个JSP页面结束
同时使用out和response.getwriter()输出数据。
<%
out.write("fan");
response.getWriter().write("hi");
%>
用JSP实现文件下载。
//下载ServletContext
String path = application.getRealPath("./images/04.jpg");
//得到下载的文件
File file = new File(path);
//得到文件的输入流
InputStream is = new FileInputStream(file);
response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
//得到文件 输出流
OutputStream os = response.getOutputStream();
byte buffer[] = new byte[1024];
int len =0 ;
while((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
}
os.flush();
os.close();
is.close();
//实现访问次数
<%! int blue=0; %>
<%
if(application.getAttribute("JiShu")==null){
application.setAttribute("JiShu","0");
}else{
blue=Integer.parseInt(application.getAttribute("JiShu").toString());
blue=blue+1;
application.setAttribute("JiShu",blue+"");
System.out.println(blue);
out.print("你是第"+blue+"个访问的嘎嘎");
}
%>