一、创建一个登录页面文件login.jsp 二、编写online.jsp,统计在线人数,并可进行注销,调用invalidate.jsp,注销后再更新在线人数。
时间: 2023-05-28 19:07:49 浏览: 77
一、login.jsp文件代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="check.jsp" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
二、online.jsp文件代码:
```jsp
<%@ page language="java" import="java.util.*,javax.servlet.*,javax.servlet.http.*"%>
<%
// 获取session对象
HttpSession session = request.getSession(true);
// 获取在线人数
Integer onlineCount = (Integer) application.getAttribute("onlineCount");
if (onlineCount == null) {
onlineCount = 0;
}
// 判断是否为注销操作
String logout = request.getParameter("logout");
if (logout != null && logout.equals("true")) {
// 销毁session
session.invalidate();
// 在线人数减一
onlineCount--;
// 更新在线人数
application.setAttribute("onlineCount", onlineCount);
// 跳转到注销成功页面
response.sendRedirect("invalidate.jsp");
} else {
// 获取用户名
String username = (String) session.getAttribute("username");
if (username == null) {
// 用户未登录,跳转到登录页面
response.sendRedirect("login.jsp");
} else {
// 用户已登录,显示在线人数和注销按钮
out.println("欢迎您," + username + ",当前在线人数为:" + onlineCount + "<br>");
out.println("<a href='online.jsp?logout=true'>注销</a>");
}
}
%>
```
三、invalidate.jsp文件代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注销成功</title>
</head>
<body>
<h1>注销成功!</h1>
</body>
</html>
```
四、check.jsp文件代码:
```jsp
<%@ page language="java" import="java.util.*,javax.servlet.*,javax.servlet.http.*"%>
<%
// 获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 判断用户名和密码是否正确
if (username.equals("admin") && password.equals("123456")) {
// 用户名和密码正确,将用户名存入session
HttpSession session = request.getSession(true);
session.setAttribute("username", username);
// 获取在线人数
Integer onlineCount = (Integer) application.getAttribute("onlineCount");
if (onlineCount == null) {
onlineCount = 0;
}
// 在线人数加一
onlineCount++;
// 更新在线人数
application.setAttribute("onlineCount", onlineCount);
// 跳转到在线页面
response.sendRedirect("online.jsp");
} else {
// 用户名或密码错误,返回登录页面
response.sendRedirect("login.jsp");
}
%>
```