application对象
application对象直接包装了servlet的ServletContext类的对象,是javax.servlet.ServletContext 类的实例。
这个对象在JSP页面的整个生命周期中都代表着这个JSP页面。这个对象在JSP页面初始化时被创建,随着jspDestroy()方法的调用而被移除。
通过向application中添加属性,则所有组成您web应用的JSP文件都能访问到这些属性。
主要方法:
取得绝对路径:(重点)
用以下代码取得路径:
<%
String path = application.getRealPath("/");
%>
或者:
<%
String path = this.getServletContext().getRealPath("/");
%>
这样,就可以操作文件了
用获取绝对路径的办法写入并读取文件
writerandread.html:
<html>
<head><title>www.thystar.com</title></head>
<body>
<form action="application_demo.jsp" method = "post">
<input type = "text" name = "filename"><br>
<textarea name = "filecontent" cols = "30" rows = "3"></textarea><br>
<input type = "submit" value = "保存">
<input type = "reset" value = "重置">
</form>
</body>
</html>
application_demo.jsp
<%@ page contentType = "text/html" pageEncoding = "GBK"%>
<%@ page import = "java.io.*"%>
<%@ page import = "java.util.*"%>
<html>
<head><title>www.thystar.com</title></head>
<body>
<% //写入文件
request.setCharacterEncoding("GBK");
String name = request.getParameter("filename");
String content = request.getParameter("filecontent");
String fileName = this.getServletContext().getRealPath("/") + "note" + File.separator + name;
File file = new File(fileName);
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();
}
PrintStream ps = null;
ps = new PrintStream(new FileOutputStream(file));
ps.println(content);
ps.close();
%>
<% //读出文件
Scanner scan = new Scanner(new FileInputStream(file));
scan.useDelimiter("\n");
StringBuffer buf = new StringBuffer();
while(scan.hasNext()){
buf.append(scan.next()).append("<br>");
}
scan.close();
%>
<%=buf%>
</body>
</html>
《Java Web开发实战经典--基础篇》