DOC

3003.docjava

By Leroy Daniels,2014-10-12 14:19
8 views 0
3003.docjava

    由于程序的原因?本文件未被完整保存。 首页 ? 研究文集 ? JSP/Servlet/JSF

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

    wbcp2000 整理 (参与分(15893?专家分(140) 发表(2002-07-25 15:24 版本(1.0 阅读(5925

上下文环境是针对服务器端的数据共享?例如聊天室目录?聊天信息就存在上下文环境中

    会话?是针对客户端信息共享?如你登录了那个聊天室

具体代码显示如下??参考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("");

     out.println("Chat</span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;"> </span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;">Room</span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;"> </span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;">Administration");

     out.println("");

     out.println("

Chat room administration

");

     out.println(" 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("

There are no rooms

");

     } else {

     out.println("

Check the rooms you would like to remove," + "and press Update List.

");

     while(rooms.hasNext()) {

     String roomName = (String) rooms.next();

     ChatRoom room = (ChatRoom) roomList.get(roomName);

     out.println(" TYPE=CHECKBOX NAME=remove VALUE='" + room.getName() + "'>" + room.getName() + "
");

     }

     }

     }

     // Add fields for adding a room

     out.println("

Enter a new room and the description

");

     out.println("

");

     out.println("

R>");

     out.println("

");

     out.println("

");

     out.println("

Name: NAME=roomname SIZE=50>
Description: NAME=roomdescr COLS=40 ROWS=5>");

     out.println("

");

     // Add submit button

     out.println("

TYPE=SUBMIT VALUE='Update List'>");

     out.println("

HREF=\"" + listRoomsPath + "\">Chat Now");

     out.println("");

     out.println("");

     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("");

     out.println("Chat</span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;"> </span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;">rooms");

     out.println("");

     out.println("

Chat rooms

");

     out.println(" METHOD=POST ACTION=\"" + chatRoomPath + "\">");

     out.println("

href=\"" + chatAdminPath + "\">Create Rooms

");

     // Get the list of rooms

     HashMap roomList = (HashMap) getServletContext().getAttribute("roomList");

     if(roomList == null) {

     out.println("

There are no rooms available right now.

");

     } 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:

");

     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(" TYPE=RADIO NAME=roomName VALUE=\"" + roomName + "\"" +

     (isFirst ? " CHECKED" : "") + ">" + " HREF=\"" + listRoomsURL + "\">" +

     roomName + "
");

     isFirst = false;

     // Show description if requested

     if (expand != null && expand.equals(roomName)) {

     out.println("

");

     if(room.getDescription().length() == 0) {

     out.println("No description available.");

     } else {

     out.println(room.getDescription());

     }

     out.println("


");

     }

     }

     // Add a field for the profile name

     out.println("

Enter your name: ");

     out.println(" NAME=profileName VALUE='" + profileName + "' SIZE=30>");

     // Add submit button

     out.println("

TYPE=SUBMIT VALUE='Enter'>");

     out.println("");

     }

     out.println("");

     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 it's 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("");

     out.println("");

     out.println(" METHOD=\"POST\" ACTION=\"" + res.encodeURL(chatRoomPath) + "\" TARGET=\"_top\">");

     out.println("

Enter your message:

");

     out.println(" NAME=\"msg\" SIZE=\"30\">");

     // Add a Submit button

     out.println("

TYPE=SUBMIT VALUE='Send Message'>");

     // Add an Exit button

     out.println("");

     out.println(" ACTION=\"" + res.encodeURL(listRoomsPath) + "\" METHOD=\"GET\" TARGET=\"_top\">");

     out.println(" TYPE=SUBMIT VALUE=Exit>");

     out.println("");

     out.println("");

     }

     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("");

     out.println("Error");

     out.println("");

     out.println("

Error

");

     out.println(msg);

     out.println("");

     }

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

     PrintWriter out = res.getWriter();

     out.println("");

     out.println(""</span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;"> </span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;">+</span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;"> </span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;">room.getName()</span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;"> </span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;">+</span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;"> </span><span style="font-family:Microsoft YaHei;font-size:15.96px;color:#000000;">"");

     out.println(" ROWS='50%,50%' BORDER=0 FRAMEBORDER=NO>");

     out.println(" SRC=\"" + res.encodeURL(chatRoomPath) + "?list=true\" NAME=\"list\" SCROLLING=\"AUTO\">");

     out.println(" SRC=\"" + res.encodeURL(chatRoomPath) + "?list=false\" NAME=\"form\" SCROLLING=\"AUTO\">");

     out.println(">");

     out.println("");

Report this document

For any questions or suggestions please email
cust-service@docsford.com