Servlet3- ServletConfig & ServletContext

ServletConfig

  • Servlet配置文件中,可以使用一个或多个<init-param>标签配置一些初始化参数
  • 创建实例对象时,自动将初始化参数封装到ServletConfig对象中,并在调用Servlet的init方法时,将Servletconfig对象传递给servlet。
<!-- 演示初始化参数 -->
  <servlet>
    <servlet-name>ServletDemo6</servlet-name>
    <servlet-class>cn.servlet.ServletDemo6</servlet-class>
    
    <!-- 配置初始化参数 -->
    <init-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </init-param>
    <init-param>
        <param-name>password</param-name>
        <param-value>123</param-value>
    </init-param>
    
  </servlet>

ServletConfig的几种方法:

  • String getServletName() 得到当前servlet的名字
  • String getInitParameter(String name) 通过参数名获得参数值
  • java.util.Enumeration<E> getInitParameterNames() 将所有参数返回到一个枚举对象中
  • ServletContext getServletContext() 返回ServletContext对象
public class ServletDemo6 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //测试ServletConfig对象的api
        //先获取ServletCongig对象
        ServletConfig config = getServletConfig();
        //获取配置文件中servlet的名称
        System.out.println("servlet的名称:"+ config.getServletName());
        
        //获取初始化参数
        String username = config.getInitParameter("username");
        String password = config.getInitParameter("password");
        System.out.println(username + password);
        
        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);
    }
}

ServletContext对象(域对象)

  • 每个web应用程序都创建一个对应的ServletContext对象,代表当前web应用
  • 通过 ServletConfig.getServletContext方法获得该对象
  • 一个web应用中所有Servlet共享同一个ServletContext对象,所以可以通过ServletContext实现通讯
  • 应用
    • 获取web应用的全局初始化参数
      • String getInitParameter(String)
    • getInitParameterNames()
    • 通过ServletContext对象实现数据共享
      • void setAttribute(String name, Object obj) 存入数据
      • void removeAttribute(String name) 删除数据
      • Object getAttribute(String name) 获取数据
    • 利用ServletContext对象读取资源文件
      • InputStream getResourceAsStream(String path) 通过文件的地址获取输入流
      • String getRealPath(String path) 通过文件的地址获取文件的绝对路径
<!-- 配置全局的初始化参数 web.xml-->
    <context-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </context-param>
public class ContextDemo1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取ServletContext对象
        ServletContext context = getServletContext();
        //读取全局的初始化参数
        String encoding = context.getInitParameter("encoding");
        System.out.println("编码:"+ encoding);
        
        Enumeration e = context.getInitParameterNames();
        while(e.hasMoreElements()){
            String name = (String)e.nextElement();
            String value = context.getInitParameter(name);
            System.out.println(name + ":" +value);
        }
    }

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

}
public class CountServlet extends HttpServlet {
    
    /**
     * 实例被创建,调用init方法进行初始化
     * 在域对象中存入一个变量,赋值为0
     */
    public void init() throws ServletException {
        //获取ServletContext对象
        getServletContext().setAttribute("count", 0);
    }

    /**
     * 每一次访问,都会执行该方法
     * 拿出Count变量,值自增,存进去
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        ServletContext context = getServletContext();
        Integer count = (Integer)context.getAttribute("count");
        context.setAttribute("count", ++count);
        System.out.println("被访问了 ");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("<h1>打野下次来</h1>");
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}



//另一个servlet文件,用来显示网站显示次数
public class Show extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Integer count = (Integer)getServletContext().getAttribute("count");
        
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("<h1>那个网站被访问了"+count+"次</h1>");
        System.out.println("被访问了 ");
    }

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

}
public class ReadServlet extends HttpServlet {

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

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

    /**
     * 通过ServletCOntext获取文件的绝对路径
     * @throws IOException
     */
    public void read3() throws IOException{
        //获取对象
        String path = getServletContext().getRealPath("/WEB-INF/classes/db.properties");
        System.out.println(path);
        InputStream in = getServletContext().getResourceAsStream(path);
        //打印方式
        print(in);
    }
    
    /**
     * 获取src目录下的文件
     * @throws IOException
     */
    public void read2() throws IOException{
        //ServletContext读取文件
        InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        //打印方式
        print(in);
    }
    
    /**
     * 传统方式读取文件
     * @throws IOException 
     */
    public void read1() throws IOException{
        InputStream in = new FileInputStream("");
        print(in);      
    }
    /**
     * 在控制台打印
     * @throws IOException
     */
    public void print(InputStream in) throws IOException{
        Properties pro = new Properties();
        pro.load(in);
        //
        String username = pro.getProperty("username");
        String password = pro.getProperty("password");
        String desc = pro.getProperty("desc");
        
        System.out.println("用户名:"+ username);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Servlet学习的大纲 servlet概念及相关接口简介 servet 执行过程 servlet映射路径 缺省s...
    奋斗的老王阅读 4,922评论 1 51
  • 这部分主要是与Java Web和Web Service相关的面试题。 96、阐述Servlet和CGI的区别? 答...
    杂货铺老板阅读 5,244评论 0 10
  • 本文包括: Servlet简介关于Servlet的一些类 Servlet生命周期 ServletConfig获得初...
    廖少少阅读 9,379评论 1 67
  • 一. Java基础部分.................................................
    wy_sure阅读 9,273评论 0 11
  • 自我对话的力量!激动得那个喜欢的样子…! 我一直都是在遇到事情时就开始打击自己,开始说,你怎么那么傻,那么笨,怎么...
    Wendy285385551阅读 3,398评论 0 0