爱心技术专栏专题

利用Servlet的上下文环境和会话来实现聊天的程序

摘录:java 来源:java 加入时间:2006年08月11日
摘要:
利用Servlet的上下文环境和会话来实现聊天的程序

上下文环境是针对服务器端的数据共享,例如聊天室目录,聊天信息就存在上下文环境中
会话,是针对客户端信息共享,如你登录了那个聊天室

具体代码显示如下,(参考J2EE编程指南)


/////////////////////////////////////////////////////////////
////////////////////…

转载:转载请保留本信息,本文来自
http://www.51dibs.com
/html/2006/article/info11/a_ef5862471e49f6a5.htm

利用Servlet的上下文环境和会话来实现聊天的程序

站点:爱心种子小博士 关键字:利用Servlet的上下文环境和会话来实

   
利用Servlet的上下文环境和会话来实现聊天的程序
上下文环境是针对服务器端的数据共享,例如聊天室目录,聊天信息就存在上下文环境中
会话,是针对客户端信息共享,如你登录了那个聊天室

具体代码显示如下,(参考J2EE编程指南)


/////////////////////////////////////////////////////////////
//////////////////////////////////////////

public class ChatEntry {
  private String profileName;
  private String message;

  public ChatEntry(String profileName, String message) {
    this.profileName = profileName;
    this.message = message;
  }

  public String getProfileName() {
    return profileName;
  }

  public void setProfileName(String profileName) {
    this.profileName = profileName;
  }

  public String getMessage() {
    return message;
  }
}




/////////////////////////////////////////
///////////////

import java.util.Stack;

public class ChatRoom extends Stack {
  private String name;
  private String description;
    
  public ChatRoom(String name, String description, int maxEntries) {
    this.name = name;
    this.description = description;

    this.setSize(maxEntries);
  }
    
  public void addChatEntry(ChatEntry entry) {
    push(entry);
  }

  public String getDescription() {
    return description;
  }
    
  public String getName() {
    return name;
  }
}


////////////////////////////////////////////
////////////////////////////////

// Import servlet packages
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Import java packages
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;

public class ChatAdminServlet extends HttpServlet {

  String chatRoomPath;
  String listRoomsPath;
  String chatAdminPath;
    
  public void init() {
    ServletContext context = getServletContext();
    chatRoomPath = context.getInitParameter("CHATROOM_PATH");
    listRoomsPath = context.getInitParameter("LISTROOMS_PATH");
    chatAdminPath = context.getInitParameter("ADMIN_PATH");
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res) 
        throws IOException, ServletException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Chat Room Administration</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<H1>Chat room administration</H1>");
    out.println("<FORM METHOD=\"POST\" ACTION=\"" + res.encodeURL(chatAdminPath) + "\">");
        
    // Check for existing chat rooms
    HashMap roomList = (HashMap) getServletContext().getAttribute("roomList");
    if(roomList != null) {
      Iterator rooms = roomList.keySet().iterator();
            
      if(!rooms.hasNext()) {
        out.println("<p>There are no rooms</p>");
      } else {
        out.println("<p>Check the rooms you would like to remove," + "and press Update List.</p>");

        while(rooms.hasNext()) {
          String roomName = (String) rooms.next();
          ChatRoom room = (ChatRoom) roomList.get(roomName);
          out.println("<INPUT TYPE=CHECKBOX NAME=remove VALUE=" + room.getName() + ">" + room.getName() + "<BR>");
        }
      }
    }

    // Add fields for adding a room
    out.println("<P>Enter a new room and the description<P>");
    out.println("<TABLE>");
    out.println("<TR><TD>Name:</TD><TD><INPUT NAME=roomname SIZE=50></TD></TR>");
    out.println("<TR><TD>Description:</TD>");
    out.println("<TD><TEXTAREA NAME=roomdescr COLS=40 ROWS=5>");
    out.println("</TEXTAREA></TD></TR>");
    out.println("</TABLE>");
        
    // Add submit button
    out.println("<P><INPUT TYPE=SUBMIT VALUE=Update List>");
    out.println("<p><A HREF=\"" + listRoomsPath + "\">Chat Now</a>");
    out.println("</FORM>");
    out.println("</BODY></HTML>");
        
    out.close();
  }

  /**
   * Processes POST request for adding new rooms, or deleting existing rooms.
   */
  public void doPost(HttpServletRequest req, HttpServletResponse res) 
              throws IOException, ServletException {
    HashMap roomList = null;
    // Check for existing chat rooms
    synchronized(getServletContext()) {
      roomList = (HashMap) getServletContext().getAttribute("roomList");
      if(roomList == null) {
        roomList = new HashMap();
        getServletContext().setAttribute("roomList", roomList);
      }
    }
        
    // Update the room list
    String[] removeList = req.getParameterValues("remove");
    synchronized(roomList) {
      if(removeList != null) {
        for(int i = 0; i < removeList.length; i++) {
          roomList.remove(removeList[i]);
        }
      }
    }
        
    String roomName = req.getParameter("roomname");
    String roomDescr = req.getParameter("roomdescr");
        
    if(roomName != null && roomName.length() > 0) {
      synchronized(roomList) {
        roomList.put(roomName, new ChatRoom(roomName, roomDescr, 4));
      }
    }
    doGet(req, res);
  }
}


/////////////////////////////////////////
///////////////////////////////////

// Import servlet packages
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Import java packages
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.net.URLEncoder;

public class ListRoomsServlet extends HttpServlet {

  String chatAdminPath;
  String listRoomsPath;
  String chatRoomPath;
    
  public void init() {
    ServletContext context = getServletContext();
    chatAdminPath = context.getInitParameter("ADMIN_PATH");
    listRoomsPath = context.getInitParameter("LISTROOMS_PATH");
    chatRoomPath = context.getInitParameter("CHATROOM_PATH");
  }
    
  public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
        
    String expand = request.getParameter("expand");
    HttpSession session = request.getSession();
    String profileName = (String) session.getAttribute("profileName");
    if(profileName == null) {
      profileName = "";
    }

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Chat rooms</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<H1>Chat rooms</H1>");
    out.println("<FORM METHOD=POST ACTION=\"" + chatRoomPath + "\">");
    out.println("<p><a href=\"" + chatAdminPath + "\">Create Rooms</a></p>");
        
    // Get the list of rooms
    HashMap roomList = (HashMap) getServletContext().getAttribute("roomList");
    if(roomList == null) {
      out.println("<p>There are no rooms available right now.</p>");
    } else {
      // Add radio boxes for selecting a room
      out.println("Select the room you like to enter " + "or click on a name to see the description:<P>");
            
      Iterator rooms = roomList.keySet().iterator();
      boolean isFirst = true;
      while(rooms.hasNext()) {
        String roomName = (String) rooms.next();
        ChatRoom room = (ChatRoom) roomList.get(roomName);
        String listRoomsURL = listRoomsPath + "/?expand=" + URLEncoder.encode(roomName);
        listRoomsURL = response.encodeURL(listRoomsURL);
                
        out.println("<INPUT TYPE=RADIO NAME=roomName VALUE=\"" + roomName + "\"" +
                            (isFirst ? " CHECKED" : "") + ">" + "<A HREF=\"" + listRoomsURL + "\">" +
                            roomName + "</A><BR>");
        isFirst = false;
                  
          // Show description if requested
          if (expand != null && expand.equals(roomName)) {
            out.println("<BLOCKQUOTE>");
          if(room.getDescription().length() == 0) {
            out.println("No description available.");
          } else {
            out.println(room.getDescription());
          }
          out.println("</BLOCKQUOTE><BR>");
        }
      }

      // Add a field for the profile name
      out.println("<P>Enter your name: ");
      out.println("<INPUT NAME=profileName VALUE=" + profileName + " SIZE=30>");
            
      // Add submit button
      out.println("<P><INPUT TYPE=SUBMIT VALUE=Enter>");
      out.println("</FORM>");
    }
    out.println("</BODY></HTML>");
    out.close();
  }
}


/////////////////////////////////////////////////////
///////////////////////////////////////


// Import servlet packages
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Import java packages
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;

public class ChatRoomServlet extends HttpServlet {
  String chatRoomPath;
  String listRoomsPath;

  public void init() {
    ServletContext context = getServletContext();
    chatRoomPath = context.getInitParameter("CHATROOM_PATH");
    listRoomsPath = context.getInitParameter("LISTROOMS_PATH");
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res) 
       throws IOException, ServletException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    ChatRoom room = getRoom(req, res);
    if(room == null) {
      return;
    }

    // Check if its a request for a message list or a form
    String listPar = req.getParameter("list");
    if(listPar != null && listPar.equals("true")) {    
      writeMessages(out, room, getProfileName(req));
    } else {
      out.println("<HTML>");
      out.println("<BODY>");
      out.println("<FORM METHOD=\"POST\" ACTION=\"" + res.encodeURL(chatRoomPath) + "\" TARGET=\"_top\">");

      out.println("<p>Enter your message:</p>");
      out.println("<INPUT NAME=\"msg\" SIZE=\"30\">");

      // Add a Submit button
      out.println("<P><INPUT TYPE=SUBMIT VALUE=Send Message>");

      // Add an Exit button
      out.println("</FORM>");
      out.println("<FORM ACTION=\"" + res.encodeURL(listRoomsPath) + "\" METHOD=\"GET\" TARGET=\"_top\">");
      out.println("<INPUT TYPE=SUBMIT VALUE=Exit>");
      out.println("</FORM>");

      out.println("</BODY></HTML>");
    }
    out.close();
  }

  public void doPost(HttpServletRequest req, HttpServletResponse res) 
        throws IOException, ServletException {
    res.setContentType("text/html");

    ChatRoom room = getRoom(req, res);
    if (room == null) {
            return;
    }

    String profileName = getProfileName(req);

    // Save message if any
    String msg = req.getParameter("msg");
    if (msg != null && msg.length() != 0) {
      room.addChatEntry(new ChatEntry(profileName, msg));
    }
    writeFrame(res, room);
  }

  private String getProfileName(HttpServletRequest req) {
    HttpSession session = req.getSession(true);
    String profileName = (String) session.getAttribute("profileName");
    if (profileName == null) {
      // Entered a room for the first time?
      profileName = req.getParameter("profileName");
      if(profileName == null || profileName.length() == 0) {
        profileName = "Anonymous";
      }
      session.setAttribute("profileName", profileName);
    } else {
      // Entered a new room with a new name?
      String newName = req.getParameter("profileName");
      if (newName != null && newName.length() > 0 && !newName.equals(profileName)) {
        profileName = newName;
        session.setAttribute("profileName", profileName);
      }
    }
    return profileName;
  }

  private ChatRoom getRoom(HttpServletRequest req, HttpServletResponse res) 
                   throws IOException {

    HttpSession session = req.getSession(true);
    PrintWriter out = res.getWriter();

    String roomName = (String) session.getAttribute("roomName");
    if(roomName == null) {
      // Just entered?
      roomName = req.getParameter("roomName");
      if(roomName == null || roomName.length() == 0) {
        writeError(out, "Room not specified");
        return null;
      }
      session.setAttribute("roomName", roomName);
    } else {
      // Entered a new room?
      String newRoom = req.getParameter("roomName");
      if (newRoom != null && newRoom.length() > 0 && !newRoom.equals(roomName)) {
        roomName = newRoom;
        session.setAttribute("roomName", roomName);
      }
    }

    HashMap roomList = (HashMap) getServletContext().getAttribute("roomList");
    ChatRoom room = (ChatRoom) roomList.get(roomName);
    if(room == null) {
      writeError(out, "Room " + roomName + " not found");
      return null;
    }
    return room;
  }

  private void writeError(PrintWriter out, String msg) {

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Error</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<H1>Error</H1>");
    out.println(msg);
    out.println("</BODY></HTML>");
  }

  private void writeFrame(HttpServletResponse res, ChatRoom room) throws IOException {

    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println("<HEAD><TITLE>" + room.getName() + "</TITLE></HEAD>");
    out.println("<FRAMESET ROWS=50%,50% BORDER=0 FRAMEBORDER=NO>");
    out.println("<FRAME SRC=\"" + res.encodeURL(chatRoomPath) + "?list=true\" NAME=\"list\" SCROLLING=\"AUTO\">");
    out.println("<FRAME SRC=\"" + res.encodeURL(chatRoomPath) + "?list=false\" NAME=\"form\" SCROLLING=\"AUTO\">");
    out.println("<NOFRAMES>");
    out.println("<BODY>");
    out.println("Viewing this page requires a browser capable of displaying frames.");
    out.println("</BODY>");
    out.println("</NOFRAMES>");
    out.println("</FRAMESET>");
    out.println("</HTML>");
    out.close();
  }

  private void writeMessages(PrintWriter out, ChatRoom room, String profileName) {

    StringBuffer sb = new StringBuffer();

    out.println("<HTML>");
    out.println("<HEAD><META http-equiv=\"refresh\" content=\"5\"></HEAD>");
    out.println("<BODY>");
    out.println("<B>Room: " + room.getName() + "</B><BR>" + "<B>Identity: " + profileName + "</B><BR>");

    // List all messages in the room
    if (room.size() == 0) {
      out.println("<FONT COLOR=RED>There are no messages in this room yet</FONT>");
    } else {
      Iterator entries = room.iterator();
      while(entries.hasNext()) {
        ChatEntry entry = (ChatEntry) entries.next();
        if(entry == null) continue;
    String entryName = entry.getProfileName();
        if(entryName.equals(profileName)) {
          out.print("<FONT COLOR=BLUE>");
        }
        out.println(entryName + " : " + entry.getMessage() + "<BR>");
        if(entryName.equals(profileName)) {
          out.print("</FONT>");
        }
      }
    }
    out.println("</BODY></HTML>");
  }
}


////////////////////////////////////
////////////
web.xml配置文件如下
<?xml version="1.0" ?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 1.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
  <context-param>
    <param-name>ADMIN_PATH</param-name>
    <param-value>chatAdmin</param-value>
  </context-param>

  <context-param>
    <param-name>LISTROOMS_PATH</param-name>
    <param-value>listRooms</param-value>
  </context-param>

  <context-param>
    <param-name>CHATROOM_PATH</param-name>
    <param-value>chatRoom</param-value>
  </context-param>

  <servlet>
    <servlet-name>chatAdmin</servlet-name>
    <servlet-class>ChatAdminServlet</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>chatRoom</servlet-name>
    <servlet-class>ChatRoomServlet</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>listRooms</servlet-name>
    <servlet-class>ListRoomsServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>chatAdmin</servlet-name>
    <url-pattern>/chatAdmin/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>chatRoom</servlet-name>
    <url-pattern>/chatRoom/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>listRooms</servlet-name>
    <url-pattern>/listRooms/*</url-pattern>
  </servlet-mapping>
                
                
                
</web-app>


在Weblogic下配置成功通过



客户服务中心信箱:[email protected] [email protected] 网站地图

声明

合作伙伴: