ServletContext对象与应用

web容器在启动的时候,会为每个web程序创建一个对应的ServletContext对象,代表当前Web应用;

 

ServletContext对象的作用:

 

 

1.共享数据

   可在各个Servlet之间分享其保存的数据

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context=this.getServletContext();
    context.setAttribute("username","zhang");//设置username的值为zhang
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context=this.getServletContext();
    PrintWriter writer= resp.getWriter();
    writer.println(context.getAttribute("username"));//从ServletContent获取username的值
}

 

 

 2.获取初始化参数

<!--设置初始化参数-->
  <context-param>
    <param-name>name</param-name>
    <param-value>zhang</param-value>
  </context-param>

 

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  ServletContext context=this.getServletContext();
  String s
= context.getInitParameter("name");
  PrintWriter writer
= resp.getWriter();
  writer.println(s);
}

 

 3.请求转发(转跳网页)

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context=this.getServletContext();
    RequestDispatcher request = context.getRequestDispatcher("/hello");
    request.forward(req,resp);
}

 

4.读取资源文件

<!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

Properties

  • 在resources目录下新建properties
  • 在java目录下新建properties

 发现:properties都会被打包到classes目录下

   @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties p=new Properties();
        p.load(is);
        String username=p.getProperty("username");
        String password=p.getProperty("password");
    }

 

posted @ 2021-10-31 11:08  是小张呀qaq  阅读(79)  评论(0)    收藏  举报