天天看点

Servlet(二)

1.ServletConfig 详解

1.1、概念与用法

共有四个 API:

  • getInitParameter(String name): 获取指定参数名的初始化参数
  • getInitParameterNames(): 获取参数名组成的 Enumeration 对象.
  • getServletName
  • getServletContext

ServletConfig 封装了 Serlvet 的配置信息, 并且可以获取 ServletContext 对象

在Servlet的配置文件web.xml中,可以使用一个或多个标签为servlet配置一些初始化参数。

例如:

<!-- 配置和映射 Servlet -->
    <servlet>
        <!-- Servlet 注册的名字 -->
        <servlet-name>helloServlet</servlet-name>
        <!-- Servlet 的全类名 -->
        <servlet-class>com.atguigu.javaweb.HelloServlet</servlet-class>

        <!-- 配置 Serlvet 的初始化参数 -->
        <init-param>
            <!-- 参数名 -->
            <param-name>user</param-name>
            <!-- 参数值 -->
            <param-value>root</param-value>
        </init-param>

        <init-param>
            <param-name>password</param-name>
            <param-value>1230</param-value>
        </init-param>

        <!-- 可以指定 Servlet 被创建的时机 -->
        <load-on-startup>-1</load-on-startup>

    </servlet>      

获取初始化参数:

> getInitParameter(String name): 获取指定参数名的初始化参数
> getInitParameterNames(): 获取参数名组成的 Enumeration 对象. 

String user = servletConfig.getInitParameter("user");
System.out.println("user: " + user);

Enumeration<String> names = servletConfig.getInitParameterNames();
while(names.hasMoreElements()){
    String name = names.nextElement();
    String value = servletConfig.getInitParameter(name);
    System.out.println("^^" + name + ": " + value);
}      

1.2、通过ServletConfig获取Servlet的初始化参数

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

package com.atguigu.javaweb;

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

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Servlet implementation class HelloServlet
 */
public class HelloServlet implements Servlet

    @Override
    public void destroy() {
        System.out.println("destroy");
    }

    @Override
    public ServletConfig getServletConfig() {
        System.out.println("getServletConfig");
        return null;
    }

    @Override
    public String getServletInfo() {
        System.out.println("getServletInfo");
        return null;
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        String user = servletConfig.getInitParameter("user");
        System.out.println("user: " + user);

        Enumeration<String> names = servletConfig.getInitParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = servletConfig.getInitParameter(name);
            System.out.println("^^" + name + ": " + value);
        }
        System.out.println("init");
    }

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
        System.out.println("service");
    }

    public HelloServlet() {
        System.out.println("HelloServlet's constructor");
    }

}      
Servlet(二)

2. ServletContext对象

当前 WEB 应用的一个大管家,从中获取当前 WEB 应用的各方面信息

Servlet 引擎 为 每个 Web 应用都创建了一个对应的 ServletContext对象,ServletContext 包含在 ServletConfig对象中

一个web 应用的 所有 Servlet 公用一个 ServletContext对象,所以ServletContext 被称为 application 对象(Web 应用程序对象)

功能

  • 获取 web 应用程序的初始化参数
  • 获取日志
  • application 域范围的属性
  • 访问资源文件
  • 获取虚拟路径所映射的本地路径
  • WEB 应用之间的访问

2.1、多个Servlet通过ServletContext对象实现数据共享

public class ServletContextDemo1 extends HttpServlet

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        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      
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      

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

2.2、获取WEB应用的初始化参数

在web.xml文件中使用​

​<context-param>​

​标签配置WEB应用的初始化参数,如下所示:

<!-- 配置当前 WEB 应用的初始化参数 -->
    <context-param>
        <param-name>driver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>

    <context-param>
        <param-name>jdbcUrl</param-name>
        <param-value>jdbc:mysql://localhost:3306/test</param-value>
    </context-param>      

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

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);
    }

}      

2.3、用servletContext实现请求转发

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      
public class ServletContextDemo5 extends HttpServlet

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

}      
Servlet(二)

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

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

Servlet(二)

代码范例:使用servletContext读取资源文件,读取jdbc.properties

<!-- 配置当前 WEB 应用的初始化参数 -->
    <!-- 配置当前 WEB 应用的初始化参数 -->
    <context-param>
        <param-name>driver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>

    <context-param>
        <param-name>jdbcUrl</param-name>
        <param-value>jdbc:mysql://localhost:3306/test</param-value>
    </context-param>      
Servlet(二)
.getContextPath();
        System.out.println(contextPath);

        Properties pros = new Properties();

        try {
            ClassLoader classLoader = getClass().getClassLoader();
            InputStream is = classLoader.getResourceAsStream("jdbc.properties");
            System.out.println("1. " + is);
            pros.load(is);

            System.out.println(pros.getProperty("name"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        pros = new Properties();

        try {
            InputStream is2 = servletContext.getResourceAsStream("/WEB-INF/classes/jdbc.properties");
            System.out.println("2. " + is2);
            pros.load(is2);
            System.out.println(pros.getProperty("name"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String picPath = servletContext.getRealPath("/WEB-INF/lib");
        System.out.println(picPath);      

输出结果:

3.四、在客户端缓存Servlet的输出

public class ServletDemo5 extends HttpServlet

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String data = "abcddfwerwesfasfsadf";
        /**
         * 设置数据合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能
         * 这里是将数据的缓存时间设置为1天
         */
        response.setDateHeader("expires",System.currentTimeMillis() + 24 * 3600 * 1000);
        response.getOutputStream().write(data.getBytes());
    }

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

        this.doGet(request, response);
    }

}