一:网站计数器(BigInteger)
<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.math.*"%>
<html>
<head>
<title> webSiteCount </title>
</head>
<body>
<%!
BigInteger count = null;
%>
<%!
public BigInteger loadBCount(File file)
{
try
{
if(file.exists())//已有存档文件
{
Scanner scan = new Scanner(new FileInputStream(file));
if(scan.hasNext())
{
count = new BigInteger(scan.next());
}
scan.close();
}
else//新建文件
{
count = new BigInteger("0");
save(file,count);
}
}catch(Exception e)
{
e.printStackTrace();
}
return count;
}
public void save(File file,BigInteger count)
{
try
{
PrintStream ps = null;
ps = new PrintStream(new FileOutputStream(file));
ps.println(count);
ps.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
%>
<%
String fileName = this.getServletContext().getRealPath("/") + "webSiteCount.txt";
File file = new File(fileName);
if(session.isNew())
{
synchronized(this)
{
count = loadBCount(file); //从文件读出
count = count.add(new BigInter("1")); //自加
save(file,count);
}
}
%>
<h2> 您是第<%=(count==null?0:count)%>位访客 </h2>
</body>
</html>
二:获取文件操作所需的路径
<h3> application.getRealPath("/")结果:<%=application.getRealPath("/")%> </h3>
<h3> getServletContext().getRealPath("/")结果:<%=getServletContext().getRealPath("/")%> </h3>
<h3> this.getServletContext().getRealPath("/")结果:<%=this.getServletContext().getRealPath("/")%> </h3>
三:文件操作
提交页面
<form action="applicationDemo.jsp" method="post">
文件名:<input type="text" name="filename" value="">
<br>
文件内容:<textarea name="cont" rows="3" clos="30" >
</textarea>
<br>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
处理页面
<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<html>
<head>
<title> applicationDemo </title>
</head>
<body>
<%
request.setCharacterEncoding("GBK");
String name = request.getParameter("filename");
String content = request.getParameter("cont");
String path = this.getServletContext().getRealPath("/")+"writeTo"+"/"+name;
File file = new File(path);
if(! file.getParentFile().exists())
{
file.getParentFile().mkdir();
}
PrintStream 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>
四:获得全部属性键值
<%
Enumeration enm = this.getServletContext().getAttributeNames();//取得全部属性
while(enm.hasMoreElements())
{
String name = (String)enm.nextElement();
%>
<h4> 属性:<%=name%> ,值:<%=this.getServletContext().getAttribute(name)%></h4>
<%
}
%>