管理登录(在线用户):---(Filter+listener+servlet)
index.jsp
<body>
<c:if test="${empty sessionScope.user }" var="boo">
<h2>用户登录</h2>
<form action="<c:url value='/LoginServlet'/>" method="post">
姓名:<input type="text" name="name"/><br/>
密码:<input type="password" name="pwd"/><br/>
<input type="submit"/>
</form>
</c:if>
<c:if test="!boo">
欢迎你${user.name },
<c:if test=" ${user.admain }" >
管理员
</c:if>
<a href="<c:url value='/servlet/ShowServlet'/>">查看用户信息</a>
<div style="width:80px;background-color:#A6FFFF;">
<a href="<c:url value='/servlet/ExitServlet'/>">安全退出</a> <br/>
</div>
</c:if> </body>
PreFilter.java(拦截所有) 做一些预处理的功能
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpServletRequest req=(HttpServletRequest) request;
if(req.getSession().getAttribute("ip")==null){
System.out.println( req.getRemoteAddr());
//在后台session是拿不到IP地址的只能通过request拿;所以在这里把Ip添加到session中
req.getSession().setAttribute("ip", req.getRemoteAddr());//
}
chain.doFilter(request, response);}
LoginFilter.java(拦截/jsps/*;/servlet/*)
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse resp=(HttpServletResponse) response;
if(req.getSession().getAttribute("user")==null){
//到主页中去;不能放行
resp.sendRedirect(req.getContextPath()+"/index.jsp");
}else{
chain.doFilter(request, response);
}
}
MySessionListener.javapublic class MySessionListener implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent se) {//用户第一次访问项目就会触发这个函数
ServletContext ctx=se.getSession().getServletContext();
//放的是所有在线用户
Map<String, HttpSession> onlines=(Map<String, HttpSession>) ctx.getAttribute("onlines");
if(onlines==null){
//一般去读;看是否为空
//Collections中集合都是同步带锁集合----单例;一个用户访问的时候其他用户可以排队
onlines=Collections.synchronizedMap(new HashMap<String, HttpSession>());
//ctx放的是onlines的地址;所以捆绑只要添加一次
ctx.setAttribute("onlines", onlines);
}
//key----JSESSIONID
onlines.put(se.getSession().getId(), se.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {//session失效会触发这个函数
ServletContext ctx=se.getSession().getServletContext();
Map<String, HttpSession> onlines=(Map<String, HttpSession>) ctx.getAttribute("onlines");
if(onlines!=null){
if(onlines.containsKey(se.getSession().getId())){
onlines.remove(se.getSession().getId());//通过key值移除
ctx.setAttribute("onlines", onlines);
} } } }
LoginServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
User user=new User();
user.setName(name);
user.setPwd(pwd);
//模拟一下管理员身份
Random r=new Random ();
int i=r.nextInt(100);
if(i%2==0){
user.setAdmin(true);
}
if(name!=null&&pwd!=null){//这里模拟从数据库读取
request.getSession().setAttribute("user", user);//把数据存储到user中
//因为在线数据是存储在requset中如果重定向到show.jsp是读取不到用户信息
response.sendRedirect(request.getContextPath()+"/servlet/ShowServlet");
}else{
response.sendRedirect(request.getContextPath()+"/index.jsp"); } }
ShoeServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//最终要封装成List<Map<String,Oblect>>写向前端页面
List<Map<String, Object>> onlines=new ArrayList<Map<String,Object>>();
//从ServletContext 中读取onlines
ServletContext ctx=request.getServletContext();
Map<String, HttpSession> maps=(Map<String, HttpSession>) ctx.getAttribute("onlines");
//在从map把数据读取拆分
if(maps!=null){
Iterator<Entry<String, HttpSession>> it=maps.entrySet().iterator();
while(it.hasNext()){
Entry<String, HttpSession> en=it.next();
Map< String, Object> map=new HashMap<String, Object>();
// en.getValue()拿到session
map.put("user", en.getValue().getAttribute("user"));
//session的创建时间与最近在线时间
map.put("creationTime", new Date( en.getValue().getCreationTime()));
map.put("lastAccessedTime", new Date( en.getValue().getLastAccessedTime()));
//在Filter中已经封装好
map.put("ip",en.getValue().getAttribute("ip"));
//ID用于管理员删除
map.put("id",en.getKey());
//添加到list中
System.out.println(map);
onlines.add(map);
} }
//每次查看在线用户算是一次请求:所以将结果放到request中
request.setAttribute("onlines", onlines);
request.getRequestDispatcher("/jsps/show.jsp").forward(request, esponse); }
ExitServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//--------安全退出-----------------
//都是关键代码
//第一步:必须把session对象的属性移除,因为判断是否登录成功是看session中是否有user属性
request.getSession().removeAttribute("user");
//让session对象失效;不能调用这个session
request.getSession().invalidate();// 自动激活session监听 中的MySessionListener的sessionDestroyed();
<body>
<h2>用户信息显示</h2>
<table>
<tr> <td>姓名</td>
<td>上线时间</td>
<td>最近在线时间</td>
<td>IP</td>
<td>操作</td> </tr>
<c:forEach items="${requestScope.onlines}" var="map">
<tr> <td> <c:if test="${empty map.user}" var="boo">
游客 </c:if>
<c:if test="!boo">${map.user.name }</c:if> </td>
<td><fmt:formatDate value="${map.creationTime}" pattern="yyyy-MM-dd HH:mm:ss"/> </td>
<td> <!-- value值是一个Date对象 -->
<fmt:formatDate value="${map.lastAccessedTime }" pattern="yyyy:MM:dd HH:mm:ss"/> </td>
<td>${map.ip}</td>
<td><c:if test="${!boo&&sessionScope.user.admin}">
<a href="<c:url value='/servlet/KickOutServlet?id=${map.id}'/>">踢出</a> </c:if> </td> </tr>
</c:forEach> </table> </body>
KickOutServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
String id=request.getParameter("id");
Map<String, HttpSession> map=(Map<String, HttpSession>) request.getSession().getAttribute("onlines");
if(map.containsKey(id)){
HttpSession session=map.get(id);
//拿到本人的ID
HttpSession mySession =request.getSession();
//删除前拿到用户名
User user=(User) session.getAttribute("user");
String name=user.getName();
//第一步:必须把session对象的属性移除,因为判断是否登录成功是看session中是否有user属性
request.getSession().removeAttribute("user");
//让session对象失效;不能调用这个session
request.getSession().invalidate();// 自动激活session监听 中的MySessionListener的sessionDestroyed();
out.println(name+"已被删除");
} }
index.jsp
<body>
<c:if test="${empty sessionScope.user }" var="boo">
<h2>用户登录</h2>
<form action="<c:url value='/LoginServlet'/>" method="post">
姓名:<input type="text" name="name"/><br/>
密码:<input type="password" name="pwd"/><br/>
<input type="submit"/>
</form>
</c:if>
<c:if test="!boo">
欢迎你${user.name },
<c:if test=" ${user.admain }" >
管理员
</c:if>
<a href="<c:url value='/servlet/ShowServlet'/>">查看用户信息</a>
<div style="width:80px;background-color:#A6FFFF;">
<a href="<c:url value='/servlet/ExitServlet'/>">安全退出</a> <br/>
</div>
</c:if> </body>
PreFilter.java(拦截所有) 做一些预处理的功能
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpServletRequest req=(HttpServletRequest) request;
if(req.getSession().getAttribute("ip")==null){
System.out.println( req.getRemoteAddr());
//在后台session是拿不到IP地址的只能通过request拿;所以在这里把Ip添加到session中
req.getSession().setAttribute("ip", req.getRemoteAddr());//
}
chain.doFilter(request, response);}
LoginFilter.java(拦截/jsps/*;/servlet/*)
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse resp=(HttpServletResponse) response;
if(req.getSession().getAttribute("user")==null){
//到主页中去;不能放行
resp.sendRedirect(req.getContextPath()+"/index.jsp");
}else{
chain.doFilter(request, response);
}
}
MySessionListener.javapublic class MySessionListener implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent se) {//用户第一次访问项目就会触发这个函数
ServletContext ctx=se.getSession().getServletContext();
//放的是所有在线用户
Map<String, HttpSession> onlines=(Map<String, HttpSession>) ctx.getAttribute("onlines");
if(onlines==null){
//一般去读;看是否为空
//Collections中集合都是同步带锁集合----单例;一个用户访问的时候其他用户可以排队
onlines=Collections.synchronizedMap(new HashMap<String, HttpSession>());
//ctx放的是onlines的地址;所以捆绑只要添加一次
ctx.setAttribute("onlines", onlines);
}
//key----JSESSIONID
onlines.put(se.getSession().getId(), se.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {//session失效会触发这个函数
ServletContext ctx=se.getSession().getServletContext();
Map<String, HttpSession> onlines=(Map<String, HttpSession>) ctx.getAttribute("onlines");
if(onlines!=null){
if(onlines.containsKey(se.getSession().getId())){
onlines.remove(se.getSession().getId());//通过key值移除
ctx.setAttribute("onlines", onlines);
} } } }
LoginServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
User user=new User();
user.setName(name);
user.setPwd(pwd);
//模拟一下管理员身份
Random r=new Random ();
int i=r.nextInt(100);
if(i%2==0){
user.setAdmin(true);
}
if(name!=null&&pwd!=null){//这里模拟从数据库读取
request.getSession().setAttribute("user", user);//把数据存储到user中
//因为在线数据是存储在requset中如果重定向到show.jsp是读取不到用户信息
response.sendRedirect(request.getContextPath()+"/servlet/ShowServlet");
}else{
response.sendRedirect(request.getContextPath()+"/index.jsp"); } }
ShoeServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//最终要封装成List<Map<String,Oblect>>写向前端页面
List<Map<String, Object>> onlines=new ArrayList<Map<String,Object>>();
//从ServletContext 中读取onlines
ServletContext ctx=request.getServletContext();
Map<String, HttpSession> maps=(Map<String, HttpSession>) ctx.getAttribute("onlines");
//在从map把数据读取拆分
if(maps!=null){
Iterator<Entry<String, HttpSession>> it=maps.entrySet().iterator();
while(it.hasNext()){
Entry<String, HttpSession> en=it.next();
Map< String, Object> map=new HashMap<String, Object>();
// en.getValue()拿到session
map.put("user", en.getValue().getAttribute("user"));
//session的创建时间与最近在线时间
map.put("creationTime", new Date( en.getValue().getCreationTime()));
map.put("lastAccessedTime", new Date( en.getValue().getLastAccessedTime()));
//在Filter中已经封装好
map.put("ip",en.getValue().getAttribute("ip"));
//ID用于管理员删除
map.put("id",en.getKey());
//添加到list中
System.out.println(map);
onlines.add(map);
} }
//每次查看在线用户算是一次请求:所以将结果放到request中
request.setAttribute("onlines", onlines);
request.getRequestDispatcher("/jsps/show.jsp").forward(request, esponse); }
ExitServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//--------安全退出-----------------
//都是关键代码
//第一步:必须把session对象的属性移除,因为判断是否登录成功是看session中是否有user属性
request.getSession().removeAttribute("user");
//让session对象失效;不能调用这个session
request.getSession().invalidate();// 自动激活session监听 中的MySessionListener的sessionDestroyed();
//第三步 存储在线用户的池onlines中也要移除该session; session监听 中的sessionDestroyed();做了这一步}
<body>
<h2>用户信息显示</h2>
<table>
<tr> <td>姓名</td>
<td>上线时间</td>
<td>最近在线时间</td>
<td>IP</td>
<td>操作</td> </tr>
<c:forEach items="${requestScope.onlines}" var="map">
<tr> <td> <c:if test="${empty map.user}" var="boo">
游客 </c:if>
<c:if test="!boo">${map.user.name }</c:if> </td>
<td><fmt:formatDate value="${map.creationTime}" pattern="yyyy-MM-dd HH:mm:ss"/> </td>
<td> <!-- value值是一个Date对象 -->
<fmt:formatDate value="${map.lastAccessedTime }" pattern="yyyy:MM:dd HH:mm:ss"/> </td>
<td>${map.ip}</td>
<td><c:if test="${!boo&&sessionScope.user.admin}">
<a href="<c:url value='/servlet/KickOutServlet?id=${map.id}'/>">踢出</a> </c:if> </td> </tr>
</c:forEach> </table> </body>
KickOutServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
String id=request.getParameter("id");
Map<String, HttpSession> map=(Map<String, HttpSession>) request.getSession().getAttribute("onlines");
if(map.containsKey(id)){
HttpSession session=map.get(id);
//拿到本人的ID
HttpSession mySession =request.getSession();
//删除前拿到用户名
User user=(User) session.getAttribute("user");
String name=user.getName();
//第一步:必须把session对象的属性移除,因为判断是否登录成功是看session中是否有user属性
request.getSession().removeAttribute("user");
//让session对象失效;不能调用这个session
request.getSession().invalidate();// 自动激活session监听 中的MySessionListener的sessionDestroyed();
out.println(name+"已被删除");
} }