1 问题描述
利用java ee相关技术实现一个简单的web聊天室系统,具体要求如下。
(1)编写一个登录页面,登录信息中有用户名和密码,分别用两个按钮来提交和重置登录信息。
(2)编写一个Servlet程序Main.java通过请求指派来处理用户提交的登录信息,如果用户名为本小组成员的名字且密码为对应的学号时,跳转到LoginSuccess显示聊天界面(类似于QQ群聊天界面,可使用HTML中的frameset标签生成两个窗口,一个用来实现用户信息输入,另一个显示所有用户聊天记录的);否则跳转到LoginFail页面,提示用户重新登录(注:此页面要包含前面的登录界面)。
(3)编写两个Servlet程序,分别用来显示“信息输入”窗口和“聊天记录显示”窗口的内容;用户在“信息输入”窗口中键入聊天内容,点击“发送”按钮后,在“聊天记录显示”窗口中显示发送消息的用户名称和聊天内容。提示:利用HTML中的textarea标签来实现。
(4)在登录界面上实现记住用户名和密码的功能,使得当用户选择了此功能并成功登录后,在其下次登录时可以不用再输入用户名和密码即可登录。提示:此功能可通过两个Cookie来实现。
以下功能选做:
(5)编写一个Listener程序来监听会话的创建和销毁事件,以此统计当前在线(登录)人数,并将其显示在聊天界面上。
(6)添加一个Filter对本系统所有的Servlet程序进行过滤,该Filter实现对请求和响应对象的编码格式的设置(实现此功能后,Servlet可以直接从请求对象中获取参数信息而无需实现对请求进行格式的编码)。在【GlassFish Server】视图中输出程序在Filter和其它资源之间的执行顺序。
2 解决方案
2.1 预期效果

图一:网上聊天系统运行示意图
2.2 系统结构示意图

图二:系统结构示意图
welcome.jsp具体页面:

图三:welcome.jsp实际运行图
2.3 具体编码
(1)Main.java(Servlet类)通过请求指派来处理login.jsp页面用户提交的登录信息(并使用Cookie实现记住用户登录用户名和密码功能),成功则跳转到welcome.jsp,失败则跳转到login.jsp。具体实现如下:
网上聊天系统登陆首页login.jsp页面代码:
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<base>">
<title>网上聊天室登陆页面</title>
<meta>
<meta>
<meta>
<meta>
<meta>
<meta>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style>
*
{
margin: 0;
padding: 0;
}
body
{
font-size: 0px;
padding: 200px;
}
</style>
Main.java类代码:
package com.liuzhen.chart;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class Main extends HttpServlet {
/**
* Constructor of the object.
*/
public Main() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=utf-8");
//此出注解是因为使用CodeFilter类过滤所有Servlet,转换编码
//request.setCharacterEncoding("utf-8");
String userName = request.getParameter("username");
String passWord = request.getParameter("password");
String checkBox = request.getParameter("save_password");
System.out.println("userName:"+userName+"\n"+"passWord:"+passWord);
request.getSession().setAttribute("nameSession", userName); //将用户名存入session中
String[] name_one = {"柳真","刘仁杰","吴超","张浩东","陈初相"};
String[] pwd_one = {"201421092073","201421092068","201421092077","201421092082","201421092119"};
String name_two = "";
String pwd_two = "";
boolean login_test = false;
for(int i=0;i
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
登陆失败页面loginFail.jsp页面代码:
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <base>"> <title>My JSP 'loginFail.jsp' starting page</title> <meta> <meta> <meta> <meta> <meta> <meta> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <br> <br> <h1>用户名和密码不匹配,请重新登陆!</h1> <a>重新登陆</a>
登陆成功页面welcome.jsp页面代码(此处使用frameset标签,分为头部、左部和中间主页三部分,分别对象header.jsp、left.jsp和main.jsp页面):
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <base>"> <title>网上聊天室</title> <meta> <meta> <meta> <meta> <meta> <meta> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <frameset> <frame> <frameset> <frame> <frame> </frameset> </frameset>
聊天头部header.jsp页面代码:
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <base>"> <title></title> <meta> <meta> <meta> <meta> <meta> <meta> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
聊天左部left.jsp页面代码(此处为了显示美观,使用了jquery-1.4.2包):
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<base>">
<title>My JSP 'test.jsp' starting page</title>
<meta>
<meta>
<meta>
<meta>
<meta>
<meta>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style>
*
{
margin: 0;
padding: 0;
}
body
{
font-size: 15px;
padding: 00px;
}
.menu
{
width: 500px;
border-bottom: solid 1px gray;
}
.menu h3
{
border: solid 1px gray;
height: 30px;
line-height: 30px;
padding-left: 10px;
padding:0 5px;
border-bottom: none;
cursor: pointer;
}
.menu p
{
border-left: solid 1px gray;
border-right: solid 1px gray;
padding: 20px 0;
padding-left: 5px;
}
.changecolor{background-color:red;}
</style>
<script></script>
<script>
$(function () {
$(".menu p:not(:first)").hide();
$(".menu h3").css("background", "#ccc");
$(".menu h3").hover(function () { $(this).css("background-color", "gray").siblings("h3").css
("background-color", "#ccc");});
$(".menu h3").mouseleave(function () {
$(".menu h3").css("background", "#ccc");}); //离开时将其变为原来颜色
var index = $(".menu h3").index(this);
$(".menu h3").click(function () { $(this).next("p").slideToggle().siblings("p").slideUp(); });
});
</script>
<div>
<h3>
我的好友</h3>
<p>
<a>周杰伦</a><br><br>
<a>周杰伦</a><br><br>
<a>周杰伦</a><br><br>
<a>周杰伦</a><br><br>
<a>周杰伦</a><br><br>
<a>周杰伦</a><br><br>
<a>周杰伦</a><br><br>
<a>周杰伦</a><br>
</p>
<h3>
我的朋友</h3>
<p>
<a>李连杰</a><br><br>
<a>李连杰</a><br><br>
<a>李连杰</a><br><br>
<a>李连杰</a><br><br>
<a>李连杰</a><br><br>
<a>李连杰</a><br><br>
<a>李连杰</a><br><br>
<a>李连杰</a><br>
</p>
<h3>
陌生人</h3>
<p>
<a>比尔盖茨</a><br><br>
<a>比尔盖茨</a><br><br>
<a>比尔盖茨</a><br><br>
<a>比尔盖茨</a><br><br>
<a>比尔盖茨</a><br><br>
<a>比尔盖茨</a><br><br>
<a>比尔盖茨</a><br>
</p>
</div>
聊天主页main.jsp页面代码:
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <base>"> <title>My JSP 'main.jsp' starting page</title> <meta> <meta> <meta> <meta> <meta> <meta> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
(2)InputInformation.java(Servlet类)通过请求指派获取main.jsp聊天输入框中输入信息,跳转到main.jsp页面,并在聊天记录显示框中显示聊天信息。具体实现如下:
InputInformation.java类代码如下:
package com.liuzhen.chart;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class InputInformation extends HttpServlet {
public String chat_record = ""; //定义聊天记录变量,此处为全局变量
/**
* Constructor of the object.
*/
public InputInformation() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=utf-8");
//此出注解是因为使用CodeFilter类过滤所有Servlet,转换编码
//request.setCharacterEncoding("utf-8");
String input_textarea = request.getParameter("input_textarea");
Date now = new Date(); //创建日期对象,及系统当前时间
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String time = dateFormat.format( now ); //按照给定的日期格式获取系统当前时间
String t = (String)request.getSession().getAttribute("nameSession"); //获取登陆页面用户名
chat_record += t+" "+input_textarea+" "+time+"\n"; //聊天记录存储
request.setAttribute("input_textarea",chat_record); //将当前聊天输入内容存储
request.getRequestDispatcher("main.jsp").forward(request,response); //跳转到当前聊天输入界面,即界面布局不变
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
(3)CodeFilter.java(过滤器类)截取系统所有Servlet类,实现对请求和响应对象的编码格式的设置,均设置为UTF-8。具体实现如下:
CodeFilter.java类代码如下:
package com.liuzhen.chart;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//采用注解方式配置URL,此处就不必再在web.xml文件中配置。如果两者均配置的话,系统将以web.xml文件中配置信息为准
@WebFilter(filterName="CodeFilter",urlPatterns={"/*"})
public class CodeFilter implements Filter{
@Override
public void destroy() {
System.out.println("destroy---CodeFilter");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("start----doFilter--CodeFilter");
HttpServletRequest request =(HttpServletRequest) arg0;
HttpServletResponse response =(HttpServletResponse) arg1;
//以上是强制内型转换,使用request对象和response对象
request.setCharacterEncoding("utf-8"); //设置过滤页面提取数据的编码
response.setContentType("text/html;charset=utf-8"); //设置过滤页面显示数据的编码
arg2.doFilter(arg0, arg1);//在页面跳转之前执行此语句前面的代码,执行完页面的代码之后,在执行后面的语句
System.out.println("第一个字符过滤器");
System.out.println("end------doFilter--CodeFilter");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init----CodeFilter");
}
}
(4)OnlineListener.java(监听器类)主动监听系统Web容器,返回当前聊天系统在线人数,具体实现如下:
OnlineListener.java类代码如下:
package com.liuzhen.chart;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineListener implements HttpSessionListener{
public void sessionCreated(HttpSessionEvent arg0) {
ServletContext context = arg0.getSession().getServletContext();
Integer count = (Integer) context.getAttribute("peopleOnline");
if (count == null) {
count = 1;
} else {
count++;
}
context.setAttribute("peopleOnline", count);
}
public void sessionDestroyed(HttpSessionEvent arg0) {
ServletContext context = arg0.getSession().getServletContext();
Integer count = (Integer) context.getAttribute("peopleOnline");
count--;
context.setAttribute("peopleOnline", count);
}
}
此处还要给OnlineListener监听器类在web.xml文件中配置路径,web.xml配置代码具体如下(红色标记代码):
<?xml version="1.0" encoding="UTF-8"?><web-app> <display-name></display-name> <listener> <listener-class>com.liuzhen.chart.OnlineListener</listener-class> </listener> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>Main</servlet-name> <servlet-class>com.liuzhen.chart.Main</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>InputInformation</servlet-name> <servlet-class>com.liuzhen.chart.InputInformation</servlet-class> </servlet> <servlet-mapping> <servlet-name>Main</servlet-name> <url-pattern>/Main</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>InputInformation</servlet-name> <url-pattern>/InputInformation</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list></web-app>
在调用监听器类实现监听系统当前在线人数时,本机上同一个浏览器同时登陆多个用户,只能算作一次,本机上不同浏览器登陆则分别算作一次。以下分别是在IE、谷歌和360浏览器登陆在线人数显示:

图四:IE浏览器登陆,显示在线人数1人

图五:谷歌浏览器登陆,显示在线人数2人

图六:360浏览器登陆,显示在线人数3人
附:本文系统代码Coding链接:https://coding.net/u/LiuZhen1995/p/MyDemo/git/tree/origin_seven










