X

由于无法提供服务器的高昂费用,博客即将迁移到github pages...

点击右上的X可以临时关闭此框并阻止跳转^_^

现在带您过去 秒后跳转...

[作业]Servlet简易聊天室

    简单例子-Servlet聊天室,所用工具:NetBeans IDE(配备GlassFish)
    本次例子重在思路,页面未做任何美化。
    最后结果展示:http://demo.dshui.wang/tomcat/First_chat_room/
    首先,需要一个登陆页面。
    Login.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%
        Cookie[] cookies = request.getCookies();
        String uname = "";
        String upwd = "";
        if(cookies!=null){
            for(int i=0;i
    
    
        
            牛逼的登陆界面
            
        
        
            
    用户名:
    密码:
    记住信息

    新建一个用来处理登录信息的Servlet: Main.java 所有的处理都在DoPost()完成

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package User;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     *
     * @author Administrator
     */
    public class Main extends HttpServlet {
    
        /**
         * Processes requests for both HTTP
         * GET and
         * POST methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                /* TODO output your page here. You may use following sample code. */
            } finally {            
                out.close();
            }
        }
    
        // 
        /**
         * Handles the HTTP
         * GET method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    
        /**
         * Handles the HTTP
         * POST method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //processRequest(request, response);
            String username,password,remember;
            HttpSession session = request.getSession(true);
            username = (String) request.getParameter("username");
            password = (String) request.getParameter("password");
            remember = (String) request.getParameter("remember");
            System.out.println("remember:"+remember);
            System.out.println(username);
            System.out.println(password);
            if(username != null && username.equals("201321092028") && password.equals("123456"))
            {
                if(remember != null && remember.equals("true"))
                {
                    Cookie cookie1 = new Cookie("remname",username);
                    Cookie cookie2 = new Cookie("rempwd",password);
                    cookie1.setMaxAge(60*60*24*5);
                    cookie2.setMaxAge(60*60*24*5);
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                }
                session.setAttribute("UserName",username);
                session.setAttribute("IsLogin","true");
                response.sendRedirect("LoginSuccess.jsp");
            }else if(username != null && username.equals("201321092027") && password.equals("123456"))
            {
                if(remember.equals("true"))
                {
                    Cookie cookie1 = new Cookie("remname",username);
                    Cookie cookie2 = new Cookie("rempwd",password);
                    cookie1.setMaxAge(60*60*24*5);
                    cookie2.setMaxAge(60*60*24*5);
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                }
                session.setAttribute("UserName",username);
                session.setAttribute("IsLogin","true");
                response.sendRedirect("LoginSuccess.jsp");
            }
            else
            {
                session.setAttribute("IsLogin","false");
                response.sendRedirect("LoginFail.jsp");
            }
        }
    
        /**
         * Returns a short description of the servlet.
         *
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// 
    }
    
    

    如果登录失败,跳转到LoginFail.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    
    
        
            
            
            请告诉他,登录失败了
        
        
            嗨,登陆失败了哟,3秒后跳转到登录页重新登陆哟! 点击此处直接跳转
        
    
    

    登录成功,则跳转到FrameSet窗口框架 LoginSuccess.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%
      session = request.getSession(true);
      String username = "";
      if(session.getAttribute("UserName") != null)
      {
          username = session.getAttribute("UserName").toString();
      }
      if(username != null && !username.equals(""))
      {
          if(!session.getAttribute("IsLogin").equals("true"))
          {System.out.println(session.getAttribute("IsLogin").toString());
              response.sendRedirect("Login.jsp");
          }
      }else{
          response.sendRedirect("Login.jsp");
      }
     %>
    
    
        
            
            
        
    
    

    上面的Frame加载了两个页面,一个是用来展示Messagebox聊天记录的,一个是用户的输入框
    Messagebox.Java

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package User;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     *
     * @author Administrator
     */
    public class messagebox extends HttpServlet {
    
        /**
         * Processes requests for both HTTP GET and POST
         * methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            try {
                /* TODO output your page here. You may use following sample code. */
                HttpSession session = request.getSession(true);
                String username = "";
                if(session.getAttribute("UserName") != null)
                {
                    username = session.getAttribute("UserName").toString();
                }
                if(username != null && !username.equals(""))
                {
                    if(!session.getAttribute("IsLogin").equals("true"))
                    {System.out.println(session.getAttribute("IsLogin").toString());
                        response.sendRedirect("Login.jsp");
                        //request.getRequestDispatcher("/Login.html").forward(request, response);
                    }
                }else{
                    response.sendRedirect("Login.jsp");
                }
                String words = (String) getServletConfig().getServletContext().getAttribute("Words");
                String messages = "";
                if(request.getParameter("usermessages") != null)
                {
                    messages = request.getParameter("usermessages");
                }
                if (words == null) {
                    words = "系统提示:可以聊天\n";
                } else if(!messages.equals("")){
                    words = (String) getServletConfig().getServletContext().getAttribute("Words") + username + " 说:"+messages + "\n";
                }
                getServletConfig().getServletContext().setAttribute("Words", words);
                String temp = (String) getServletConfig().getServletContext().getAttribute("online");
                if(temp==null)temp="0";
                out.println("");
                out.println("");
                out.println("Servlet messagebox");
                out.println("");
                out.println("");
                out.println("");
                out.println("

    当前在线:"); out.println(temp); out.println("人

    "); out.println(""); out.println(""); out.println(""); } finally { out.close(); } } // /** * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// }

    用户填写框:userinput.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <% session = request.getSession(true);%>
    
    
        
            
            输入框
        
        
            
    退出登陆

    我们还需要一个退出登录的功能:Loginout.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <% 
        session = request.getSession(true);
        session.removeAttribute("UserName");
        session.removeAttribute("IsLogin");
    %>
    
    
        
            
            
            Logout
        
        
            

    成功退出!

    注意了,既然是聊天室的话,也要知道当前有多少人在线吧,这个用监听来实现:SessionListrner.java

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package Listener;
    
    import javax.servlet.annotation.WebListener;
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionBindingEvent;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    
    /**
     * Web application lifecycle listener.
     *
     * @author Anthony
     */
    @WebListener()
    public class SessionListenr implements HttpSessionListener, HttpSessionAttributeListener {
    
        @Override
        public void sessionCreated(HttpSessionEvent se) {
            
        }
    
        @Override
        public void sessionDestroyed(HttpSessionEvent se) {
            
        }
    
        @Override
        public void attributeAdded(HttpSessionBindingEvent event) {
            if(event.getName().equals("UserName"))
            {
                String current = (String) event.getSession().getServletContext().getAttribute("online");
                String info = (String) event.getSession().getServletContext().getAttribute("Words");
                if(info==null)info ="";
                if(current == null) current="0";
                int c=Integer.parseInt(current);
                c++;
                current = String.valueOf(c);
                event.getSession().getServletContext().setAttribute("online", current);
                event.getSession().getServletContext().setAttribute("Words", info+event.getValue()+" 加入聊天室\n");
            }
        }
    
        @Override
        public void attributeRemoved(HttpSessionBindingEvent event) {
            if(event.getName().equals("UserName"))
            {
                String current = (String) event.getSession().getServletContext().getAttribute("online");
                String info = (String) event.getSession().getServletContext().getAttribute("Words");
                if(info==null)info ="";
                if(current==null)current = "0";
                int c = Integer.parseInt(current);
                c--;
                current = String.valueOf(c);
                event.getSession().getServletContext().setAttribute("online", current);
                event.getSession().getServletContext().setAttribute("Words", info+event.getValue()+" 离开了聊天室\n");
            }
        }
    
        @Override
        public void attributeReplaced(HttpSessionBindingEvent event) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }
    

    附上NetBean项目工程:
    链接: http://pan.baidu.com/s/1qWL2xRm 密码: 22wa