使用監聽器監聽用戶訪問頁面的次數


/**

創建SesstionListener類實現  HttpSessionListener  接口   寫如下代碼

*/

public void sessionCreated(HttpSessionEvent arg0) {
  ServletContext application =arg0.getSession().getServletContext();
  int count=1;
  if(application.getAttribute("count")!=null){
  count=(Integer)application.getAttribute("count");           //獲取application的值          

  count++;                                                                           這一段就是判斷application的值  如果不為空就獲取count並且+1  在存到application中
  application.setAttribute("count", count);
}
  application.setAttribute("count", count);
}

@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
  ServletContext application =arg0.getSession().getServletContext();
  Integer count=(Integer)application.getAttribute("count");
  count--;
  application.setAttribute("count", count);
}

/**

配置Eeb.XML文件   如下

*/

<listener>
  <listener-class>cn.yct.Listeren.SessionAttListener</listener-class>     //包名.類名
</listener>
<listener>
  <listener-class>cn.yct.Listeren.SesstionListener</listener-class>         //包名.類名

</listener>

 

/**

創建  CountServlet   繼承  HttpServlet  實現她的方法   寫如下代碼

*/

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

  response.setContentType("text/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  HttpSession session=request.getSession();        //創建Sessions對象
  String name=request.getParameter("name");      //獲取登錄的用戶名
  if(name!=null){
    request.getRequestDispatcher("/Login/success.jsp").forward(request, response);     //跳轉到登錄成功的頁面
    session.setMaxInactiveInterval(10);       //設置session的失效
}

/**

主頁面   登錄的頁面

*/

<form action="CountServlet">    
   <table>
    <tr>
      <td>用戶名:</td>
      <td><input type="text" name="name"></td>
    </tr>
    <tr>
      <td><input type="submit" value="提交"></td>
    </tr>
  </table>
</form>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM