关闭

ajax聊天室(JSP版)4

1883人阅读 评论(0) 收藏 举报

Servlet类真的没什么好说的。

先写个BaseServlet基类,以后的几个Servlet类就直接继承它,而不是HttpServlet。


package org.jvk.chatroom.servlet;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
public abstract class BaseServlet extends HttpServlet {
 
    public final static String USER = "user";
 
    private static final longserialVersionUID = 520131401655L;
 
    protected Log log = LogFactory.getLog(this.getClass());
 
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       execute(request, response);
    }
 
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       execute(request, response);
    }
 
    /**
     *由子类实现,处理GETPOST请求
     *
     *@paramrequest
     *@paramresponse
     *@throwsServletException
     *@throwsIOException
     */
    publicab stract void execute(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException;
 
    protected final String getValue(HttpServletRequest request, String param) {
       String str = request.getParameter(param);
       if (str == null)
           return"";
       return str;
    }
 
    private static byte[] lock = new byte[0];
 
    protected final void setNoCache(HttpServletRequest request,
           HttpServletResponse response) {
       synchronized (lock) {
           if (request.getProtocol().compareTo("HTTP/1.0") == 0)
              response.setHeader("Prama", "no-cache");
           else if (request.getProtocol().compareTo("HTTP/1.1") == 0)
              response.setHeader("Cache-Control", "no-cache");
           response.setDateHeader("Expires", 0);
       }
    }
}

 
package org.jvk.chatroom.servlet;
 
import java.io.IOException;
import java.util.Collection;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.jvk.chatroom.bean.Room;
import org.jvk.chatroom.bean.User;
import org.jvk.chatroom.service.ChatroomManager;
 
public class Login extends BaseServlet {
 
    private static final longserialVersionUID = 5201314016000L;
 
    // 设置session生命周期为1分钟
    private static intsessionTimeOut = 60 * 1;
 
    private static final String ROOM_PAGE = "pages/chatroom.jsp";
 
    private static final String LOGIN_PAGE = "pages/login.jsp";
 
    private staticf inal String this_PAGE = "login";
 
    private static final String ERROR_PAGE = "pages/error.jsp";
 
    public void execute(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       String userName = getValue(request, "userName");
       String roomName = getValue(request, "roomName");
       if (userName.length() < 1 || roomName.length() < 1) {
           Collection<Room> rooms = ChatroomManager.newInstance().getRooms()
                  .values();
           request.setAttribute("rooms", rooms);
           request.getRequestDispatcher(LOGIN_PAGE).forward(request, response);
       } else if (ChatroomManager.newInstance().exists(roomName, userName)) {
           log.info("该用户已存在,请使用其他字符");
           request.setAttribute("returnURL", this_PAGE);
           request.setAttribute("errorMessage", "该用户已存在,请使用其他字符");
           request.getRequestDispatcher(ERROR_PAGE).forward(request, response);
       } else {
           HttpSession session = request.getSession(true);
           User user = new User(userName, ChatroomManager.newInstance()
                  .getRoom(roomName));
           session.setMaxInactiveInterval(sessionTimeOut);
           user.setLastGetMessage(510);
           user.setLastGetUserList(520);
           session.setAttribute(USER, user);
           session.setAttribute("room", ChatroomManager.newInstance().getRoom(
                  roomName));
           response.sendRedirect(ROOM_PAGE);
       }
    }
 
}

package org.jvk.chatroom.servlet;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.jvk.chatroom.bean.Message;
import org.jvk.chatroom.bean.User;
import org.jvk.chatroom.service.ChatroomManager;
 
 
public class SendMessage extends BaseServlet {
    private static final longserialVersionUID = 520131401655L;
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException,
           IOException {
       HttpSession session = request.getSession(false);
       if (session == null){
           response.getWriter().write("");
           return;
       }
       synchronized (session) {
           User user = (User) session.getAttribute(USER);
           Message message = new Message();
           String to = request.getParameter("to");
           if ("all".equals(to))
              to = null;
           String content = request.getParameter("content");
           message.setContent(content);
           message.setFrom(user.getName());
           message.setTo(to);
           message.setDate(System.currentTimeMillis());
           ChatroomManager.newInstance().addMessageToRoom(message, user.getRoom());
           //假装响应下
           response.getWriter().write("");
       }
    }
}
 

 
package org.jvk.chatroom.servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.jvk.chatroom.bean.Message;
import org.jvk.chatroom.bean.User;
import org.jvk.chatroom.service.ChatroomManager;
 
public class GetMessage extends BaseServlet {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException,
           IOException {
       HttpSession session = request.getSession(false);
       if (session == null)
           return;
       synchronized (session) {
           User user = (User) session.getAttribute(USER);
           List<Message> messages = ChatroomManager.newInstance().getMessagesFromRoom(user);
           StringBuffer xml = new StringBuffer(4096);
           xml.append("<messages>");
           for (Message message : messages) {
              xml.append("<message>");
              xml.append("<from>" + message.getFrom() + "</from>");
              xml.append("<date>" + new SimpleDateFormat().format(new Date(message.getDate())) + "</date>");
              xml.append("<content>" + message.getContent() + "</content>");
              xml.append("</message>");
           }
           xml.append("</messages>");
           System.out.println("xml="+xml);
           setNoCache(request, response);
           response.setContentType("text/xml; charset=UTF-8");
           PrintWriter out = response.getWriter();
           out.print(xml);
           out.flush();
       }
 
    }
 
}
 

 
package org.jvk.chatroom.servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.jvk.chatroom.bean.User;
import org.jvk.chatroom.service.ChatroomManager;
 
public class GetUserList extends BaseServlet {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       HttpSession session = request.getSession(false);
       if (session == null)
           return;
       synchronized (session) {
           User user = (User) session.getAttribute(USER);
           ChatroomManager dao = ChatroomManager.newInstance();
           List<User> list = dao.getUsersFromRoom(user);
          
           StringBuffer buffer = new StringBuffer(1024);
           buffer.append("<users>");
           for (User tempUser : list) {
              buffer.append("<user name=/"" + tempUser.getName() + "/"/>");
           }
           buffer.append("</users>");
           log.info("users=/n" + buffer);
           setNoCache(request,response);
           response.setContentType("text/xml; charset=UTF-8");
           PrintWriter out = response.getWriter();
           out.print(buffer);
           out.flush();
       }
 
    }
}

没有了,就这几个类。 
 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:134317次
    • 积分:2151
    • 等级:
    • 排名:第18256名
    • 原创:70篇
    • 转载:6篇
    • 译文:1篇
    • 评论:35条
    最新评论
    好友
    明星Blog