栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

javaweb-10:ServletContext对象

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

javaweb-10:ServletContext对象

6.5、ServletContext

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

1.共享数据

我在这个Servlet中保存的数据,可以在另一个Servlet中拿到

核心代码:

HelloServlet.java

package com.gongyi.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 HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //this.getInitParameter();//初始化参数
        //this.getServletConfig();//Servlet配置
        //this.getServletContext();//Servlet上下文
        ServletContext context = this.getServletContext();
        String userName = "工一";//数据
        context.setAttribute("userName",userName);//将一个数据保存在了Servlet中,名字为userName,值为userName


        System.out.println("Hello Servlet from servlet-02 module");
    }
}

GetServlet.java

package com.gongyi.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 userName = (String) context.getAttribute("userName");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("名字:"+userName);
    }

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

测试访问结果:

设置key

再访问getc

彩蛋

1.好习惯

学习一个新技术,新建一个父工程,然后分章节建立子模块

一般笔记类文件存在note.md中

2.一个tomcat同一个端口可以运行多个web服务【虚拟目录映射】

一般测试一个,打开一个,移除别的,会加快tomcat服务运行速度

3.新建maven工程时,如果项目名和artifactId不一致,项目名会出现在artifactId后面

4.idea快速打开maven配置

5.问题:

1)新建maven web子模块时,新建完成后,pom与父pom没关系了,还得手工修改

6.java新特性中支持用中文作为变量名

String 工一="gongyi";
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/281531.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号