JSP内置对象--application对象(getRealPath(),getAttributeNames(),getContextPath())

application对象是javax.servlet.ServletContext接口的实例化对象。是整个servlet的上下文,代表了整个web容器的操作。

常用方法:

1.java.lang.String getRealPath(java.lang.String path):得到虚拟目录对应的绝对路径;

2. java.util.Enumeration<java.lang.String> getAttributeNames():得到所有属性的名称

3. java.lang.String getContextPath():取得当前的虚拟路径名称

除了以上3个方法外,对属性的增加,取得和删除也有应用,setAttribute(),getAttribute(), removeAttribute()

  • 取得绝对路径

例子:

<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
<%    // http://localhost/mldn/
    String path = application.getRealPath("/") ;
%>
<h3>真实路径:<%=path%></h3>
</body>
</html>

运行结果:

真实路径:D:\Workspace\

这个真实路径就是server.xml里配置的。

需要注意,application的操作本身是ServletContext接口的实例,但是在jsp中有个方法的功能可以完全与之对应,getServletContext();

<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
<%    // http://localhost/mldn/
    String path = this.getServletContext().getRealPath("/") ;
%>
<h3>真实路径:<%=path%></h3>
</body>
</html>

这两个操作的效果完全一样,在正常情况下,所有的方法不是由对象调用么?那为什么这里面没有对象。

如果非要加上一个对象的话,就需要用this表示。

一定要记住,this.getServletContext()非常重要!!!实际使用中替代application操作

因为取得绝对路径,就意味着jsp可以进行文件操作了。

如果要想进行文件操作,一个要通过一个File类找到一个指定的路径。这个路径最好是绝对路径,这个时候,getRealPath()方法就起作用了,因为所有的web目录都是活的。

input_content.htm:

<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
<form action="input_content.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>

input_content.jsp:

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
<%    
    request.setCharacterEncoding("GBK") ;    // 解决乱码问题
    String name = request.getParameter("filename") ;
    String content = request.getParameter("filecontent") ;
    // 要想操作文件必须有绝对路径,那么这个时候getRealPath()
    String fileName = this.getServletContext().getRealPath("/") + "note" + File.separator + name ;    // 保存在note文件夹之中
    File file = new File(fileName) ;    // 实例化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. 网站人数可能很多,需要要用BigInteger完成

2. 用户每次第一次访问的时候才需要计数操作。执行计算前必须使用isNew()判断

3. 更改,保存的时候需要进行同步操作

count.jsp;

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.math.*"%>
<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
<%!
    BigInteger count = null ;
%>
<%!    // 为了开发简便,将所有的操作定义在方法之中,所有的异常直接加入完整的try...catch处理
    public BigInteger load(File file){
        BigInteger count = null ;    // 接收数据
        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")) ;    // 再原本的基础上增加1。
            save(file,count) ;
        }
    }
%>
<h2>您是第<%=count==null?0:count%>位访客!</h2>
</body>
</html>

 

  • 查看属性

application里也存在属性操作,有个方法可以取得全部属性:getAttributeNames()

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="java.util.*"%>
<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
<%    
    Enumeration enu = this.getServletContext().getAttributeNames() ;    // 取得全部的属性
    while(enu.hasMoreElements()){
        String name = (String) enu.nextElement() ;
%>
        <h4><%=name%> --> <%=this.getServletContext().getAttribute(name)%></h4>
<%
    }
%>
</body>
</html>

通过tomcat配置的第三方jar文件,都是通过application属性设置到服务器上去的,所以在每次配置一个新的开发包的时候,服务器必须重新启动。

 

总结:

1. application表示上下文的资源环境

2. 实际中可以使用this.getServletContext()方法来代替application的使用

3. 通过getRealPath()方法来取得一个虚拟目录对应的真实路径

 

posted @ 2015-11-10 15:22  wujixing909  阅读(3132)  评论(0编辑  收藏  举报