Servlet监听器,统计网站在线人数实例

(1)创建一个监听器实现类

package com.web.listener;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnlineListener implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener{

 private ServletContext application = null;
 @Override
 public void sessionCreated(HttpSessionEvent arg0) {
  // TODO Auto-generated method stub
  
 }

 @Override
 //会话销毁时会回调的方法
 public void sessionDestroyed(HttpSessionEvent arg0) {
  // TODO Auto-generated method stub
  List<String> online = (List<String>)this.application.getAttribute("online");
  String username = (String) arg0.getSession().getAttribute("username");
  online.remove(username);
  this.application.setAttribute("online", online);
 }

 //往会话中添加属性时回调的方法
 @Override
 public void attributeAdded(HttpSessionBindingEvent event) {
  // TODO Auto-generated method stub
  List<String> online = (List<String>)this.application.getAttribute("online");
  
  if("username".equals(event.getName())){
   online.add((String) event.getValue());
  }
  
  this.application.setAttribute("online", online);
 }

 @Override
 public void attributeRemoved(HttpSessionBindingEvent event) {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void attributeReplaced(HttpSessionBindingEvent event) {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void contextDestroyed(ServletContextEvent arg0) {
  // TODO Auto-generated method stub
  
 }

 @Override
 //应用上下文初始化时调用
 public void contextInitialized(ServletContextEvent arg0) {
  // TODO Auto-generated method stub
  this.application = arg0.getServletContext();
  this.application.setAttribute("online", new LinkedList<String>());
 }
 
}


(2)在web.xml中注册监听器

<!-- 注册监听器 -->
  <listener>
   <listener-class>com.web.listener.OnlineListener</listener-class>
  </listener>


(3)处理用户登录的Servlet代码

package com.web.listener;

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

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

public class LoginServlet extends HttpServlet{
 public void doGet(HttpServletRequest req,HttpServletResponse resp)
   throws ServletException,IOException{
  doPost(req,resp);
 }
 
 public void doPost(HttpServletRequest req,HttpServletResponse resp)
   throws ServletException,IOException{
  req.setCharacterEncoding("utf-8");
  
  String username = (String) req.getParameter("username");
  //往session中添加属性
  //会触发HttpSessionAttributeListener中的attributeAdded方法

  if(username!=null && !username.equals("")){
   req.getSession().setAttribute("username", username);
  }
  
  //从应用上下文中获取在线用户名列表
  List<String> online = (List<String>)getServletContext().getAttribute("online");
  resp.setContentType("text/html;charset=utf-8");
  PrintWriter out = resp.getWriter();
  out.println("<HTML>");
  out.println("<HEAD><TITLE>用户列表</TITLE></HEAD>");
  out.println("<BODY>");
  out.println("当前用户是:"+username);
  out.println("<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));
   System.out.println(i+1+"."+online.get(i));
  }
  //注意:要对链接URL进行自动重写处理
  out.println("<hr/><a href=\""+ resp.encodeURL("logout")+"\">注销</a>");
  out.println("</BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
  
 }
}


(4)处理用户注销的Servlet代码

package com.web.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 LogoutServlet extends HttpServlet{
 public void doGet(HttpServletRequest req,HttpServletResponse resp)
   throws ServletException,IOException{
  doPost(req,resp);
 }
 
 public void doPost(HttpServletRequest req,HttpServletResponse resp)
   throws ServletException,IOException{
  req.setCharacterEncoding("utf-8");
  //销毁会话,会触发SessionListener中的sessionDestroyed方法
  req.getSession().invalidate();
  
  List<String>  online =(List<String>)getServletContext().getAttribute("online");
  
  resp.setContentType("text/html;charset=utf-8");
  PrintWriter out = resp.getWriter();
  out.println("<HTML>");
  out.println("<HEAD><TITLE>用户列表</TITLE></HEAD>");
  out.println("<BODY>");
  out.println("<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));
  }
  out.println("<hr/><a href=\"index.html\">主页</a>");
  out.println("</BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
 }
}

(5)在web.xml中配置以上两个Servlet

 <!-- LoginServlet与LogoutServlet -->
  <servlet>
    <servlet-name>login</servlet-name>
    <servlet-class>com.web.listener.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
 
  <servlet>
    <servlet-name>logout</servlet-name>
    <servlet-class>com.web.listener.LogoutServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>logout</servlet-name>
    <url-pattern>/logout</url-pattern>
  </servlet-mapping>


(6)创建一个index.html文件,用来供用户登录,代码如下:

<!DOCTYPE html>
<html>
  <head>
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   
    <title>login</title>
  </head>
 
  <body>
    <form action="login" method="post">
     用户名:<input type="text" name ="username" style="height: 32px; "/>
     <input type="submit" value="登陆"/><br/><br/>
    </form>
  </body>
</html>













  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Spring与Servlet整合的实例: 1. 首先,我们需要创建一个Servlet类,比如说HelloServlet: ```java @WebServlet("/hello") public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = "Hello, World!"; request.setAttribute("message", message); request.getRequestDispatcher("/WEB-INF/views/hello.jsp").forward(request, response); } } ``` 2. 接下来,我们需要创建一个Spring配置文件,比如说spring-config.xml,定义一个bean,该bean会在Servlet初始化时加载: ```xml <bean id="message" class="java.lang.String"> <constructor-arg value="Hello, Spring!"/> </bean> ``` 3. 接着,我们需要在web.xml中注册Servlet和Spring监听器: ```xml <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>com.example.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-config.xml</param-value> </context-param> ``` 4. 最后,我们需要在JSP视图中获取Spring bean的值: ```html <html> <head><title>Hello, World!</title></head> <body> <h1>${message}</h1> </body> </html> ``` 这样,当我们访问/hello时,Servlet会将消息传递给JSP,并在JSP中显示Spring bean的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值