JavaWeb API整理学习

来源:互联网 发布:淘宝详情页是怎么做的 编辑:程序博客网 时间:2024/06/05 21:11

1.1. ServletConfig对象说明(了解)

1:

该对象可以获取实例化对象初始化信息

初始化信息需要在web.xml配置文件中配置信息

通过该api方法 String getInitParameter(String name)  根据参数名称 获得 值

 <servlet>
    <servlet-name>CookieServlet</servlet-name>
    <servlet-class>cn.myhome.test.CookieServlet</servlet-class>
    <init-param>
        <param-name>encode</param-name>
        <param-value>utf-8</param-value>
    </init-param>
  </servlet>

2:

获取ServletConfig对象方法  参看GenericServlet源码  init(ServletConfig config ){

 this.config = config;

 init();

}

3: 在自定义的Servlet中  直接获取该对象  this.getServletConfig(); 对象

String encode = this.getServletConfig().getInitParameter("encode");------->utf-8

在配置了init-parm标签的servlet 代码中 通过ServletConfig 对象获取配置信息;注意并不是所有的servlet都能获取该配置信息的。它专属于配置了init-parm标签的Servlet


1.2. Servlet上下文对象 ServletContext (部分掌握)

1、ServletContext每个工程对应一个

2、获得ServletContext对象 ----- >servletConfig.getServletContext();

                               或者this.getServletContext();


全局初始化参数配置 (所有Servlet都可以访问)

* 和ServletConfig配置初始化参数 区分开

1) 配置全局初始化参数

  当前web应用所有的组件(servlet & jsp) 都可以访问

<!-- web.xml 文件中去配置信息 全局初始化参数-->

在容器启动的时候 初始化参数就有了...

2) 获得ServletContext对象 ServletContext context =getServletContext();

3) 通过 StringgetInitParameter(String name)  获得全局参数信息



        String encode = this.getServletConfig().getInitParameter("encode");
        String contextPath = this.getServletContext().getContextPath();   //--------->/writeWebCode01
        System.out.println(contextPath);
        String url = this.getServletContext().getInitParameter("url");//------>jdbc:mysql//localhost:8080/manager
        System.out.println(url);
        String realPath = this.getServletContext().getRealPath("web.xml");//WEB-INF下的文件路径通过该方法获得
        System.out.println(realPath);//磁盘中实际的路径

         String mimeType = this.getServletContext().getMimeType(".html");//注意   点不能忘掉
        System.out.println(mimeType);//                 text/html


ServletContext 对象可以获取服务器下所有资源的路径  getRealPath() 获取服务器绝对路径

     

应用: ServletContext获取服务器资源的绝对路径

  String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/b.txt");//src目录下的b.txt文件   ------>

        File f= new File(realPath);
        System.out.println(f.exists());//true
        realPath = this.getServletContext().getRealPath("/a.txt");//WebContent目录下的a.txt文件
        f= new File(realPath);
        System.out.println(f.exists());//true
        realPath = this.getServletContext().getRealPath("/WEB-INF/mm/c.txt");//WebContent目录下mm文件夹下的c.txt文件
        f= new File(realPath);
        System.out.println(f.exists());//true
        //工程下的d.txt文件没有发布到服务器上,所有不能访问



0 0