设计一个简单的Web聊天程序。 要求:用户输入用户名登录,进入聊天页面,该页面可以发送并显示聊天信息;若用户已经登录则不可重复登入;用户登录成功,在聊天内容窗口显示该用户上线。 提示:程序中用application对象保存聊天内容和全部登录用户名,用session对象保存用户登录信息,用request和response对象进行页面参数传递。
时间: 2024-03-25 11:42:01 浏览: 79
好的,我可以为您提供一个简单的Web聊天程序设计思路和代码实现。
1. 首先,创建一个登录页面login.jsp,用户输入用户名和密码,点击登录按钮后提交表单到login.do处理登录请求。
2. 在login.do中,首先判断用户是否已经登录,如果已经登录则跳转到聊天页面chat.jsp;如果未登录,则验证用户名和密码是否正确,如果正确则将用户信息保存在session中,并且将用户添加到用户列表中。
3. 在chat.jsp中,通过AJAX实时获取聊天内容,同时通过WebSocket实现实时聊天。当用户发送聊天内容时,将内容通过AJAX请求发送到服务器,服务器将内容保存在application中,然后通过WebSocket发送给所有在线用户。
4. 当用户退出聊天页面时,将用户从用户列表中移除,并在聊天内容窗口显示该用户下线。
以下是示例代码:
login.jsp
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<h1>登录页面</h1>
<form action="login.do" method="post">
<label>用户名:</label>
<input type="text" name="username"><br>
<label>密码:</label>
<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
login.do
```
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
response.sendRedirect("chat.jsp");
} else {
if ("admin".equals(username) && "admin".equals(password)) {
session.setAttribute("username", username);
ServletContext application = getServletContext();
List<String> userList = (List<String>) application.getAttribute("userList");
if (userList == null) {
userList = new ArrayList<>();
}
userList.add(username);
application.setAttribute("userList", userList);
response.sendRedirect("chat.jsp");
} else {
response.sendRedirect("login.jsp");
}
}
}
}
```
chat.jsp
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>聊天页面</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
var socket = new WebSocket("ws://localhost:8080/chat");
socket.onmessage = function(event) {
var message = event.data;
$("#chatContent").append(message + "<br>");
};
$("#sendButton").click(function() {
var message = $("#message").val();
$.ajax({
url: "send.do",
type: "post",
data: {message: message},
success: function() {
$("#message").val("");
}
});
});
});
</script>
</head>
<body>
<h1>聊天页面</h1>
<p>欢迎您,<%=session.getAttribute("username")%></p>
<div id="chatContent"></div>
<input type="text" id="message">
<button id="sendButton">发送</button>
</body>
</html>
```
WebSocketServlet
```
@WebServlet("/chat")
public class WebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
public void onOpen(Session session, EndpointConfig config) {
sessions.add(session);
ServletContext application = getServletContext();
List<String> userList = (List<String>) application.getAttribute("userList");
if (userList != null) {
for (String user : userList) {
try {
session.getBasicRemote().sendText(user + "上线了!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onClose(Session session, CloseReason closeReason) {
sessions.remove(session);
ServletContext application = getServletContext();
List<String> userList = (List<String>) application.getAttribute("userList");
if (userList != null) {
userList.remove((String) session.getUserProperties().get("username"));
application.setAttribute("userList", userList);
for (Session s : sessions) {
try {
s.getBasicRemote().sendText((String) session.getUserProperties().get("username") + "下线了!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onMessage(String message, Session session) {
ServletContext application = getServletContext();
List<String> chatContent = (List<String>) application.getAttribute("chatContent");
if (chatContent == null) {
chatContent = new ArrayList<>();
}
chatContent.add((String) session.getUserProperties().get("username") + ": " + message);
application.setAttribute("chatContent", chatContent);
for (Session s : sessions) {
try {
s.getBasicRemote().sendText((String) session.getUserProperties().get("username") + ": " + message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onError(Session session, Throwable throwable) {
throwable.printStackTrace();
}
}
```
send.do
```
@WebServlet("/send.do")
public class SendServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = request.getParameter("message");
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
ServletContext application = getServletContext();
List<String> chatContent = (List<String>) application.getAttribute("chatContent");
if (chatContent == null) {
chatContent = new ArrayList<>();
}
chatContent.add(username + ": " + message);
application.setAttribute("chatContent", chatContent);
for (Session s : WebSocketServlet.sessions) {
try {
s.getBasicRemote().sendText(username + ": " + message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
以上是一个简单的Web聊天程序的设计思路和代码实现,希望能对您有所帮助!
阅读全文