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

    1.ServletConfig

    作用:

    当servlet执行初始化函数init()之后,可以利用ServletConfig获取存储在web.xml里的参数,这样就可以不用在servlet中硬编码一些参数,例如作者姓名,当在servlet中使用作者姓名这个参数的时候直接调用web.xml,如果需要修改参数值,只需修改web.xml,不用重新编译servlet。

    用法:

    1. 在web.xml中指定参数name和参数value
      <servlet>
          <servlet-name>login</servlet-name>
          <servlet-class>com.ycty.login_control.Login</servlet-class>
          <init-param>
              <param-name>author</param-name>
              <param-value>feipeng8848</param-value>
          </init-param>

      </servlet>

      ServletConfig是配置servlet,所以要放置到servlet的标签中。 

    2. 在servlet中
      out.println(  getServletConfig().getIntParameter("author")  );

               这里写图片描述

    2.ServletContext

    ServletConfig的确很方便,但是,如果想在jsp中也使用servlet的配置参数的话,是很麻烦的,首先在servlet中String a_author = getServletConfig().getIntParameter(“author”)获得参数,然后利用requst.setAttribute(“author”,a_author),把参数传递给jsp。

    能不能直接在jsp中调用配置参数呢?

    能,用ServletContext。

    (1).在web.xml中

      <web-app>
      <context-param>
        <param-name>author</param-name>
        <param-value>This is context-param,author is feipeng8848</param-value>
      </context-param>
      </web-app>

    这里需要注意一点,ServletConfig是针对servlet的配置,需要写进servlet标签内部,而ServletContext是针对整个web应用,所以他的上层标签是web-app。 

    (2)在jsp中

    out.println(getServletContext().getParameter(author));

    这里写图片描述

    ServletContext常用于配置数据库的URL、password、username等

    说明:

    1.getServletContext()和getServletConfig()是在 GenericServlet类中实现了的方法,由于httpServlet继承了该类,所以可以直接使用getServletContext()和getServletConfig()。

    getServletConfig()的另外一种写法:

    ServletConfig config = this.getServletConfig();
    out.println( config.getParameter("author"));

    getServletContext()的另外一种写法:

    ServletContext context = this.getServletContext();
    out.println( context.getParameter("author"));

     2.使用ServletContext存在线程安全问题。

  • 相关阅读:
    BZOJ2762: [JLOI2011]不等式组
    BZOJ1452: [JSOI2009]Count
    Codeforces Round #441 (Div. 2, by Moscow Team Olympiad)
    BZOJ1635: [Usaco2007 Jan]Tallest Cow 最高的牛
    BZOJ2730: [HNOI2012]矿场搭建
    Flask实现异步非阻塞请求功能
    在flask中使用websocket-实时消息推送
    Python数据库连接池DBUtils
    flask请求上下文
    scanf与getchar
  • 原文地址:https://www.cnblogs.com/feipeng8848/p/6698918.html
Copyright © 2011-2022 走看看