JavaWeb用Servlet写一个聊天室
文章目录
一、思考
怎么写聊天室?需要利用Servlet技术实现一个简单的聊天室,实现多人同时交流,当发送聊天信息时,信息窗口显示发言人的姓名以及发言的内容。在进入聊天室之前需要进行登录。
需要用什么软件?一些可以编程的软件都可以使用,这里我用到了NetBeans IDE8.2
二、具体操作步骤
1.新建一个web项目
2.写一个简单的登录界面(index.html)
代码如下:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body bgcolor="#FFFFFF">
<h1 align="center"> <b>欢迎登录聊天室</b></h1>
<form action="login" method="post">
<table width="52%" border="2" align="center">
<tr bgcolor="#FFFFCC">
<td align="center" width="43%">
<div align="center">
用户名:
</div>
</td>
<td width="57%"><div align="left">
<input type="text" name="username" size="50">
</div>
</td>
</tr>
<tr bgcolor="#FFFFCC">
<td align="center" width="43%">
<div align="center">
密 码:
</div>
</td>
<td width="57%"><div align="left">
<input type="password" name="password" value="123" size="50">
</div>
</td>
</tr>
</table>
<br>
<div align="center">
<input type="submit" name="Submit" value="登录">
<input type="reset" name="Reset" value="重置">
<div>提示:密码为123</div>
</div>
</form>
</body>
</html>
该代码用post方法提交到login
3.新建一个Servlet
4.Login代码(login.java)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.chat;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class login extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = request.getSession();
session.setAttribute("username", username);
if (password != null && password.equals("123")) {
RequestDispatcher rd = request.getRequestDispatcher("main.jsp");
rd.forward(request, response);
} else {
RequestDispatcher rd = request.getRequestDispatcher("fail.jsp");
rd.forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
进行密码和用户名的比对,如果密码为123并且用户名不为空,成功将跳转到main.jsp页面,失败将跳转到fail.jsp页面,所以接下来我们需要创建俩个jsp页面
5.创建一个jsp页面一个html页面
6.写一个失败的界面(fail.jsp)
代码如下:
<%--
Document : fail
Created on : 2023-4-2, 22:09:48
Author : Admin
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>密码或账号错误,登录失败</h1>
<a href="index.html">重新登陆</a>
</body>
</html>
7.成功的页面(main.jsp)
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>聊天室</title>
</head>
<frameset rows="80,*,80" frameborder="no" border="0" framespacing="0">
<frame src="top.jsp" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" />
<frame src="middle.jsp" name="mainFrame" id="mainFrame" title="mainFrame" />
<frame src="bottom.jsp" name="bottomFrame" scrolling="No" noresize="noresize" id="bottomFrame" title="bottomFrame" />
</frameset>
<noframes><body>
</body>
</noframes></html>
这里我们用了frame面板,将内容划分为3个面板,所以我们又要用到3个jsp页面
8.创建3个jsp页面
9.3个jsp页面代码
1头部页面(top.jsp)
<%--
Document : top
Created on : 2023-4-9, 23:51:51
Author : Admin
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div align="middle"><span class="STYLE1">聊天室</span></div>
</body>
</html>
2.中部页面(middle.jsp)
<%--
Document : middle
Created on : 2023-3-31, 9:41:55
Author : CY-306
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
欢迎登陆<%=session.getAttribute("username")%>
</body>
</html>
3.底部页面(bottom.jsp)
<%--
Document : bottom
Created on : 2023-3-31, 9:05:40
Author : CY-306
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body >
<form id="form1" name="form1" method="post" action="Say" target="mainFrame">
<%=session.getAttribute("username")%>对
<input type="text" name="toname" />
说:
<label>
<input type="text" name="word" />
</label>
<input type="radio" name="emotion" value="laugh.jpg"><img src="laugh.jpg"></input>
<input type="radio" name="emotion" value="cry.jpg"><img src="cry.jpg"></input>
<input type="submit" name="Submit" value="提交" />
</form>
</body>
</html>
在底部页面代码中我们用post方法将内容提交到Say中,所以我们需要写一个Say的Servlet
10.新建一个Servlet
代码如下:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author CY-306
*/
public class Say extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
String words = (String) getServletContext().getAttribute("words");
response.setHeader("refresh", "3");
HttpSession session = request.getSession();
String word = request.getParameter("word");
String toname = request.getParameter("toname");
String emotion = request.getParameter("emotion");
String name = (String) session.getAttribute("username");
if (words == null) {
words = "";
}
if (words == null || word == null) {
word = words;
} else {
if(emotion!=null){
word = name + "对" + toname + "说:" + word + "<img src = " + emotion + ">";
words = words + "<br>" + word;
} else{
word = name + "对" + toname + "说:" + word ;
words = words + "<br>" + word;
}
}
getServletContext().setAttribute("words", words);
out.print(words);
out.println("</body>");
out.println("</html>");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
到此结束
项目运行截图