zoukankan      html  css  js  c++  java
  • ServletConfig和ServletContext

    ServletConfig和ServletContext

    • Servlet初始化参数

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

    1 <servlet-name>ServletConfigDemo1</servlet-name>
    2     <servlet-class>....</servlet-class>
    3     ....
    4     <init-param>
    5         <param-name>charest</param-name>
    6         <param-value>UTF-8</param-value>
    7     </init-param>
    8     ....
    9 </servlet>
    • 通过ServletConfig获取Servlet的初始化参数

    要想获取Servlet的初始化参数,顾名思义,应该在初始化中得到 所以在init()中:

    1 public void init(ServletConfig config) throws ServletException {  
    2      this.config = config; 
    3 } 

    Servlet对象中含有ServletConfig对象,可以通过this.getServletConfig()获得(servletConfig)

    而获取初始化参数,只需要调用servletConfig.getInitParameter("charest")

    • 多个Servlet之间通过ServletContext共享数据

    由于ServletConfig维护了ServletContext的引用,可以用 this.getServletConfig().getServletContext()获取ServletContext对象(context)

    也直接this.getServletContext() 数据传输过程定义在doGet()中.

    servlet1传入数据: context.setAttribute()

    servlet2获取数据: context.getAttribute()

    当然也要在servlet1运行之后servlet1才能取得共享数据

    • 获取WEB应用的初始化参数
    1 <display-name></display-name>
    2 <context-param>
    3     <param-name>url</param-name>
    4     <param-value>jdbc:mysql://localhost:3306/test</param-value>
    5 </context-param>

    通过ServletContext获取整个web网站的初始化参数

    context.getInitParameter("url")

    • ServletContext请求转发

    RequestDispatcher rd = context.getRequestDispacher("/servlet/....");

    rd.forward(request,response);

    • ServletContext读取资源文件

    使用ServletContext的getResourceAsStream()方法获取输入流对象

    InputStream in = this.getServletContext().getResourceAsStream((String) uri);

    然后将数据写进输入流

    • 客户端缓存Servlet输出

    在客户端进行合理的数据缓存,可以避免浏览器频繁的向服务器发送多余请求.

    下面一段代码为将数据缓存到浏览器1天时间

    String data = "reserved"; response.setDateHeader("expires",System.currentTimeMillis()+24 * 3600 * 1000); response.getOutputStream().write(data.getBytes());

  • 相关阅读:
    !JS实战之随机像素图
    bgp选路原则【第二部】
    BGP基础【第三部】
    【★】KMP算法完整教程
    ★如何引导客户需求?几个经…
    html标签缺省(自带)样式大全
    Web颜色对照表大全
    PS各个工具的字母快捷键和英…
    色相、明度及饱和度
    用webgl打造自己的3D迷宫游戏
  • 原文地址:https://www.cnblogs.com/sunnysola/p/4936725.html
Copyright © 2011-2022 走看看