内容发布更新时间 : 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
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
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
Login.html
web.xml
xmlns:web=\ xsi:schemaLocation=\ http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\ id=\ version=\>
六、本次实验的体会(结论):
本次实验中,我通过查阅老师的课件和教材,加深了对Servlet、过滤器和监听器概念以及基本使用方法的理解。