ch6.JSP内置对象--application对象

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开发实战经典--基础篇》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值