取得绝对路径:
1 通过application得到
2 通过this.getServletContext()方法得到
如果取得了绝对路径,那么就意味着在jsp之中可以进行文件操作了。
如果想要进行文件操作首先一定要通过File类只熬到一个指定的路径,这个路径最好是绝对路径,
所以这个时候getRealPath()方法就起到了作用了,因为所有的web目录都是活的。
创建文件用例:
<%@page contentType="text/html" pageEncoding="Utf-8"%>
<html>
<body>
<form method="post" action="day4q.jsp">
请输入文件名称:<input name="filename" type="text"><br>
请输入文件内容:<textarea name="filecontent" cols="20" rows="3">
</textarea><br>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
</html>
day4q.jsp:
<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@page import="java.io.*" %>
<%@page import="java.util.*" %>
<html>
<body>
<%
request.setCharacterEncoding("utf-8");
String name=request.getParameter("filename");
String content=request.getParameter("filecontent");
//要想操作文件必须有绝对路径
String path=this.getServletContext().getRealPath("/")
+"note"+File.separator+name; //保存在note文件夹之中
File file=new File(path); //实例化File类对象
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>
网站计数器:
开发注意
1:网站的来访人数可能会很多,有可能超过20位整数,所以必须使用大整数类,BigInteger完成;
2:用户每次在第一次访问的时候才需要进行计数的操作,在执行之前必须使用isNew()判断;
3:在进行更改,保存的时候需要进行同步操作。(异步处理)
代码:
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@page import="java.io.*" %>
<%@page import="java.util.*"%>
<%@page import="java.math.*" %>
<html>
<body>
<%!
BigInteger count = null ;
%>
<%! //为了开发方便,将所有的操作定义在方法之中,所有异常直接抛出
public BigInteger load(File file){
//接收数据
try {
if(file.exists()){
Scanner scan = new Scanner(new
FileInputStream(file));
if(scan.hasNext()){ //内容很大,以字符串读取
count = new BigInteger(scan.next());
}
scan.close();
}else{ // 应该保存一个新的,从0开始
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("/")+"count.txt";
File file = new File(fileName);
if(session.isNew()){ //如果是新用户
synchronized(this){
count = load(file);
count = count.add(new BigInteger("1"));
save(file,count);
}
}
%>
<h2>您是第<%=count==null?0:count%>位</h2>
</body>
</html>
查看属性:在application中有一个方法可以取得所有属性:getAttributeNames()
<%@page import="java.util.Enumeration"%>
<%@page contentType="text/html" pageEncoding="utf-8" %>
<html>
<body>
<%
Enumeration en=this.getServletContext().getAttributeNames();
while(en.hasMoreElements()){
String name=(String)en.nextElement();
%>
<h4> <%= name%>----><%=this.getServletContext().getAttribute("name")%></h4>
<%
}
%>
</body>
</html>