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;
/**
* @Classname HelloServlet
* @Description TODO
* @Date 2021/9/29 8:31
* @Created by Administrator
*/
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;
/**
* @Classname GetServlet
* @Description TODO
* @Date 2021/9/29 8:49
* @Created by Administrator
*/
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";