最近在做一个java网络开发的一个小练习,简易网页聊天室:
1)是用oracle做数据库的,存有两张表
a. chatuser表,保存登陆用户的
SQL> desc chatuser
Name Type Nullable Default Comments
---------- ------------ -------- ------- --------
USERNAME VARCHAR2(25)
LOGINTIME TIMESTAMP(6) Y
LOGOFFTIME TIMESTAMP(6) Y
LOGINSTATE NUMBER(5) Y
b.UserChatContent表,保存聊天记录的
SQL> desc UserChatContent
Name Type Nullable Default Comments
----------- -------------- -------- ------- --------
USERNAME VARCHAR2(25)
CHATCONTENT VARCHAR2(1000) Y
SPEAKTIME TIMESTAMP(6) Y
jdbc工具包用了董工封装的dataSource
2)java类:
a.entity:(5个)
po类:ChatUser,UserChatContent (对应数据库两张表)
vo类:ChatUserVo,UserChatContentVo (继承po类)
其他:UserName (用来查询数据库表时,只查用户名用的)
b.logic:(2个)
Checkpolice (用来定时检查在线用户是否超时没操作的实现runnable借口的线程类)
DaoChat (处理与数据库的一系列操作,如:查询在线用户,登录,退出,查聊天记录等)
3)jsp页面:(5 个,我是放在意个chat3的文件夹里)
a. login.jsp 登录页面,也处理重复登录,退出事务
b. index.jsp 主页面,用frame框架,嵌套了聊天记录,在线用户,发言三大窗口
c. content.jsp 显示当天聊天记录
d. users.jsp 显示在线用户
e. sayWordBox.jsp 发言窗口,退出按钮...
主要代码:
java类:
entity类 5个
-----------------ChatUser 类----------------------
package com.entity.po;
import java.sql.Timestamp;
public class ChatUser {
private String userName;
private Timestamp loginTime;
private Timestamp logoffTime;
private Integer loginState;//1为登录,0为未登录
public ChatUser() {
super();
}
public ChatUser(String userName) {
super();
this.userName = userName;
}
public ChatUser(String userName, Timestamp loginTime) {
super();
this.userName = userName;
this.loginTime = loginTime;
}
public ChatUser(String userName, Timestamp loginTime, Timestamp logoffTime,
Integer loginState) {
super();
this.userName = userName;
this.loginTime = loginTime;
this.logoffTime = logoffTime;
this.loginState = loginState;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Timestamp getLoginTime() {
return loginTime;
}
public void setLoginTime(Timestamp loginTime) {
this.loginTime = loginTime;
}
public Timestamp getLogoffTime() {
return logoffTime;
}
public void setLogoffTime(Timestamp logoffTime) {
this.logoffTime = logoffTime;
}
public Integer getLoginState() {
return loginState;
}
public void setLoginState(Integer loginState) {
this.loginState = loginState;
}
}
------------------------end-------------------------
-----------------UserChatContent 类----------------------
package com.entity.po;
import java.sql.Timestamp;
public class UserChatContent {
private String userName;
private String chatContent;
private Timestamp speakTime;
public UserChatContent() {
super();
}
public UserChatContent(String userName, String chatContent) {
super();
this.userName = userName;
this.chatContent = chatContent;
this.speakTime = new Timestamp( System.currentTimeMillis() );
}
public UserChatContent(String userName, String chatContent, Timestamp speakTime) {
super();
this.userName = userName;
this.chatContent = chatContent;
this.speakTime = speakTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getChatContent() {
return chatContent;
}
public void setChatContent(String chatContent) {
this.chatContent = chatContent;
}
public Timestamp getSpeakTime() {
return speakTime;
}
public void setSpeakTime(Timestamp speakTime) {
this.speakTime = speakTime;
}
}
------------------------end-------------------------
-----------------ChatUserVo 类----------------------
package com.entity.vo;
import java.sql.Timestamp;
import com.entity.po.ChatUser;
public class ChatUserVo extends ChatUser{
public ChatUserVo() {
super();
// TODO Auto-generated constructor stub
}
public ChatUserVo(String userName, Timestamp loginTime,
Timestamp logoffTime, Integer loginState) {
super(userName, loginTime, logoffTime, loginState);
// TODO Auto-generated constructor stub
}
public ChatUserVo(String userName, Timestamp loginTime) {
super(userName, loginTime);
// TODO Auto-generated constructor stub
}
public ChatUserVo(String userName) {
super(userName);
// TODO Auto-generated constructor stub
}
}
------------------------end-------------------------
-----------------UserChatContentVo 类----------------------
package com.entity.vo;
import java.sql.Timestamp;
import com.entity.po.UserChatContent;
public class UserChatContentVo extends UserChatContent{
public UserChatContentVo() {
super();
// TODO Auto-generated constructor stub
}
public UserChatContentVo(String userName, String chatContent, Timestamp speakTime) {
super(userName, chatContent, speakTime);
// TODO Auto-generated constructor stub
}
public UserChatContentVo(String userName, String chatContent) {
super(userName, chatContent);
// TODO Auto-generated constructor stub
}
}
------------------------end-------------------------
-----------------UserChatContent 类----------------------
package com.entity;
public class UserName {
private String userName;
public UserName() {
super();
}
public UserName(String userName) {
super();
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
------------------------end-------------------------
logic类 2个
-----------------DaoChat 类----------------------
package com.logic;
import java.sql.Timestamp;
import java.util.List;
import com.entity.UserName;
import com.entity.po.ChatUser;
import com.entity.po.UserChatContent;
import com.entity.vo.ChatUserVo;
import com.entity.vo.UserChatContentVo;
import com.sql.RemoteExecute;
public class DaoChat {
@SuppressWarnings("unchecked")
public boolean islogin(String userName){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return false;
}
RemoteExecute remoteExecute = new RemoteExecute();
String sql = "select userName from ChatUser where userName = '" + userName + "' and loginState = 1";
List<UserName> list = (List<UserName>)remoteExecute.query(sql, null, UserName.class);
closeRe(remoteExecute);
if( list != null && list.size() != 0){
return true;
}
return false;
}
@SuppressWarnings("unchecked")
private boolean islogin(String userName,RemoteExecute remoteExecute){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return false;
}
String sql = "select userName from ChatUser where userName = '" + userName + "' and loginState = 1";
List<UserName> list = (List<UserName>)remoteExecute.query(sql, null, UserName.class);
if( list != null && list.size() != 0){
return true;
}
return false;
}
@SuppressWarnings({ "unchecked", "deprecation" })
public boolean login(String userName){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return false;
}
RemoteExecute remoteExecute = new RemoteExecute();
String sql = "select * from ChatUser where userName = '" + userName + "'";//检查用户名是否已经登录过...如果登录过,则判断是否在线
List<ChatUserVo> list = (List<ChatUserVo>)remoteExecute.query(sql, null, ChatUserVo.class);
if( list != null && list.size() != 0){//已经登录过...
if( list.get(0).getLoginState() == 1 ){//在线
//System.out.println("用户列的登陆情况:" + list.get(0).getLoginState());
closeRe(remoteExecute);
return false;
}else{//没在线
Timestamp timestamp = new Timestamp( System.currentTimeMillis() );
//(timestamp '2011-9-10 14:01:00')
sql = "update ChatUser set loginState = 1, loginTime = (timestamp '" + timestamp.toLocaleString() + "') where userName = '" + userName + "'";
remoteExecute.excute(sql, null);
closeRe(remoteExecute);
return true;
}//else
}else{//没登录过的,进行登录,并注册
ChatUserVo user = new ChatUserVo();
user.setUserName(userName);
user.setLoginTime(new Timestamp( System.currentTimeMillis() ));
user.setLoginState(1);
remoteExecute.save(user, ChatUser.class, "userName");
closeRe(remoteExecute);
return true;
}//else
}//login
private void closeRe(RemoteExecute remoteExecute) {
if( remoteExecute == null )return;
remoteExecute.commit();
remoteExecute.close();
remoteExecute = null;
}
public void checkLoginUsers() {
CheckPolice checkPolice = new CheckPolice();
Thread cheThread = new Thread(checkPolice,"checkPolice");
cheThread.start();
}
@SuppressWarnings("deprecation")
public boolean logoff(String userName){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return false;
}
RemoteExecute remoteExecute = new RemoteExecute();
Timestamp timestamp = new Timestamp( System.currentTimeMillis() );
String sql = "update ChatUser set loginState = 0, logoffTime = (timestamp '" + timestamp.toLocaleString() + "') where userName = '" + userName + "'";
int i = remoteExecute.excuteUpdate(sql, null);
closeRe(remoteExecute);
if( i >= 1 )
return true;
return false;
}
public boolean speak(String userName,String speakContent){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return false;
}
RemoteExecute remoteExecute = new RemoteExecute();
if( !this.islogin(userName, remoteExecute) ){
return false;
}
UserChatContentVo userChatContentVo = new UserChatContentVo();
userChatContentVo.setUserName(userName);
userChatContentVo.setSpeakTime(new Timestamp( System.currentTimeMillis() ));
userChatContentVo.setChatContent(speakContent);
remoteExecute.save(userChatContentVo, UserChatContent.class, "userName");
closeRe(remoteExecute);
return true;
}
@SuppressWarnings({ "unchecked", "deprecation" })
public List<UserChatContentVo> getAllSpeakContentList(String userName){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return null;
}
String sql = "select * from UserChatContent order by speakTime";
RemoteExecute remoteExecute = new RemoteExecute();
if( !this.islogin(userName, remoteExecute) ){
return null;
}
List<UserChatContentVo> slist = (List<UserChatContentVo>)remoteExecute.query(sql, null, UserChatContentVo.class);
closeRe(remoteExecute);
return slist;
}
@SuppressWarnings({ "unchecked", "deprecation" })
public List<UserChatContentVo> getTodaySpeakContentList(String userName){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return null;
}
RemoteExecute remoteExecute = new RemoteExecute();
if( !this.islogin(userName, remoteExecute) ){
return null;
}
Timestamp nowt = new Timestamp( System.currentTimeMillis() );
int year = nowt.getYear() + 1900;
int month = nowt.getMonth() + 1;
int day = nowt.getDate();
String nowtString = String.valueOf(year) + String.valueOf(month) + String.valueOf(day);
//System.out.println(nowtString);
String sql = "select * from UserChatContent where to_number(extract(YEAR from speakTime)||extract(MONTH from speakTime)||extract(DAY from speakTime)) = '" + nowtString + "' order by speakTime";
List<UserChatContentVo> slist = (List<UserChatContentVo>)remoteExecute.query(sql, null, UserChatContentVo.class);
closeRe(remoteExecute);
return slist;
}
@SuppressWarnings("unchecked")
public List<ChatUserVo> getAllUserList(String userName){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return null;
}
String sql = "select * from ChatUser order by LoginTime";
RemoteExecute remoteExecute = new RemoteExecute();
if( !this.islogin(userName, remoteExecute) ){
return null;
}
List<ChatUserVo> list = (List<ChatUserVo>)remoteExecute.query(sql, null, ChatUserVo.class);
closeRe(remoteExecute);
return list;
}
@SuppressWarnings("unchecked")
public List<UserName> getUserListOfLogin(String userName){
if( userName == null || "".equals(userName)){
System.out.println("你传的参数不符合条件...");
return null;
}
String sql = "select userName from ChatUser where loginState = 1 order by LoginTime";
RemoteExecute remoteExecute = new RemoteExecute();
if( !this.islogin(userName, remoteExecute) ){
return null;
}
List<UserName> list = (List<UserName>)remoteExecute.query(sql, null, UserName.class);
closeRe(remoteExecute);
return list;
}
}
------------------------end-------------------------
-----------------CheckPolice 类----------------------
package com.logic;
import java.sql.Timestamp;
import java.util.List;
import com.entity.UserName;
import com.sql.RemoteExecute;
public class CheckPolice implements Runnable{
@SuppressWarnings("deprecation")
public void run() {
Timestamp nowt = null;
try {
nowt = new Timestamp( System.currentTimeMillis() );
String timeString = String.valueOf(nowt.getYear() + 1900)
+ String.valueOf(nowt.getMonth() + 1)
+ String.valueOf(nowt.getDate())
+ String.valueOf(nowt.getHours()) + nowt.getMinutes();
nowt = null;
System.out.println("我是警察..." + timeString);
Thread.sleep( 100000 );
System.out.println("警察开始查牌...");
this.checkChatUser(timeString);
timeString = null;
this.run();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//run
@SuppressWarnings({ "unchecked", "deprecation" })
public void checkChatUser(String timeString){
try {
Integer.parseInt(timeString);
} catch (NumberFormatException e) {
System.out.println("你传的参数不符合条件...");
return;
}
RemoteExecute remoteExecute = new RemoteExecute();
String sqlForChat = "select distinct userName from UserChatContent " +
"where to_number(extract(YEAR from speakTime)||" +
"extract(MONTH from speakTime)||" +
"extract(DAY from speakTime)||" +
"extract(hour from speakTime)||" +
"extract(minute from speakTime)) >= " + timeString;
String sqlForUser = "select userName from ChatUser where loginState = 1";
List<UserName> list = (List<UserName>)remoteExecute.query(//获得十分钟内有说话的用户的用户名
sqlForChat, null, UserName.class);
List<UserName> userList = (List<UserName>)remoteExecute.query(//获得登录用户的用户名
sqlForUser, null, UserName.class);
boolean flag = true;
String sqlForLoginoff = null;
Timestamp timestamp = new Timestamp( System.currentTimeMillis() );
for(UserName user:userList){//把超出规定时间,没有说话的用户,退出登录
flag = true;//先假设用户已经超出时间了
for(UserName uccv:list){
if( user.getUserName().equals( uccv.getUserName() ) ){//没有超出时间的用户
flag = false;
break;
}
}//for
if( flag == true ){//超出时间的用户退出登录...
sqlForLoginoff = "update ChatUser set loginState = 0, logoffTime = (timestamp '" + timestamp.toLocaleString() + "') where userName = '" + user.getUserName() + "'";
remoteExecute.excuteUpdate(sqlForLoginoff, null);
}//if
}//for
remoteExecute.commit();
remoteExecute.close();
remoteExecute = null;
}//checkChatUser
}
------------------------end-------------------------
jsp 页面 5 个
-----------------login.jsp 页面----------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.logic.DaoChat"%>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
if( "false".equals( request.getParameter("state") ) )
out.println("<font color='red' >用户名已经登陆...</font>");
//out.println("yy"+request.getParameter("logState"));
if( "logoff".equals(request.getParameter("logState")) ){
String userName = null;
if( session.getAttribute("userName") != null ){
DaoChat daoChat = new DaoChat();
userName = session.getAttribute("userName").toString().trim();
daoChat.logoff(userName);
session.removeAttribute("userName");
out.println("<font color='red' >退出成功...</font>");
}//if
userName = null;
}//if
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>聊天室登录...</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>
<br>
<form action="chat3/index.jsp" method="post">
用户名:<input type="text" name="userName"/><input type="submit" value="登录..." />
</form>
</body>
</html>
------------------------end-------------------------
-----------------index.jsp 页面----------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.logic.DaoChat"%>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String userName = null;
DaoChat daoChat =new DaoChat();
if( application.getAttribute("checkPolice") == null ){
daoChat.checkLoginUsers();
application.setAttribute("checkPolice","true");
}
if( session.getAttribute("userName") == null ){
if( request.getParameter("userName") != null )
userName = request.getParameter("userName").trim();
if( userName == null || "".equals(userName)) userName = "无名" + System.currentTimeMillis();
userName = userName.trim();
boolean test = daoChat.login(userName);
if( !test ){//已经在线
//System.out.println(test);
//System.out.println(!test);
response.sendRedirect("login.jsp?state=false");
return;
}
session.setAttribute("userName",userName);
}else if( !daoChat.islogin(userName) ){
session.removeAttribute("userName");
response.sendRedirect("login.jsp");
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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>
<frameset rows="80%,*">
<frameset cols="80%,*">
<frame src="/testWeb/chat3/content.jsp" />
<frame src="/testWeb/chat3/users.jsp" />
</frameset>
<frame src="/testWeb/chat3/sayWordBox.jsp" />
</frameset>
</html>
------------------------end-------------------------
-----------------content.jsp 页面----------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.entity.vo.UserChatContentVo"%>
<%@page import="com.logic.DaoChat"%>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
DaoChat daoChat =new DaoChat();
String chatContent = "";
List<UserChatContentVo> userChatContentList = null;
String userName = null;
if( session.getAttribute("userName") == null ){
;
}else{
userName = session.getAttribute("userName").toString().trim();
}
userChatContentList = daoChat.getTodaySpeakContentList(userName);
if( userChatContentList != null ){
for( UserChatContentVo uc:userChatContentList){
chatContent = chatContent + uc.getUserName() + "--"
+ uc.getSpeakTime().toLocaleString()
+ " 说:" + uc.getChatContent() + "\n";
}
}else{
out.println("<font color='red' >你过久没有操作,导致登陆过时失效...请重新登陆</font>");
session.removeAttribute("userName");
return;
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'content.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">
<Meta http-equiv="Refresh" Content="2; Url=content.jsp">
<!--javascript:top.location.href='login.jsp';
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<textarea name="chatContent" rows="30" cols="108" ><%=chatContent %></textarea>
</body>
</html>
------------------------end-------------------------
-----------------users.jsp 页面----------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.logic.DaoChat"%>
<%@page import="com.entity.UserName"%>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
DaoChat daoChat =new DaoChat();
String users = "";
List<UserName> userList = null;
String userName = null;
if( session.getAttribute("userName") == null ){
return;
}else{
userName = session.getAttribute("userName").toString().trim();
}
userList = daoChat.getUserListOfLogin(userName);
if( userList != null ){
for( UserName us:userList){
users = users + us.getUserName() + "\n";
}
}else{
out.println("<font color='red' >你过久没有操作,导致登陆过时失效...请重新登陆</font>");
session.removeAttribute("userName");
return;
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>users--3</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">
<Meta http-equiv="Refresh" Content="2; Url=users.jsp">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<textarea name="users" rows="30" cols="18" ><%=users %></textarea>
</body>
</html>
------------------------end-------------------------
-----------------sayWordBox.jsp 页面----------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.logic.DaoChat"%>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String userName = null;
String userContent = "";
DaoChat daoChat =new DaoChat();
userContent = request.getParameter("userContent");
if( session.getAttribute("userName") == null ){
return;
}else{
userName = session.getAttribute("userName").toString();
}
userName = userName.trim();
if( userContent != null && !"".equals( userContent ) ){//建立一个新的聊天记录对象
boolean test = daoChat.speak(userName,userContent);
if( test == false ){
out.println("<font color='red' >你过久没有操作,导致登陆过时失效...请重新登陆</font>");
session.removeAttribute("userName");
return;
}
}//if
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'sayWordBox.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>
<br>
<form action="/testWeb/chat3/sayWordBox.jsp" method="post">
<input name="userContent" type="text" size="108" style="width:700px;font-size:32px" />
<input name="subm" type="submit" value="发言" />
</form>
<form name="logoff" action="chat3/login.jsp" method="post" target="_top">
<input name="logState" type="hidden" value="logoff" />
欢迎 <%=userName %> 来到SeeHope聊天室...<input type="submit" value="退出" />
</form>
</body>
</html>
------------------------end-------------------------