jsp实验5 下载本文

内容发布更新时间 : 2024/11/15 5:55:48星期一 下面是文章的全部内容请认真阅读。

import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

public class OnlineUserServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

request.setCharacterEncoding(\ String name = request.getParameter(\ String pwd = request.getParameter(\ if(null == name || null == pwd || name.equals(\ response.sendRedirect(\ } else{ HttpSession session = request.getSession(); User user = (User)session.getAttribute(\ if(null == user || !name.equals(user.getName())) { user = new User(name); session.setAttribute(\ } response.setContentType(\ PrintWriter out = response.getWriter(); out.println(\欢迎用户\登录\ UserList ul = UserList.getInstance(); out.println(\当前在线的用户列表:
\ Enumeration enums = ul.getUserList(); int i = 0; while(enums.hasMoreElements()) { out.println(enums.nextElement()); out.println(\ if(++i == 10) { out.println(\ } } out.println(\当前在线的用户数:\ out.println(\退出登录\ out.close(); } }

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException,IOException {

doGet(request, response); } }

User.java

package com;

import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener;

public class User implements HttpSessionBindingListener {

private String name;

private UserList ul = UserList.getInstance();

public User() { }

public User(String name) { this.name = name; }

public void setName(String name) { this.name = name; } public String getName() { return name; } @Override public void valueBound(HttpSessionBindingEvent event) { ul.addUser(name); } @Override public void valueUnbound(HttpSessionBindingEvent event) { ul.removeUser(name); } }

UserList.java

package com;

import java.util.Enumeration; import java.util.Vector;

public class UserList { private static final UserList userList = new UserList(); private Vector vector;

private UserList(){ vector=new Vector(); }

public static UserList getInstance(){ return userList; } public void addUser(String name) { if(name != null) vector.addElement(name); } public void removeUser(String name) { if(name != null) vector.remove(name); } public Enumeration getUserList() { return vector.elements(); } public int getUserCount() { return vector.size(); } }

Login.html

用户登录

用户名:
密码:

web.xml

xmlns:web=\ xsi:schemaLocation=\

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\ id=\ version=\>

ch3

OnlineUserServlet com.OnlineUserServlet

OnlineUserServlet success

logout

com.LogoutServlet

logout logout

index.html index.htm index.jsp default.html default.htm default.jsp

六、本次实验的体会(结论):

本次实验中,我通过查阅老师的课件和教材,加深了对Servlet、过滤器和监听器概念以及基本使用方法的理解。