JavaEE在线人数管理系统
这篇博客是filter、listener和servlet技术的相关总结,实现了简单的显示在线人数、在线人详细信息、管理员踢人功能
下面是详细代码
web.xml
<?xmlversion="1.0"encoding="UTF-8"?> <web-appversion="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <filter> <filter-name>character</filter-name> <filter-class>cn.hncu.filter.CharacterFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter> <filter-name>login</filter-name> <filter-class>cn.hncu.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>character</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>login</filter-name> <url-pattern>/servlet/*</url-pattern> <url-pattern>/jsps/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> <listener> <listener-class>cn.hncu.listener.MySessionListener</listener-class> </listener> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>cn.hncu.servlet.LoginServlet</servlet-class> </servlet> <servlet> <servlet-name>ShowServlet</servlet-name> <servlet-class>cn.hncu.servlet.ShowServlet</servlet-class> </servlet> <servlet> <description>ThisisthedescriptionofmyJ2EEcomponent</description> <display-name>ThisisthedisplaynameofmyJ2EEcomponent</display-name> <servlet-name>KickOutServlet</servlet-name> <servlet-class>cn.hncu.servlet.KickOutServlet</servlet-class> </servlet> <servlet> <description>ThisisthedescriptionofmyJ2EEcomponent</description> <display-name>ThisisthedisplaynameofmyJ2EEcomponent</display-name> <servlet-name>LoginOutServlet</servlet-name> <servlet-class>cn.hncu.servlet.LoginOutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowServlet</servlet-name> <url-pattern>/servlet/ShowServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>KickOutServlet</servlet-name> <url-pattern>/servlet/KickOutServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>LoginOutServlet</servlet-name> <url-pattern>/servlet/LoginOutServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
index.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%> <%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <title>在线人信息管理</title> </head> <body> <h2>在线人信息管理</h2> <h3>会员登录</h3> <c:iftest="${emptysessionScope.user.name}"var="boo"> <formaction='<c:urlvalue="/LoginServlet"></c:url>'> 姓名:<inputtype="text"name="name"><br/> <inputtype="submit"value="登录"><br/> </form> </c:if> <c:iftest="${!boo}"> 欢迎回来,${sessionScope.user.name} <c:iftest="${sessionScope.user.admin}"var="bo"> 管理员 </c:if> <c:iftest="${!bo}"> 会员 </c:if> </c:if> <br/> <c:iftest="${!boo}"var="boo"> <ahref='<c:urlvalue="/servlet/ShowServlet"/>'>查看在线人信息</a><br/> <ahref='<c:urlvalue="/servlet/LoginOutServlet"/>'>安全退出</a><br/> </c:if> </body> </html>
/jsps/show.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%> <%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <title>在线人信息</title> <styletype="text/css"> table{ color:green; border:1pxsolidblue; border-collapse:collapse; width:500px; margin:auto; } td{ border:1pxsolidblue; } th{ border:1pxsolidblue; } body{ text-align:center; } </style> <metahttp-equiv="refresh"content="3"> </head> <body> <table> <tr> <th>姓名</th> <th>上线时间</th> <th>最后访问时间</th> <th>ip</th> <th>操作</th> </tr> <c:forEachitems="${requestScope.onlines}"var="online"> <tr> <td> <c:iftest="${!emptyonline.user}"var="boo"> ${online.user.name} </c:if> <c:iftest="${emptyonline.user}"> 游客 </c:if> </td> <td>${online.createTime}</td> <td>${online.lastAccessedTime}</td> <td>${online.ip}</td> <td> <c:iftest="${online.user!=sessionScope.user}"> <c:iftest="${!online.user.admin&&boo}"> <ahref='<c:urlvalue="/servlet/KickOutServlet?id=${online.id}"/>'>踢出</a> </c:if> </c:if> </td> </tr> </c:forEach> </table> </body> </html>
User.java(值对象)
packagecn.hncu.domain; publicclassUser{ privateStringname; privatebooleanadmin; publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicbooleanisAdmin(){ returnadmin; } publicvoidsetAdmin(booleanadmin){ this.admin=admin; } @Override publicStringtoString(){ return"User[name="+name+",admin="+admin+"]"; } }
MySessionListener.java(监听器)
packagecn.hncu.listener; importjava.util.Collections; importjava.util.HashMap; importjava.util.Map; importjavax.servlet.http.HttpSession; importjavax.servlet.http.HttpSessionEvent; importjavax.servlet.http.HttpSessionListener; publicclassMySessionListenerimplementsHttpSessionListener{ @Override publicvoidsessionCreated(HttpSessionEventse){ Map<String,HttpSession>onlines=(Map<String,HttpSession>)se.getSession().getServletContext().getAttribute("onlines"); if(onlines==null){ onlines=Collections.synchronizedMap(newHashMap<String,HttpSession>());//对map进行加上同步锁 se.getSession().getServletContext().setAttribute("onlines",onlines); } onlines.put(se.getSession().getId(),se.getSession()); } @Override publicvoidsessionDestroyed(HttpSessionEventse){ Map<String,HttpSession>onlines=(Map<String,HttpSession>)se.getSession().getServletContext().getAttribute("onlines"); if(onlines.containsKey(se.getSession().getId())){ onlines.remove(se.getSession().getId()); } } }
CharacterFilter.java(字符过滤器)
packagecn.hncu.filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; importjavax.servlet.http.HttpServletRequest; publicclassCharacterFilterimplementsFilter{ privateStringcharset; @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ charset=filterConfig.getInitParameter("charset"); } @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse, FilterChainchain)throwsIOException,ServletException{ request.setCharacterEncoding(charset); response.setCharacterEncoding(charset); HttpServletRequestreq=(HttpServletRequest)request; if(req.getSession().getAttribute("ip")==null){ req.getSession().setAttribute("ip",req.getRemoteAddr()); } chain.doFilter(request,response); } @Override publicvoiddestroy(){ } }
LoginFilter.java(防止游客乱访问过滤器)
packagecn.hncu.filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; publicclassLoginFilterimplementsFilter{ @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ } @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse, FilterChainchain)throwsIOException,ServletException{ HttpServletRequestreq=(HttpServletRequest)request; if(req.getSession().getAttribute("user")==null){ ((HttpServletResponse)response).sendRedirect(req.getContextPath()+"/index.jsp"); return; } chain.doFilter(request,response); } @Override publicvoiddestroy(){ } }
LoginServlet.java
packagecn.hncu.servlet; importjava.io.IOException; importjava.io.PrintWriter; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importcn.hncu.domain.User; publicclassLoginServletextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ doPost(request,response); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ Stringname=request.getParameter("name"); Useruser=(User)request.getSession().getAttribute("user"); if(user==null&&name!=null&&name.trim().length()>0){//封装User user=newUser(); user.setName(name); if(name.equals("admin")){ user.setAdmin(true); } } request.getSession().setAttribute("user",user); response.sendRedirect(request.getContextPath()+"/index.jsp"); } }
ShowServlet.java
packagecn.hncu.servlet; importjava.io.IOException; importjava.io.PrintWriter; importjava.text.SimpleDateFormat; importjava.util.ArrayList; importjava.util.Date; importjava.util.HashMap; importjava.util.Iterator; importjava.util.List; importjava.util.Map; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.HttpSession; publicclassShowServletextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ doPost(request,response); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ Map<String,HttpSession>onlines=(Map<String,HttpSession>)request.getServletContext().getAttribute("onlines"); List<Map<String,Object>>list=newArrayList<Map<String,Object>>();//吧Online封装成list if(onlines!=null){ Iterator<HttpSession>it=onlines.values().iterator(); while(it.hasNext()){ HttpSessions=it.next(); Map<String,Object>map=newHashMap<String,Object>(); map.put("id",s.getId()); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); map.put("createTime",sdf.format(newDate(s.getCreationTime()))); map.put("lastAccessedTime",sdf.format(newDate(s.getLastAccessedTime()))); map.put("ip",s.getAttribute("ip"));//ip信息在characterFilter中补 map.put("user",s.getAttribute("user")); list.add(map); } } request.setAttribute("onlines",list); request.getRequestDispatcher("/jsps/show.jsp").forward(request,response); } }
KickOutServlet.java
packagecn.hncu.servlet; importjava.io.IOException; importjava.io.PrintWriter; importjava.util.Map; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.HttpSession; publicclassKickOutServletextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ doPost(request,response); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ Stringid=request.getParameter("id"); Map<String,HttpSession>onlines=(Map<String,HttpSession>)request.getServletContext().getAttribute("onlines"); if(onlines!=null){ if(onlines.containsKey(id)){ onlines.get(id).invalidate(); } } request.getRequestDispatcher("/servlet/ShowServlet").forward(request,response); } }
LoginOutServlet.java
packagecn.hncu.servlet; importjava.io.IOException; importjava.io.PrintWriter; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; publicclassLoginOutServletextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ doPost(request,response); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ request.getSession().invalidate(); response.sendRedirect(request.getContextPath()+"/index.jsp"); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。