enter.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html><body><!--建立一個使用者登入的表單,提交到doEnter頁面--><form action="doEnter.jsp" method="post">來賓名:<input type="text" name="guestName"/><br/><input type="submit" value="進入"/></form></body></html>
doEnter.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@page import="entity.User"%><%//從請求中取出訪客名String guestName = request.getParameter("guestName");//如果來賓名稱輸入為null或者為空白,則重新登入if (guestName == null || guestName.equals("")) {response.sendRedirect("enter.jsp");} else {//建立使用者物件User user = new User();//在user對象中儲存訪客名user.setUserName(guestName);//在session中儲存User對象session.setAttribute("guest", user);response.sendRedirect("online.jsp");}%>
online.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@page import="entity.User"%><%@page import="entity.Constents"%><body><%entity.User user = null;//判斷有沒有guest屬性if (session.getAttribute("guest") == null) {response.sendRedirect("enter.jsp");} else {user = (entity.User) session.getAttribute("guest");%>您好,<%=user.getUserName()%><br /> 此時線上人數為:<%=Constents.ONLINE_USER_COUNT%><br /><a href="doOut.jsp">離開</a><%}%></body>
doOut.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%//使用session失效session.invalidate();response.sendRedirect("enter.jsp");%>
Constents.java
package entity;public class Constents {//靜態整型變數,用來儲存線上的人數public static int ONLINE_USER_COUNT=0;//網站線上人數}
User.java
package entity;import javax.servlet.http.HttpSessionBindingEvent;import javax.servlet.http.HttpSessionBindingListener;public class User implements HttpSessionBindingListener{private int id;private String userName;private String password;private String email;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public void valueBound(HttpSessionBindingEvent event) {//存入session是自動調用Constents.ONLINE_USER_COUNT++;}public void valueUnbound(HttpSessionBindingEvent event) {//從session中刪除自動調用Constents.ONLINE_USER_COUNT--;}}
Google
IE