10 ServletContext 对象

ServletContext 对象:一个模板中只定义一个,可以使得不同的页面之间进行数据交流

执行三部曲:
1.SetServletContext.java
2.GetServletContext.java
3.web.xml


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 SetServletContext extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();   // 获得ServletContext对象
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        String userName="詹";
        context.setAttribute("userName",userName);    // 设置,添加
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
package com.zhan.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 GetServletContext extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        String userName=(String) context.getAttribute("userName");   // 强制转换
        resp.getWriter().println("名字:"+userName);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>set</servlet-name>
    <servlet-class>com.zhan.servlet.SetServletContext</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>set</servlet-name>
    <url-pattern>/set</url-pattern>
  </servlet-mapping>
<!--  -->
  <servlet>
    <servlet-name>get</servlet-name>
    <servlet-class>com.zhan.servlet.GetServletContext</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>get</servlet-name>
    <url-pattern>/get</url-pattern>
  </servlet-mapping>



</web-app>
posted @ 2023-10-05 10:16  被占用的小海海  阅读(4)  评论(0编辑  收藏  举报