07-ServletContext

07-ServletContext

概述

本文主要讲解servletContext,即servlet的上下文管理
一个web容器是由多个Servlet构成的,servletContext是在所有Servlet上层的一个东西,里面可以存储一些数据,初始化一些数据,请求转发以及读取资源文件,是所有Servlet都可以访问的,可以保证Servlet间通信

实践一-共享数据

新建一个maven-archetype-webapp的项目
父pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>JavaWeb-Study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>01-HelloServlet</module>
        <module>02-ServletContext</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
    </dependencies>
</project>

子pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.example</groupId>
        <artifactId>JavaWeb-Study</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>02-ServletContext</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>02-ServletContext Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

</project>

src/main/java/webapp/WEB_INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0"
         metadata-complete="true">
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>getc</servlet-name>
        <servlet-class>com.kuang.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>
</web-app>

GetServlet.java


package com.kuang.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 功能描述
 *
 * @since 2022-08-08
 */
public class GetServlet extends HelloServlet {
    private static final long serialVersionUID = -1598018725610471770L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = getServletContext();
        String username = (String) context.getAttribute("userName");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("名字" + username);

    }
}

HelloServlet.java


package com.kuang.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能描述
 *
 * @since 2022-08-08
 */
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = -6233245317352266402L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Hello");
        ServletContext context = getServletContext();
        context.setAttribute("userName", "秦疆");
    }
}

测试

  1. 启动Tomcat
  2. 请求http://localhost:8080/s2/hello 会往context里面写"userName"
  3. http://localhost:8080/s2/getc 会从context里面取"userName"并返回给页面

实践二-初始化数据

在程序启动的时候初始化一些数据,例子中初始化"username",供Servlet上下文使用

package com.kuang.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述
 *
 * @since 2022-08-09
 */
public class InitParamServlet extends HttpServlet {
    private static final long serialVersionUID = -5613337032764804137L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = getServletContext().getInitParameter("username");
        resp.getWriter().print(url);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

    <context-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </context-param>
    <servlet>
        <servlet-name>geti</servlet-name>
        <servlet-class>com.kuang.servlet.InitParamServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>geti</servlet-name>
        <url-pattern>/geti</url-pattern>
    </servlet-mapping>

实践三-请求转发

将/getd的请求直接转发到/geti


package com.kuang.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述
 *
 * @since 2022-08-09
 */
public class DispatcherServlet extends HttpServlet {
    private static final long serialVersionUID = 81025791841920598L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getServletContext().getRequestDispatcher("/geti").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

    <servlet-mapping>
        <servlet-name>getd</servlet-name>
        <url-pattern>/getd</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>getp</servlet-name>
        <servlet-class>com.kuang.servlet.PropertiesServlet</servlet-class>
    </servlet>

实践四-读取资源文件

ServletContext读取资源文件中内容


package com.kuang.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 功能描述
 *
 * @since 2022-08-09
 */
public class PropertiesServlet extends HttpServlet {
    private static final long serialVersionUID = -6445764844737255330L;

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

    <servlet>
        <servlet-name>getp</servlet-name>
        <servlet-class>com.kuang.servlet.PropertiesServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getp</servlet-name>
        <url-pattern>/getp</url-pattern>
    </servlet-mapping>

db.properties

username=root1
password=121212

总结

ServletContext这些功能后续都不会用,会被其他的技术取代
共享数据功能会被Session取代
初始化参数几乎不用
请求转发会用Request取代
读取资源文件会用反射方法
这篇博客只是一个引子,帮助理解和进阶

posted @ 2022-08-09 09:24  Oh,mydream!  阅读(16)  评论(0编辑  收藏  举报