javaweb-10:ServletContext对象
2021/9/29 9:10:50
本文主要是介绍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; /** * @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";
这篇关于javaweb-10:ServletContext对象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-04TiDB 资源管控的对撞测试以及最佳实践架构
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现