Servlet应用开发——用户在线计数,只显示用户名是怎么回事?
package com.smalle.listener;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet{
    private static final long seriaVersionUID=1L;
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        this.doPost(request, response);
    }

    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        request.setCharacterEncoding("utf-8");
        String username=request.getParameter("username");

        //往session中添加属性,会触发HttpSessionAttributeListener中的attributeAdded方法
        if(username!=null&&!username.equals("")) {
            request.getSession().setAttribute("username",username); 
            }

        //从应用上下文中获取在线用户名列表
        List<String> online=(List<String>)getServletContext().getAttribute("online");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        out.println("");
        out.println("<title>用户列表</title>");
        out.println(" ");
        out.println("当前用户是: "+username);
        out.print("<hr><h3>在线用户列表</h3>");

        int size=online==null ? 0:online.size();
        for(int i=0;i<size;i++) {
            if(i>0) {
                out.println("<br>");
            }
            out.println(i+1+"."+online.get(i));
        }

        //注意:要对链接URL进行自动重写处理
        out.println("<hr/><a href=\""+response.encodeURL("logoutListener")+"\"> 注销</a>" );
        out.println("<hr/><a href='\'index.jsp\''>  主页</a>" );
        out.println(" ");
        out.println("");
        out.flush();
        out.close();
    }
}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐