1、ServletContext 概念
ServletContext官方叫servlet上下文。服務器會為每一個工程創(chuàng)建一個對象,這個對象就是ServletContext對象造成。這個對象全局唯一,而且工程內(nèi)部的所有servlet都共享這個對象雄嚣。所以叫全局應用程序共享對象谜疤。
Web應用程序是Servlet、JSP頁面和內(nèi)容的集合现诀,被Eclipse自動部署在Tomcat服務器URL名稱空間的特定目錄(如/catalog)下夷磕。注意,有時候可能通過.war文件部署仔沿。
對于在其部署描述符中標記為distributed的Web應用程序坐桩,每個虛擬機中都有一個上下文實例,這個實例稱為上下文對象封锉。例如绵跷,當前的Tomcat中部署了WebProject01,WebProject02……WebProject07共7個Web應用程序成福,那么碾局,在啟動Tomcat時,將分別為每一個Web應用程序創(chuàng)建一個上下文對象奴艾。
在這種情況下净当,上下文不能用作共享全局信息的位置而使用外部資源,比如數(shù)據(jù)庫蕴潦、或者文件服務器等像啼。因為這些信息不是真正的全局信息。
作用:
- 是一個域?qū)ο?/li>
- 可以讀取全局配置參數(shù)
- 可以搜索當前工程目錄下面的資源文件
- 可以獲取當前工程名字(了解)
2. ServletContext接口
2.1 獲取ServletContext對象
- ServletConfig接口中定義的getServletContext方法
- 由于自定義的Servlet類間接實現(xiàn)了ServletConfig接口潭苞,因此可以直接調(diào)用getServletContext方法返回ServletContext對象 JSP文件中使用上下文對象的方法
- JSP文件的內(nèi)置對象application即上下文對象忽冻,可以調(diào)用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 域?qū)ο蟪S梅椒ǎ?/h3>
- void setAttribute(String key,Object value) 往域?qū)ο罄锩嫣砑訑?shù)據(jù)僧诚,添加時以key-value形式添加
- Object getAttribute(String key) 根據(jù)指定的key讀取域?qū)ο罄锩娴臄?shù)據(jù)
- void removeAttribute(name); 根據(jù)指定的key從域?qū)ο罄锩鎰h除數(shù)據(jù)
2.3 讀取全局配置參數(shù)方法:
- String getInitParameter(String path) 返回上下文參數(shù)的值
- Enumeration<String> getInitParameterNames() 獲取所有參數(shù)名稱列表
代碼案例:
(1)在web.xml中配置全局參數(shù)
<!-- 全局配置參數(shù),因為不屬于任何一個servlet蝗碎,但是所有的servlet都可以通過servletContext讀取
這個數(shù)據(jù) -->
<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);
//獲取所有全局變量的參數(shù)名稱
Enumeration<String> list = context.getInitParameterNames();
//遍歷所有參數(shù)
while (list.hasMoreElements()) {
String name = list.nextElement();
String value = getServletContext().getInitParameter(name);
System.out.println(name + ":" + value );
}
}
2.4 可以搜索當前工程目錄下面的資源文件
- getServletContext().getRealPath(path) 根據(jù)相對路徑獲取服務器上資源的絕對路徑
- getServletContext().getResourceAsStream(path) 根據(jù)相對路徑獲取服務器上資源的輸入字節(jié)流
- getServletContext().getContextPath() 獲取項目名稱
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//根據(jù)相對路徑獲取服務器上資源的絕對路徑
System.out.println(getServletContext().getRealPath("web.xml"));
//根據(jù)相對路徑獲取服務器上資源的輸入字節(jié)流
System.out.println(getServletContext().getResourceAsStream("web.xml"));
//獲取項目名稱
System.out.println(getServletContext().getContextPath());
}
3. 代碼案例(實現(xiàn)網(wǎng)絡聊天室)
實現(xiàn)一個網(wǎng)上在線多人聊天室湖笨,頁面比較丑,主要寫后端
直接上代碼Q芰狻8厦础!
頁面部分代碼:
(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()為獲取當前系統(tǒng)時間
Message message = new Message();
message.setUserName("系統(tǒng)提示");
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="發(fā)送" 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>在線用戶列表(目前在線人數(shù):<%=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 {
// 設置相應內(nèi)容類型
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()為獲取當前系統(tǒng)時間
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);
}
}
越努力放闺,越幸運 我們亦是拾光者K钫选!怖侦!