jsp学习笔记 - 内置对象 application

时间:2023-03-10 02:34:31
jsp学习笔记 - 内置对象 application

---恢复内容开始---

1.application一般用this.getServletContext()替代

2.appllication有一个非常有用的函数 getRealPath(),获取绝对路径,以便实现jsp的文件操作

String fileName = this.getServletContext().getRealPath("/") + "note" + File.separator + name;

3.保存文件用 PrintStream类对象  

File file = new File(fileName);  

 if (!file.getParentFile().exists()){
    file.getParentFile().mkdir();
 }

 PrintStream ps = null;

ps = new PrintStream(new FileOutputStream(file));

ps.println(fileContent);
   ps.close();

3.读取文件用Scanner类对象

Scanner scan = new Scanner(new FileInputStream(file));

scan.useDelimiter(";");

 StringBuffer buf = new StringBuffer();

 while(scan.hasNext()){

  buf.append(scan.next()).append("<br>");

} 

  scan.close();

<%=buf%>

4.获取服务器环境属性

<%
Enumeration enu = this.getServletContext().getAttributeNames() ; // 取得全部的属性
while(enu.hasMoreElements()){
String name = (String) enu.nextElement() ;
%>
<h4><%=name%> --> <%=this.getServletContext().getAttribute(name)%></h4>
<%
}
%>