자바 웹 은 servlet 모니터 로 온라인 인원 을 표시 합 니 다.
1.모니터 만 들 기
package com.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
//             
public class MyServletSessionListener implements HttpSessionAttributeListener {
 @Override
 public void attributeAdded(HttpSessionBindingEvent event) {
  // TODO          
  ServletContext cx = event.getSession().getServletContext();//  session         ServletContext  
  Object objectlogincount = cx.getAttribute("logincount");//         logincount   
  String name = event.getName();
  if("is".equals(name)){//  session        is,          
   //System.out.println("       :"+event.getValue());
   if(objectlogincount==null){//  logincount  ,        
    cx.setAttribute("logincount", 1);
   }else{//         
    int a = Integer.parseInt(objectlogincount.toString());//         
    a++;
    cx.setAttribute("logincount", a);
   }
  }
  System.out.println("        :"+cx.getAttribute("logincount"));
 }
 @Override
 public void attributeRemoved(HttpSessionBindingEvent event) {
  // TODO          
  
 }
 @Override
 public void attributeReplaced(HttpSessionBindingEvent event) {
  // TODO          
  
 }
 
}2.웹 xml 에 모니터 설정
<listener>
  <listener-class>com.listener.MyServletSessionListener</listener-class>
</listener>3.LoginServ(servlet)로 테스트
package com.serv;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(urlPatterns={"/LoginServ"})
public class LoginServ extends HttpServlet {
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO          
  String name = req.getParameter("user");
  String pwd = req.getParameter("pwd");
  if(true){//   get    ,            
   HttpSession session = req.getSession();
   session.setAttribute("is", name);//setAttribute()          ,        。            ,    /   。
  }
 }
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO          
  doGet(req, resp);
 }
}캡 처 실행:브 라 우 저 에 주소 입력:
 my eclipse 콘 솔 에서 출력 합 니 다:
 이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.