DAO-创建CustomerDao.java
package DAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import VO.Customer;
public class CustomerDao {
private Connection conn = null;
public void initConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncodeing=utf-8","root","123456");
}
//查询对象的方法
public Customer getCustomerByAccount(String account) throws Exception {
Customer cus = null;
initConnection();//连接数据库的方法
String sql = "select account,password,cname from customer where account=?";//通过账号查询
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, account);
ResultSet rs = ps.executeQuery();
if(rs.next()){
cus = new Customer();//把查询到大的内容放到Customer对象属性中赋值
cus.setAccount(rs.getString("account"));
cus.setPassword(rs.getString("password"));
cus.setCname(rs.getString("cname"));
}
closeConnection();//关闭数据库连接
return cus; //返回这个对象
}
//关闭数据库的方法
public void closeConnection() throws Exception {
conn.close();
}
}
VO-创建Customer.java
package VO;
public class Customer {
private String account;
private String password;
private String cname;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
}
首先创建登录页面,loginForm.jsp,代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'loginForm.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
/*初始化application*/
ArrayList customers = (ArrayList)application.getAttribute("customers");
if(customers==null) {
customers = new ArrayList();
application.setAttribute("customers",customers);
}
ArrayList msgs = (ArrayList)application.getAttribute("msgs");
if(msgs==null) {
msgs = new ArrayList();
application.setAttribute("msgs",msgs);
}
%>
★★欢迎登录在线交流系统★★
<form action="loginAction" name="form1" method="post">
输入账号:<input name="account" type="text"><BR>
输入密码:<input name="password" type="password">
<input type="submit" value="登录" >
</form>
</body>
</html>
创建loginServlet进行登录验证,详细代码如下:
package Servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import DAO.CustomerDao;
import VO.Customer;
@WebServlet("/loginAction")
public class loginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");//防止乱码
//获取登录页面输入框的值
String account = request.getParameter("account");
String password = request.getParameter("password");
//获取session、application对象
HttpSession session=request.getSession();
ServletContext application=request.getServletContext();
CustomerDao cdao = new CustomerDao();
Customer customer = null;
try {
customer = cdao.getCustomerByAccount(account);//调用CustomerDao类中的方法,返回一个对象
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(customer==null || !customer.getPassword().equals(password)){
//当对象为空或者对象的属性密码和输入框输入的密码不一样时,重新跳转登录页面
response.sendRedirect("logon.jsp");
}
else{//输入成功时,把这个对象存入session,另一个页面会获取session
session.setAttribute("customer",customer);
ArrayList customers = (ArrayList)application.getAttribute("customers");//获取对象集合
ArrayList msgs = (ArrayList)application.getAttribute("msgs");//获取消息集合
customers.add(customer);//将这个对象存入customer集合中
msgs.add(customer.getCname() + "上线啦!");//在msgs消息结合当中存入一条消息
response.sendRedirect("charForm.jsp");//密码账号输入正确后,跳转到另一个交流页面
}
}
}
创建交流页面,chatForm.jsp,详细代码如下:
<%@page import="VO.Customer"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'charForm.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
Customer customer = (Customer)session.getAttribute("customer");//从session中获取customer对象
%>
欢迎<%=customer.getCname() %>聊天<br>
<form action="chatAction" name="form1" method="post">
输入聊天信息:<input name="msg" type="text" size="40">
<input type="submit" value="发送" >
</form>
<a href="logoutAction">退出登录</a>
<HR>
<iframe src="msgs.jsp" width="100%" height="80%" frameborder="0"></iframe>
</body>
</html>
创建charServlet进行消息的处理,详细代码如下:
package Servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import VO.Customer;
@WebServlet("/chatAction")
public class charServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取session、application对象
HttpSession session=request.getSession();
ServletContext application=request.getServletContext();
Customer customer = (Customer)session.getAttribute("customer");//从session中获取前面存入的session
request.setCharacterEncoding("UTF-8");
String msg = request.getParameter("msg");//获取输入框里面的消息
ArrayList msgs = (ArrayList)application.getAttribute("msgs");//获取msgs消息集合
if(msg!=null && !msg.equals("")){//当输入框输入的消息不为空时,往消息集合中msgs中添加一条新的消息
msgs.add(customer.getCname() + "说:" + msg);
}
response.sendRedirect("charForm.jsp"); //并再跳转到发消息页面
}
}
创建logoutServlet,进行退出登录处理,详细代码如下:
package Servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import DAO.CustomerDao;
import VO.Customer;
@WebServlet("/logoutAction")
public class loginoutServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取session、application对象
HttpSession session=request.getSession();
ServletContext application=request.getServletContext();
Customer customer = (Customer)session.getAttribute("customer");//获取session里面的对象
ArrayList customers = (ArrayList)application.getAttribute("customers"); //获取在线人数集合
customers.remove(customer);//把在线人数集合中移除这个对象
ArrayList msgs = (ArrayList)application.getAttribute("msgs");//获取到消息集合,并添加一条新的消息
msgs.add(customer.getCname() + "下线啦!");
session.invalidate();//设置session无效,并跳转到登录页面
response.sendRedirect("loginForm.jsp");
}
}
创建显示消息页面,msgs.jsp,详细代码如下:
<%@page import="VO.Customer"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'msgs.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
response.setHeader("Refresh","10"); //设置客户端浏览器每隔10s定期刷新一次
%>
<table width="80%" border="0" align="center">
<tr bgcolor="yellow" align="center">
<td width="75%">消息</td>
<td width="25%">当前在线</td>
</tr>
<tr bgcolor="pink">
<td><%
ArrayList msgs = (ArrayList)application.getAttribute("msgs");//获取消息集合msgs,并打印里面的内容
for(int i=msgs.size()-1;i>=0;i--){
out.println(msgs.get(i) + "<br>");
}
%></td>
<td valign="top"><%
ArrayList customers = (ArrayList)application.getAttribute("customers");//获取人数集合,打印在线人数
for(int i=customers.size()-1;i>=0;i--){
Customer customer = (Customer)customers.get(i);
out.println(customer.getAccount() + "(" + customer.getCname() + ")" + "<br>");
}
%></td>
</tr>
</table>
</body>
</html>
结果:
输入正确的登录信息,点击登录:
进入交流页面:
输入聊天信息,点击发送:
点击退出登录:
数据库表: