08.《JavaEE 筆記》ServletContext 上下文(實現(xiàn)多人在線聊天室)

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ù)庫蕴潦、或者文件服務器等像啼。因為這些信息不是真正的全局信息。

作用:

  1. 是一個域?qū)ο?/li>
  2. 可以讀取全局配置參數(shù)
  3. 可以搜索當前工程目錄下面的資源文件
  4. 可以獲取當前工程名字(了解)

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>
  1. void setAttribute(String key,Object value) 往域?qū)ο罄锩嫣砑訑?shù)據(jù)僧诚,添加時以key-value形式添加
  2. Object getAttribute(String key) 根據(jù)指定的key讀取域?qū)ο罄锩娴臄?shù)據(jù)
  3. void removeAttribute(name); 根據(jù)指定的key從域?qū)ο罄锩鎰h除數(shù)據(jù)

2.3 讀取全局配置參數(shù)方法:

  1. String getInitParameter(String path) 返回上下文參數(shù)的值
  2. 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 可以搜索當前工程目錄下面的資源文件

  1. getServletContext().getRealPath(path) 根據(jù)相對路徑獲取服務器上資源的絕對路徑
  2. getServletContext().getResourceAsStream(path) 根據(jù)相對路徑獲取服務器上資源的輸入字節(jié)流
  3. 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)絡聊天室)

image.png

實現(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()%>&nbsp;<%=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钫选!怖侦!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末篡悟,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子匾寝,更是在濱河造成了極大的恐慌搬葬,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件艳悔,死亡現(xiàn)場離奇詭異急凰,居然都是意外死亡,警方通過查閱死者的電腦和手機猜年,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門抡锈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人乔外,你說我怎么就攤上這事床三。” “怎么了杨幼?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵撇簿,是天一觀的道長。 經(jīng)常有香客問我推汽,道長补疑,這世上最難降的妖魔是什么歧沪? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任歹撒,我火速辦了婚禮,結(jié)果婚禮上诊胞,老公的妹妹穿的比我還像新娘暖夭。我一直安慰自己,他們只是感情好撵孤,可當我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布迈着。 她就那樣靜靜地躺著,像睡著了一般邪码。 火紅的嫁衣襯著肌膚如雪裕菠。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天闭专,我揣著相機與錄音奴潘,去河邊找鬼旧烧。 笑死,一個胖子當著我的面吹牛画髓,可吹牛的內(nèi)容都是我干的掘剪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼奈虾,長吁一口氣:“原來是場噩夢啊……” “哼夺谁!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起肉微,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤匾鸥,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后碉纳,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體扫腺,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年村象,在試婚紗的時候發(fā)現(xiàn)自己被綠了笆环。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡厚者,死狀恐怖躁劣,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情库菲,我是刑警寧澤账忘,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站熙宇,受9級特大地震影響鳖擒,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜烫止,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一蒋荚、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧馆蠕,春花似錦期升、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至吼渡,卻和暖如春容为,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工坎背, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留竭缝,地道東北人。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓沼瘫,卻偏偏與公主長得像抬纸,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子耿戚,可洞房花燭夜當晚...
    茶點故事閱讀 44,914評論 2 355

推薦閱讀更多精彩內(nèi)容