ServletConfig:封装servlet的配置信息。

在Servlet的配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数。

<servlet>
  <servlet-name>ServletDemo4</servlet-name>
  <servlet-class>cn.itcast.web.servlet.ServletDemo4</servlet-class>
  <init-param> <!-- servletConfig -->
    <param-name>charset</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
  <init-param> <!-- servletConfig -->
    <param-name>xxx</param-name>
    <param-value>yyy</param-value>
  </init-param>
</servlet>

当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,程序员通过ServletConfig对象就可以得到当前servlet的初始化参数信息。

 import java.io.IOException;
 import java.util.Enumeration;

 import javax.servlet.ServletConfig;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 //通过servletCOnfig获取servlet配置的初始化参数
 public class ServletDemo4 extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {

         ServletConfig config = this.getServletConfig();

         //获取配置的初始化参数的方式1
         //String value = config.getInitParameter("charset");

         Enumeration e = config.getInitParameterNames();
         while(e.hasMoreElements()){
             String name = (String) e.nextElement();
             String value = config.getInitParameter(name);
             System.out.println(name + "=" + value);
         }

     }

     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doGet(request, response);
     }

 }

应用场景:

  获得字符集编码(编码是配置的,最好不要写死)
  获得数据库连接信息
  获得配置文件,查看struts案例的web.xml文件

ServletContext:代表当前web应用。即每个web应用都对应一个ServletContext

  WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。

  ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得代表当前web应用的   ServletContext对象。

  由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。

  ServletContext对象通常也被称之为context域对象。(即该对象作用范围为:整个web应用生命周期内)

获取代表当前web应用的ServletContext对象的方式:

1.ServletContext context=this.getServletConfig().getServletContext();

2.从父类继承而来

  ServletContext context= this.getServletContext();

  类似ServletConfig的获取方式

  ServletConfig config = this.getServletConfig();

ServletContext应用:

1. 多个Servlet通过ServletContext对象实现数据共享。

  ServletContext context= this.getServletContext();

  context.setAttribute("data","aa");//在一个servlet中设置值

  context.getAttribute("data");//在另一个servlet中可以获取该值。

2. 通过ServletContext获取WEB应用的初始化参数。

 <!-- 为web应用设置初始化参数,这些设置的初始化参数可以通过servletContext对象的getInitParameter()方法获取 -->
  <context-param>
      <param-name>url</param-name>
      <param-value>jdbc:mysql://localhost:3306/test</param-value>
  </context-param>

  <context-param>
      <param-name>username</param-name>
      <param-value>root</param-value>
  </context-param>

  <context-param>
      <param-name>password</param-name>
      <param-value>root</param-value>
  </context-param>
 import java.io.IOException;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 //通过servletContext,获取为web应用配置的初始化参数
 public class ServletDemo7 extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {

         //String value = this.getServletContext().getInitParameter("xxx");
         String url = this.getServletContext().getInitParameter("url");
         String username = this.getServletContext().getInitParameter("username");
         String password = this.getServletContext().getInitParameter("password");

         System.out.println(url);
         System.out.println(username);

     }

     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doGet(request, response);
     }

 }

3.获取文件的mime类型

//通过servletContext获取文件的mime类型
public class ServletDemo8 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String filename = "1.jpg";

        ServletContext context = this.getServletContext();
        System.out.println(context.getMimeType(filename));//获取指定文件的mime类型

        response.setHeader("content-type", "image/jpeg");//如果已经知道输出的文件的mime类型,可以这么写
      
     response.setHeader("content-type",context.getMimeType(filename));//如果不知道文件类型,可以先通过ServletContext获取 

    }

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

4.  通过servletContext 实现请求转发 。(MVC设计模式)

//servlet收到请求产生数据,然后转交给jsp显示
String data = "aaaaaa"; this.getServletContext().setAttribute("data", data); RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/view.jsp");//得到转发请求对象 rd.forward(request, response);

5. 利用ServletContext对象读取资源文件。

  得到文件路径
     读取资源文件的三种方式
     .properties文件(属性文件)

getRealPath(string path)---根据web应用中的相对路径得到在硬盘的物理路径(绝对路径)。用来在web工程中读取文件。

getResource(string path)--根据路径获取url

  getResourceAsStream(path)

getResourcePaths(path)

  读取资源文件的三种方式:  资源文件在Eclipse  web工程的WebRoot根目录下。

 //读取配置文件的第一种方式,相对路径
    private void test1() throws IOException {

        ServletContext context = this.getServletContext();
        InputStream in = context.getResourceAsStream("/db.properties");//db.properties在WebRoot根目录下。/ 代表web应用根目录

        Properties prop = new Properties();  //map
        prop.load(in);

        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");

        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
    }
//读取配置文件的第二种方式,得到物理路径
    private void test2() throws IOException {
        ServletContext context = this.getServletContext();
        String realpath = context.getRealPath("/db.properties");  //c:\\sdsfd\sdf\db.properties

        //获取到操作文件名   realpath=abc.properties
        String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
        System.out.println("当前读到的文件是:" + filename);

        FileInputStream in = new FileInputStream(realpath);
        Properties prop = new Properties();
        prop.load(in);

        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");

        System.out.println("文件中有如下数据:");
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);

    }
    
//读取配置文件的第三种方式
    private void test3() throws IOException {
        ServletContext context = this.getServletContext();
        URL url = context.getResource("/db.properties");
        InputStream in = url.openStream();
....
     //下面代码用方式一,二的模板代码 }

读取的资源文件在eclipse web工程中src文件夹里。该如何读???

//读取src下面的配置文件(传统方式FileInputStream不可取)
    private void test4() throws IOException {
        FileInputStream in = new FileInputStream("src/db.properties");//src目录里的文件发布时,会部署到WebRoot根目录里的WEB-INF里的classes文件夹下。
        System.out.println(in);
    }
上面即使改为: FileInputStream in = new FileInputStream("/WEB-INF/classes/db.properties");也不行,因为这里的相对路径,是指相对JVM的启动路径。
即tomcat的bin目录。startup.bat所在的目录。

正确的方式为:
//读取src下面的配置文件
    private void test5() throws IOException {
        InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties prop = new Properties();  //map
        prop.load(in);

        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");

        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
    }
    

下面是超级重要的东西:

 在web工程的普通java程序中如何读取资源文件

如数据库访问层的包中放置了数据库的配置文件db.properties,由于该包中的文件是普通的java程序,不是上面所说的servlet,
那么在开发中该如何读取呢???
用类装载器去读,类装载器只能装载类目录下的文件,即db.properties只能在src目录下,不能放在WebRoot根目录下。

package cn.itcast.dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

//在web工程的普通java程序中如何读取资源文件
public class StudentDao {  //不是servlet

    public String get() throws IOException {  //类装载器读
        test1();
        test2();
        return null;
    }

    //以下代码在读文件时,可以读到更新后的文件,用类装载器去读取文件位置,数据依然用传统方式去读。
    public void test2() throws IOException{

        ClassLoader loader = StudentDao.class.getClassLoader();//得到该类的类装载器
URL url = loader.getResource("cn/itcast/dao/db.properties");//用类装载器的方法区装载 String filepath = url.getPath();//得到文件在硬盘的绝对路径,之后可以用传统方式去读 FileInputStream in = new FileInputStream(filepath); Properties prop = new Properties(); //map prop.load(in); String dburl = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); System.out.println(dburl); System.out.println(username); System.out.println(password); } //以下代码在读文件时,读到不到更新后的文件 public void test1() throws IOException{ ClassLoader loader = StudentDao.class.getClassLoader(); InputStream in = loader.getResourceAsStream("cn/itcast/dao/db.properties"); Properties prop = new Properties(); //map prop.load(in); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); System.out.println(url); System.out.println(username); System.out.println(password); } }
注意: 

如果db.properties在src的根目录,路径写法:
    loader.getResourceAsStream("db.properties");
如果db.properties在package cn.itcast.dao里,路径写法:
    loader.getResourceAsStream("cn/itcast/dao/db.properties");

通过类装载器读文件时,需要注意的问题:不能装载大文件,否则会内存溢出。
如果文件很大,可以使用类装载器获得路径,然后用传统io方式去读。


getServletContextName()方法:获取web.xml配置文件中配置的web应用的名称
<display-name>sina</display-name>

应用场景:
//获取web.xml文件中配置的web应用的显示名称
public class ServletDemo13 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = this.getServletContext().getServletContextName();

        response.getWriter().write("<a href='/"+name+"/1.html'>点点</a>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}


对于不经常变化的数据,在servlet中可以为其设置合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能。


//设置浏览器的缓存
public class ServletDemo14 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        long expriestime = System.currentTimeMillis() + 1*24*60*60*1000;
        response.setDateHeader("expires", expriestime);
        String data = "adsdfsdfsdfsdfdsf";
        response.getWriter().write(data);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

ServletConfig与ServletContext对象(接口)的更多相关文章

  1. day05 Servlet 开发和 ServletConfig 与 ServletContext 对象

    day05 Servlet 开发和 ServletConfig 与 ServletContext 对象 1. Servlet 开发入门 - hello world 2. Servlet 的调用过程和生 ...

  2. ServletConfig与ServletContext对象详解

    一.ServletConfig对象 在Servlet的配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数.(配置在某个servlet标签或者整个w ...

  3. javaWEB总结(4):ServletContext对象方法

    前言:之前每次学到ServletContext对象都会抗拒,跳着学,后面才发现有很多不懂的原理都在这个对象里面,后悔莫及,所以今天特地把他单放在一篇文章里,算是对他的忏悔. 1.什么是ServletC ...

  4. ServletConfig与ServletContext

    ServletConfig与ServletContext对象详解 一.ServletConfig对象    在Servlet的配置文件中,可以使用一个或多个<init-param>标签为s ...

  5. mvc-servlet---ServletConfig与ServletContext对象详解(转载)

    ServletConfig与ServletContext对象详解 一.ServletConfig对象    在Servlet的配置文件中,可以使用一个或多个<init-param>标签为s ...

  6. 一、HttpServletRequest接口 二、HttpServletReponse接口 三、POST和GET请求方式及其乱码处理 四、ServletContext对象和ServletConfig对象

    一.HttpServletRequest接口 内部封装了客户端请求的数据信息 接收客户端的请求参数.HTTP请求数据包中配置参数 ###<1>常用方法 getContextPath()重要 ...

  7. Servlet接口的实现类,路径配置映射,ServletConfig对象,ServletContext对象及web工程中文件的读取

    一,Servlet接口实现类:sun公司为Servlet接口定义了两个默认的实现类,分别为:GenericServlet和HttpServlet. HttpServlet:指能够处理HTTP请求的se ...

  8. Java Servlet(三):Servlet中ServletConfig对象和ServletContext对象

    本文将记录ServletConfig/ServletContext中提供了哪些方法,及方法的用法. ServletConfig是一个抽象接口,它是由Servlet容器使用,在一个servlet对象初始 ...

  9. 小谈-—ServletConfig对象和servletContext对象

    一.servletContext概述 servletContext对象是Servlet三大域对象之一,每个Web应用程序都拥有一个ServletContext对象,该对象是Web应用程序的全局对象或者 ...

随机推荐

  1. Ajax中参数带有html格式的 传入后台保存【一】

    因业务需求  要讲如下编辑器中带有样式的数据传入数据库保存 第一种方法  json格式传入 $(".privilegezn_page .btn_ok").click(functio ...

  2. QQ互联功能

    QQ作为现在使用人数最多的几个聊天软件之一,倘若能够方便的进行沟通(在大家的机器上都安装了QQ客户端或者浏览器的前提下),在商家推广的时候也许会带来不小的利益. http://wp.qq.com/in ...

  3. C/C++ - <string> 与<string.h>、<cstring>的区别

    <string.h><string.h>是C版本的头文件,包含比如strcpy.strcat之类的字符串处理函数. <string><string>是C ...

  4. UltraEdit 中的常用正则表达式

    正则表达式 (UltraEdit Syntax):   % 匹配行首 - 表明要搜索的字符串一定在行首.   $ 匹配行尾 - 表明要搜索的字符串一定在行尾   ? 匹配除换行符外的任一单个字符.   ...

  5. 计算机安装了IE8一半退出重启时,桌面只显示背景

    记得我在一家公司实习网管的时候,我遇到过一个这样的情况:那时候公司就我一个网管(原来的那个老员工走了才临时要了我),公司有台台式,上面装了公司的ERP还有一系列的软件.因为那个ERP限制了机器,用另外 ...

  6. 第三次冲刺spring会议(第一次会议)

    [例会时间]2014/5/20 21:15 [例会地点]9#446 [例会形式]轮流发言 [例会主持]马翔 [例会记录]兰梦 小组成员:兰梦 ,马翔,李金吉,赵天,胡佳

  7. 字符串长度截取换行/n

    /// <summary>        /// 格式化字符串长度,超出部分显示省略号,区分汉字跟字母.汉字2个字节,字母数字一个字节        /// </summary> ...

  8. jsp页面中EL表达式不能被解析

    原因是:在默认情况下,Servlet 2.4 / JSP 2.0支持 EL 表达式. 用maven插件的生成的webApp的项目结构比较老的是2.3的版本,只要将web中的开头定义换成2.4以上的定义 ...

  9. js上拉跳转原理

    今天遇到一个需要上拉跳转的地方,其原理跟上拉加载有点类似,代码如下 window.onscroll = function(){ if(getScrollTop() + getClientHeight( ...

  10. 多工段查询存放到DataTable到List<DataTable>集合在C#里面做汇总

    private void btnQuery_Click(object sender, EventArgs e) { if (cboxFactory.Text=="") { Mess ...