1、ServletContext 概念
ServletContext官方叫servlet上下文。服务器会为每一个工程创建一个对象,这个对象就是ServletContext对象。这个对象全局唯一,而且工程内部的所有servlet都共享这个对象。所以叫全局应用程序共享对象。
Web应用程序是Servlet、JSP页面和内容的集合,被Eclipse自动部署在Tomcat服务器URL名称空间的特定目录(如/catalog)下。注意,有时候可能通过.war文件部署。
对于在其部署描述符中标记为distributed的Web应用程序,每个虚拟机中都有一个上下文实例,这个实例称为上下文对象。例如,当前的Tomcat中部署了WebProject01,WebProject02……WebProject07共7个Web应用程序,那么,在启动Tomcat时,将分别为每一个Web应用程序创建一个上下文对象。
在这种情况下,上下文不能用作共享全局信息的位置而使用外部资源,比如数据库、或者文件服务器等。因为这些信息不是真正的全局信息。
作用:
- 是一个域对象
- 可以读取全局配置参数
- 可以搜索当前工程目录下面的资源文件
- 可以获取当前工程名字(了解)
2. ServletContext接口
2.1 获取ServletContext对象
- ServletConfig接口中定义的getServletContext方法
- 由于自定义的Servlet类间接实现了ServletConfig接口,因此可以直接调用getServletContext方法返回ServletContext对象 JSP文件中使用上下文对象的方法
- JSP文件的内置对象application即上下文对象,可以调用ServletContext接口中的任意方法
Servlet中获取:(以下两种都可以)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取Servlet上下文引用 ServletContext context1 = this.getServletContext(); ServletContext context2 = request.getServletContext(); }jsp中获取:
<% ServletContext context1 = this.getServletContext(); ServletContext context2 = request.getServletContext(); %>2.2 域对象常用方法:
- void setAttribute(String key,Object value) 往域对象里面添加数据,添加时以key-value形式添加
- Object getAttribute(String key) 根据指定的key读取域对象里面的数据
- void removeAttribute(name); 根据指定的key从域对象里面删除数据
2.3 读取全局配置参数方法:
- String getInitParameter(String path) 返回上下文参数的值
- Enumeration<String> getInitParameterNames() 获取所有参数名称列表
代码案例:
(1)在web.xml中配置全局参数
<!-- 全局配置参数,因为不属于任何一个servlet,但是所有的servlet都可以通过servletContext读取 这个数据 --> <context-param> <param-name>userName</param-name> <param-value>86_god</param-value> </context-param> <context-param> <param-name>e-mail</param-name> <param-value>2584966199@qq.com</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>https://www.zhihu.com/people/he-lai-xin-huan</param-value> </context-param>(2)在Servlet中获取全局变量
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); String userName = context.getInitParameter("userName"); System.out.println(userName); //获取所有全局变量的参数名称 Enumeration<String> list = context.getInitParameterNames(); //遍历所有参数 while (list.hasMoreElements()) { String name = list.nextElement(); String value = getServletContext().getInitParameter(name); System.out.println(name + ":" + value ); } }2.4 可以搜索当前工程目录下面的资源文件
- getServletContext().getRealPath(path) 根据相对路径获取服务器上资源的绝对路径
- getServletContext().getResourceAsStream(path) 根据相对路径获取服务器上资源的输入字节流
- getServletContext().getContextPath() 获取项目名称
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //根据相对路径获取服务器上资源的绝对路径 System.out.println(getServletContext().getRealPath("web.xml")); //根据相对路径获取服务器上资源的输入字节流 System.out.println(getServletContext().getResourceAsStream("web.xml")); //获取项目名称 System.out.println(getServletContext().getContextPath()); }3. 代码案例(实现网络聊天室)![]()
image.png
实现一个网上在线多人聊天室,页面比较丑,主要写后端
直接上代码!!!
页面部分代码:
(1)index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <frameset cols="80%,*"> <frame name="index" src="chatFrame.jsp" scrolling="no" /> <frame name="onlineList" src="onlineList.jsp" scrolling="no" /> <noframes> <body> 对不起,您的浏览器不支持框架,请使用更好的浏览器。 </body> </noframes> </frameset> </html>(2)chatFrame.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>聊天室</title> </head> <frameset rows="80%,*"> <frame name="chattingRecords" src="chattingRecords.jsp" scrolling="no" /> <frame name="inputFrame" src="inputFrame.jsp" scrolling="no" /> <noframes> <body> 对不起,您的浏览器不支持框架,请使用更好的浏览器。 </body> </noframes> </frameset> </html>(3)chattingRecords.jsp
<%@page import="java.util.Date"%> <%@page import="java.text.SimpleDateFormat"%> <%@page import="com.company.project.po.Message"%> <%@page import="java.util.ArrayList"%> <%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% ArrayList<Message> messages = (ArrayList<Message>) getServletContext().getAttribute("messages"); ArrayList<String> userList = (ArrayList<String>) getServletContext().getAttribute("userList"); String userId = request.getSession().getId(); if (messages == null) { messages = new ArrayList(); } if(userList == null){ userList = new ArrayList(); } if(!userList.contains(userId)){ userList.add(userId); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String sendTime = df.format(new Date());// new Date()为获取当前系统时间 Message message = new Message(); message.setUserName("系统提示"); message.setContent("欢迎"+request.getSession().getId()+"加入"); message.setSendTime(sendTime); messages.add(message); } getServletContext().setAttribute("userList", userList); getServletContext().setAttribute("messages", messages); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>聊天记录</title> <script> function fresh() { location.reload(); } window.setInterval(function() { fresh(); }, 1000); </script> </head> <body> <% if (messages != null) for (Message message : messages) { %> <%=message.getSendTime()%> <%=message.getUserName()%>说:<%=message.getContent() %> <br> <% } %> </body> </html>(4)inputFrame.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path; %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>输入框</title> <script type="text/javascript"> function IsNull() { var mess = document.getElementById("inputText").value; var send = document.getElementById("sendForm"); console.log(mess); console.log(send); if(mess != null && mess != ""){ send.submit(); } } </script> </head> <body> <form action="<%=basePath %>/send-message" method="get" id="sendForm"> <textarea id="inputText" name ="inputText" style="width: 100%"> </textarea> <input type="button" value="发送" onclick="IsNull()"> </form> </body> </html>(5)onlineList.jsp
<%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% ArrayList<String> userList = (ArrayList<String>) getServletContext().getAttribute("userList"); if(userList == null){ userList = new ArrayList(); } %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>在线列表</title> <script> function fresh() { location.reload(); } window.setInterval(function() { fresh(); }, 1000); </script> </head> <body> <h2>在线用户列表(目前在线人数:<%=userList.size() %>)<h2> <% for(String user:userList){ %> <%=user %><br> <% } %> </body> </html>模型model代码:
Message.java
package com.company.project.po; public class Message { private String userName; private String sendTime; private String content; public String getUserName() { return userName; } public String getContent() { return content; } public void setUserName(String userName) { this.userName = userName; } public void setContent(String content) { this.content = content; } public String getSendTime() { return sendTime; } public void setSendTime(String sendTime) { this.sendTime = sendTime; } @Override public String toString() { return "Message [userName=" + userName + ", sendTime=" + sendTime + ", content=" + content + "]"; } }Servlet代码
SendMessage.java
package com.company.project.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.company.project.po.Message; @WebServlet("/send-message") public class SendMessage extends HttpServlet { private static final long serialVersionUID = 1L; public SendMessage() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置相应内容类型 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); HttpSession session = request.getSession(); String inputText = (String)request.getParameter("inputText"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String sendTime = df.format(new Date());// new Date()为获取当前系统时间 Message message = new Message(); message.setUserName(session.getId()); message.setContent(inputText); message.setSendTime(sendTime); ArrayList<Message> messages = (ArrayList<Message>)getServletContext().getAttribute("messages"); if(messages == null) { messages = new ArrayList<>(); } messages.add(message); getServletContext().setAttribute("messages", messages); response.sendRedirect("page/inputFrame.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }越努力,越幸运 我们亦是拾光者!!!
AI大模型学习福利
作为一名热心肠的互联网老兵,我决定把宝贵的AI知识分享给大家。 至于能学习到多少就看你的学习毅力和能力了 。我已将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。
一、全套AGI大模型学习路线
AI大模型时代的学习之旅:从基础到前沿,掌握人工智能的核心技能!
因篇幅有限,仅展示部分资料,需要点击文章最下方名片即可前往获取
二、640套AI大模型报告合集
这套包含640份报告的合集,涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。
因篇幅有限,仅展示部分资料,需要点击文章最下方名片即可前往获
三、AI大模型经典PDF籍
随着人工智能技术的飞速发展,AI大模型已经成为了当今科技领域的一大热点。这些大型预训练模型,如GPT-3、BERT、XLNet等,以其强大的语言理解和生成能力,正在改变我们对人工智能的认识。 那以下这些PDF籍就是非常不错的学习资源。
因篇幅有限,仅展示部分资料,需要点击文章最下方名片即可前往获
四、AI大模型商业化落地方案
因篇幅有限,仅展示部分资料,需要点击文章最下方名片即可前往获
作为普通人,入局大模型时代需要持续学习和实践,不断提高自己的技能和认知水平,同时也需要有责任感和伦理意识,为人工智能的健康发展贡献力量