简易聊天室KunKunChatroom
简易聊天室KunKunChatroom
一、实现原理
1、页面:不断检查触发事件windows.setInterval(触发函数,毫秒数)
页面不停执行检查是否在线、发言、踢下线
重定位主页面 window.location=" "
重定位并且发送请求window.location.href="${pageContext.request.contextPath}/user?method=exit";
$("#form1").serialize()实现表单内容全部发送
2、逻辑
通过不断检查ServletContext范围内的session和使session失效,实现检查用户是否在线和踢下线
二、具体
1、BaseServlet完成任务分发
(1)获取request中的method方法名称
HttpServletRequest.getParamter("method")
(2)获取当前类对象
Class c=this.getClass()
(3)通过方法名称获取方法的反射对象
Method m=c.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class)
(4)反射方法目标方法
String result = (String)m.invoke(this,req,res)
(5)通过返回值完成请求转发
req.getRequestDispatcher(result).forward(req,res)
2、UserServlet用户管理
(1)从session中获取用户对象
User existUser=(User)req.getSession().getAttribute("existUser")
(2)返回页面值
resp.getWriter().println("1");
(3)返回session对象并失效
HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect(request.getContextPath()+"/index.jsp");
(4)发言时间
new Date().toLocaleString()
(5)发言内容放置于ServletContext中,在整个Servlet中存在
ServletContext application = getServletContext();
String sourceMessage = (String) application.getAttribute("message");
application.setAttribute("message", sourceMessage);
(6)Integer转换成int
int id = Integer.parseInt(req.getParameter("id"));
(7)将map对象封装转换成对象
BeanUtils.populate(user, map);
3、UserDaoImpl数据库操作
(1)//获取数据库
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
(2)数据库操作语句
String sql = "select * from user where username = ? and password = ?";
(3)传参
//通过用户密码判断是否可以查询到
existUser = queryRunner.query(sql, new BeanHandler<User>(User.class),
user.getUsername(),user.getPassword());
4、JDBCUtils工具类连接数据库
(1)代码
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
// 获得连接池:
public static DataSource getDataSource(){
return dataSource;
}
// 获得连接
public static Connection getConnection() {
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
(2)c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///kunkunchatroom</property>
<property name="user">root</property>
<property name="password">admin</property>
</default-config>
</c3p0-config>
5、listener实现ServletContextListener
(1)
//自动启动
public void contextInitialized(ServletContextEvent sce) {
Map<User,HttpSession> userMap = new HashMap<User,HttpSession>();
sce.getServletContext().setAttribute("userMap", userMap);
}
6、虚拟路径
${ pageContext.request.contextPath }