Java-ServletContxt对象及使用

白衣少年
2022-11-04 / 0 评论 / 31 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月07日,已超过591天没有更新,若内容或图片失效,请留言反馈。

什么是ServletContext

Web容器在启动时,它会为每个Web应用程序都创建一个对应的ServletContext对象,这个对象代表当前Web应用。并且它被所有客户端共享(比如你在淘宝登陆了,那你的登陆信息会被带到很多页面,就是跳到其他页面发现也是登陆上的)。

ServletContext的应用

  1. 共享数据
    多个Servlet通过ServletContext对象实现数据共享

    • 添加属性:setAttribute(String name, Object obj);
    • 得到值:getAttribute(String name),这个方法返回Object
    • 删除属性:removeAttribute(String name)

测试:

首先创建一个放置数据的类

package com.cheng.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;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username = "万里顾一程";//数据
        context.setAttribute("username", "万里顾一程");//将一个数据保存在ServletContext中,username=万里顾一程
    }

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

注册Servlet

<servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>com.cheng.servlet.HelloServlet</servlet-class>
</servlet>
  <servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/hello</url-pattern>
</servlet-mapping>

然后创建一个接收数据的类

package com.cheng.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;

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String attribute = (String) context.getAttribute("username");//返回值,并类型强转为String
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("名字="+attribute);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

注册Servlet

<servlet>
  <servlet-name>hello1</servlet-name>
  <servlet-class>com.cheng.servlet.GetServlet</servlet-class>
</servlet>
  <servlet-mapping>
  <servlet-name>hello1</servlet-name>
  <url-pattern>/hello1</url-pattern>
</servlet-mapping>

启动Tomcat开始测试:

  1. 启动 HelloServlet 放置数据到ServletContext中
  2. 启动 GetServlet 从ServletContext中获得数据

名字=??.png

获取配置的初始化参数

web.xml 里配置的初始化参数可以用getInitParameter()方法获取

<context-param>
  <param-name>url</param-name>
  <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>

写一个实现类

package com.cheng.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;

public class ServletDemon03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

注册Servlet

<servlet>
  <servlet-name>hello3</servlet-name>
  <servlet-class>com.cheng.servlet.ServletDemon03</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>hello3</servlet-name>
  <url-pattern>/hello3</url-pattern>
</servlet-mapping>

运行Tomcat,查看结果

获取数据.png

请求转发

  1. RequestDispatcher 代表请求的派发者。
  2. Forward是指内部转发。当一个Servlet处理请求的时候,它可以决定自己不继续处理,而是转发给另一个Servlet处理。
    例如,我们已经编写了一个能处理 /hello3ServletDemon03 ,继续编写一个能处理 /hello4ServletDemon04ServletDemon04 在收到浏览器的请求后,它并不自己发送响应,而是把请求和响应都转发给路径为 /hello3ServletDemon03 ,后续请求的处理实际上是由 ServletDemon03 完成的。这种处理方式称为转发( Forward
    流程图如下所示:
    请求转发.png

编些一个实现请求转发的实现类

package com.cheng.servlet;

import javax.servlet.RequestDispatcher;
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;



/**
 * @User len
 * @Classname com.cheng.servlet.ServletDemon04
 * @Project javaweb-01-servlet
 * @Description TODO
 * @Author wpcheng
 * @Create 2021-02-06-18:36
 * @Version 1.0
 */
public class ServletDemon04 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        //RequestDispatcher 代表请求的派发者, 只能使用绝对路径
        RequestDispatcher dispatcher = context.getRequestDispatcher("/hello3");//请求的是地址为/hello3的资源,因此该请求是由路径为/hello3的servlet实现的
        dispatcher.forward(req,resp);//内部转发
    }

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

注册路径为/hello4的servlet

<servlet>
  <servlet-name>hello4</servlet-name>
  <servlet-class>com.cheng.servlet.ServletDemon04</servlet-class>
</servlet>
  <servlet-mapping>
  <servlet-name>hello4</servlet-name>
  <url-pattern>/hello4</url-pattern>
</servlet-mapping>

注册路径为/hello3的servlet

<servlet>
  <servlet-name>hello3</servlet-name>
  <servlet-class>com.cheng.servlet.ServletDemon03</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>hello3</servlet-name>
  <url-pattern>/hello3</url-pattern>
</servlet-mapping>

启动Tomcat查看转发结果

查看结果.png

==注:转发是在Web服务器内部完成的,对浏览器来说,它只发出了一个HTTP请求,浏览器的地址栏路径仍然是/hello4,浏览器并不知道该请求在Web服务器内部实际上做了一次转发。==

读取资源文件

类路径:即发布到Tomcat服务器后的ClassPath路径,在classes目录下
Properties可以用来保存属性集(类似Map, 以键值的形式保存数据,不同的是Properties都是String类型的)。这个类的优势是可以从流中获得属性集,或者把属性集报错到流中。
获取配置文件的信息

username=root
password=123456

实现类

package com.cheng.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;

public class ServletDemon05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // “ / ”代表了当前工程的根目录
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/jdbc.properties");
        Properties prop = new Properties();
        prop.load(is);//下载文件流
        String user = prop.getProperty("username");//通过键获取属性
        String pwd = prop.getProperty("password");
        resp.getWriter().println(user);
        resp.getWriter().println(pwd);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

注册servlet

<servlet>
    <servlet-name>hello5</servlet-name>
    <servlet-class>com.cheng.servlet.ServletDemon05</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>hello5</servlet-name>
    <url-pattern>/hello5</url-pattern>
</servlet-mapping>

实现

实现.png

3

打赏

评论 (0)

OwO
取消