JavaWeb中的application统计在线人数案例

来源:互联网 发布:qq定位软件 编辑:程序博客网 时间:2024/05/22 17:03
1、后台部分(a/登录,建一个LoginServlet类继承HttpServlet父类)
package com.iotek.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class LoginServlet extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {ServletContext application = req.getServletContext();Integer count = (Integer)application.getAttribute("count");if(count==null){application.setAttribute("count", 1);}else{application.setAttribute("count", count+1);}resp.sendRedirect("index.jsp");}}
<pre name="code" class="java">(b/注销,建一个LogoutServlet类继承HttpServlet父类)

2、前端部分代码
<pre name="code" class="javascript"><%@page import="org.apache.catalina.SessionListener"%><%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body>当前在线人数:<%Object obj=application.getAttribute("count");%><%if(obj==null){out.print(0);}else{out.println(obj);}%><form action="baidu" method="GET"><input type="submit"  value="登录"/></form><form action="baidu2" method="GET"><input type="submit"  value="注销"/></form></body></html>
3、web.xml的配置
<pre name="code" class="javascript"><?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>demo1103</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  <servlet>  <servlet-name>test</servlet-name>  <servlet-class>com.iotek.servlet.LoginServlet</servlet-class>  </servlet>  <servlet-mapping>  <servlet-name>test</servlet-name>  <url-pattern>/baidu</url-pattern>  </servlet-mapping>  <servlet>  <servlet-name>test2</servlet-name>  <servlet-class>com.iotek.servlet.LogoutServlet</servlet-class>  </servlet>  <servlet-mapping>  <servlet-name>test2</servlet-name>  <url-pattern>/baidu2</url-pattern>  </servlet-mapping>  </web-app>

4、application


0 0