深入分析JavaWeb Item6 -- servletConfig 与servletContext详解_servlet context item

    String data = "xdp\_gacl";
    /\*\*

* ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,
* 可以通过ServletConfig.getServletContext方法获得ServletContext对象。
*/
ServletContext context = this.getServletConfig().getServletContext();//获得ServletContext对象
context.setAttribute(“data”, data); //将data存储到ServletContext对象中
}

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

}



package gacl.servlet.study;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo2 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    String data = (String) context.getAttribute("data");//从ServletContext对象中取出数据
    response.getWriter().print("data="+data);
}

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

}


  先运行`ServletContextDemo1`,将数据data存储到`ServletContext`对象中,然后运行`ServletContextDemo2`就可以从`ServletContext`对象中取出数据了,这样就实现了数据共享,如下图所示:


  ![这里写图片描述](https://img-blog.csdn.net/20151204150021315)


##### **3.2、获取WEB应用的初始化参数**


  如果想在所有的Servlet应用中都要配置并读取初始化参数,则可以在`web.xml`文件的`<web-app>`中使用`<context-param>`标签配置WEB应用的初始化参数,如下所示:



<?xml version="1.0" encoding="UTF-8"?>





url
jdbc:mysql://localhost:3306/test

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
```

获取Web应用的初始化参数,代码如下:

package gacl.servlet.study;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ServletContextDemo3 extends HttpServlet {

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

        ServletContext context = this.getServletContext();
        //获取整个web站点的初始化参数
        String contextInitParam = context.getInitParameter("url");
        response.getWriter().print(contextInitParam);
    }

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

}

运行结果:

这里写图片描述

3.3、用servletContext实现请求转发

实现Servlet的转发。

  • ServletContextDemo4
package gacl.servlet.study;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo4 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String data = "<h1><font color='red'>abcdefghjkl</font></h1>";
        response.getOutputStream().write(data.getBytes());
        ServletContext context = this.getServletContext();//获取ServletContext对象
        RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");//获取请求转发对象(RequestDispatcher)
        rd.forward(request, response);//调用forward方法实现请求转发
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}
  • ServletContextDemo5
package gacl.servlet.study;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo5 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getOutputStream().write("servletDemo5".getBytes());
    }

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

}

运行结果:

这里写图片描述

访问的是ServletContextDemo4,浏览器显示的却是ServletContextDemo5的内容,这就是使用ServletContext实现了请求转发

3.4、利用ServletContext对象读取资源文件

利用ServletContext对象读取资源文件,因为文件的位置不同,所有读取的方式也不同,一般来说分为两种情况:

  • 在Servlet的context域中读取文件,工程目录下的src目录发布到服务器中,会映射到“/WEB-INF/classes”文件夹下。所以要一一对应。而且这个是相对目录,相对于web服务器的目录。如果要用传统的文件读取文件,则要使用绝对路劲
PrintWriter out = response.getWriter();
        ServletContext context = this.getServletContext();
        String path = context.getRealPath("/WEB-INF/classes/itcast.properties");
        InputStream in = new FileInputStream(path);
        Properties pro = new Properties();
        pro.load(in);
  • 如果是非servlet中读取配置文件,则要使用类加载器去读取。稍后讲到
     
    项目目录结构如下:

这里写图片描述

代码范例:使用servletContext读取资源文件

package gacl.servlet.study;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/\*\*
 \* 使用servletContext读取资源文件
 \* 
 \* @author gacl
 \* 
 \*/
public class ServletContextDemo6 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException { 
        /\*\*
 \* response.setContentType("text/html;charset=UTF-8");目的是控制浏览器用UTF-8进行解码;
 \* 这样就不会出现中文乱码了
 \*/
        response.setHeader("content-type","text/html;charset=UTF-8");
        readSrcDirPropCfgFile(response);//读取src目录下的properties配置文件
        response.getWriter().println("<hr/>");
        readWebRootDirPropCfgFile(response);//读取WebRoot目录下的properties配置文件
        response.getWriter().println("<hr/>");
        readPropCfgFile(response);//读取src目录下的db.config包中的db3.properties配置文件
        response.getWriter().println("<hr/>");
        readPropCfgFile2(response);//读取src目录下的gacl.servlet.study包中的db4.properties配置文件

    }

    /\*\*
 \* 读取src目录下的gacl.servlet.study包中的db4.properties配置文件
 \* @param response
 \* @throws IOException
 \*/
    private void readPropCfgFile2(HttpServletResponse response)
            throws IOException {
        InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/gacl/servlet/study/db4.properties");
        Properties prop = new Properties();
        prop.load(in);
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        response.getWriter().println("读取src目录下的gacl.servlet.study包中的db4.properties配置文件:");
        response.getWriter().println(
                MessageFormat.format(
                        "driver={0},url={1},username={2},password={3}", 
                        driver,url, username, password));
    }

    /\*\*
 \* 读取src目录下的db.config包中的db3.properties配置文件
 \* @param response
 \* @throws FileNotFoundException
 \* @throws IOException
 \*/
    private void readPropCfgFile(HttpServletResponse response)
            throws FileNotFoundException, IOException {
        //通过ServletContext获取web资源的绝对路径
        String path = this.getServletContext().getRealPath("/WEB-INF/classes/db/config/db3.properties");
        InputStream in = new FileInputStream(path);
        Properties prop = new Properties();
        prop.load(in);
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        response.getWriter().println("读取src目录下的db.config包中的db3.properties配置文件:");
        response.getWriter().println(
                MessageFormat.format(
                        "driver={0},url={1},username={2},password={3}", 
                        driver,url, username, password));
    }

    /\*\*
 \* 通过ServletContext对象读取WebRoot目录下的properties配置文件
 \* @param response
 \* @throws IOException
 \*/
    private void readWebRootDirPropCfgFile(HttpServletResponse response)
            throws IOException {
        /\*\*
 \* 通过ServletContext对象读取WebRoot目录下的properties配置文件
 \* “/”代表的是项目根目录
 \*/
        InputStream in = this.getServletContext().getResourceAsStream("/db2.properties");
        Properties prop = new Properties();
        prop.load(in);
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        response.getWriter().println("读取WebRoot目录下的db2.properties配置文件:");
        response.getWriter().print(
                MessageFormat.format(
                        "driver={0},url={1},username={2},password={3}", 
                        driver,url, username, password));
    }

    /\*\*
 \* 通过ServletContext对象读取src目录下的properties配置文件
 \* @param response
 \* @throws IOException
 \*/
    private void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException {
        /\*\*
 \* 通过ServletContext对象读取src目录下的db1.properties配置文件
 \*/
        InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db1.properties");
        Properties prop = new Properties();
        prop.load(in);
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        response.getWriter().println("读取src目录下的db1.properties配置文件:");
        response.getWriter().println(
                MessageFormat.format(
                        "driver={0},url={1},username={2},password={3}", 
                        driver,url, username, password));
    }

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

}

运行结果如下:

这里写图片描述

使用类装载器读取资源文件

我们在非servlet中读取资源文件时(比如在数据库的dao层读取配置文件),采用类装载器 classLoader,你可以先采用servlet服务先读取,然后在把servlet传递给dao,这样虽然可以实现,但是,这样损坏了我们编代码的设计原则,就是层之间不能有交织在一起的东西。

package gacl.servlet.study;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.Properties;

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

/\*\*
 \* 用类装载器读取资源文件
 \* 通过类装载器读取资源文件的注意事项:不适合装载大文件,否则会导致jvm内存溢出
 \* @author gacl
 \*
 \*/
public class ServletContextDemo7 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /\*\*
 \* response.setContentType("text/html;charset=UTF-8");目的是控制浏览器用UTF-8进行解码;
 \* 这样就不会出现中文乱码了
 \*/
        response.setHeader("content-type","text/html;charset=UTF-8");
        test1(response);
        response.getWriter().println("<hr/>");
        test2(response);
        response.getWriter().println("<hr/>");
        //test3();
        test4();

    }

    /\*\*
 \* 读取类路径下的资源文件
 \* @param response
 \* @throws IOException
 \*/
    private void test1(HttpServletResponse response) throws IOException {
        //获取到装载当前类的类装载器
        ClassLoader loader = ServletContextDemo7.class.getClassLoader();
        //用类装载器读取src目录下的db1.properties配置文件
        InputStream in = loader.getResourceAsStream("db1.properties");
        Properties prop = new Properties();
        prop.load(in);
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        response.getWriter().println("用类装载器读取src目录下的db1.properties配置文件:");
        response.getWriter().println(
                MessageFormat.format(
                        "driver={0},url={1},username={2},password={3}", 
                        driver,url, username, password));
    }

    /\*\*
 \* 读取类路径下面、包下面的资源文件
 \* @param response
 \* @throws IOException
 \*/
    private void test2(HttpServletResponse response) throws IOException {
        //获取到装载当前类的类装载器
        ClassLoader loader = ServletContextDemo7.class.getClassLoader();
        //用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件
        InputStream in = loader.getResourceAsStream("gacl/servlet/study/db4.properties");


### 基础面试题

**[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/topics/618166371)**

> 主要内容包括:**HTML,CSS,JavaScript,浏览器,性能优化等等**

rvletResponse response) throws IOException {
        //获取到装载当前类的类装载器
        ClassLoader loader = ServletContextDemo7.class.getClassLoader();
        //用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件
        InputStream in = loader.getResourceAsStream("gacl/servlet/study/db4.properties");


### 基础面试题

**[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/topics/618166371)**

> 主要内容包括:**HTML,CSS,JavaScript,浏览器,性能优化等等**

![](https://img-blog.csdnimg.cn/img_convert/da9603db32ce6df2eb14c46f28367633.webp?x-oss-process=image/format,png)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值