1. 實作思路
1. 登入頁面
在頁面輸入使用者名密碼,送出到登入邏輯頁面
2. 登入邏輯頁面
調資料庫判斷使用者名密碼的正确性
正确:跳到聊天室界面并且存儲使用者名
錯誤:傳回登入界面
3.聊天室界面
1.拿到存儲的使用者名
2.将發送的消息傳到聊天室邏輯頁面
3.拿到application中的值将application中的值展示到聊天記錄文本域中
4.聊天室邏輯頁面
将傳過來的消息用application域對象存儲起來
擷取之前application中的值
2、邏輯思路圖
3、執行個體代碼:
Login.jsp 登入頁面
<form action="loginOpreation.jsp" method="post">
使用者名:<input type="text" name="uname" ><br/>
密碼:<input type="password" name="upass" ><br/>
<input type="submit" value="登入" >
</form>
LoginOperation.jsp 登入邏輯頁面
<!-- 登入邏輯頁面 -->
<%
String uname=request.getParameter("uname");
String upass=request.getParameter("upass");
BuserDao bd=new BuserDao();
Buser b=new Buser(uname,upass);
if(bd.Login(b)){
session.setAttribute("uname", uname);
session.setAttribute("upass", upass);
request.getRequestDispatcher("chatRoom.jsp").forward(request, response);
}else{
response.sendRedirect("login.jsp");
}
chatRoom 聊天室
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- <meta http-equiv="refresh" content="5;url=chatRoom.jsp"> -->
<title>Insert title here</title>
<script type="text/javascript">
function $(o){
return document.getElementById(o);
}
function s(){
var str=$("input").value;
if(str==""){
alert("輸入框不能為空,請輸入!");
}else{
document.location="chatRoomOpreation.jsp?sendInfo="+str;;
}
}
</script>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
//擷取application中的值
String all="";
Object o=application.getAttribute("all");
if(o!=null){
all=o.toString();
}
%>
<h1>多人聊天室</h1>
你好:<%=session.getAttribute("uname") %>
<form method="post">
<div style="width:1000px; height:350px; overflow:auto; border:1px solid #000000;">
<%=all
%>
</div>
<br/>
<!-- 第二種,輸入框 -->
<input type="text" name="sendInfo" id="input"/>
<!-- 第二種,富文本編輯器 -->
<!-- <textarea rows="10" cols="10" name="sendInfo" id="1"></textarea>
<script type="text/javascript">
CKEDITOR.replace("sendInfo");
</script> -->
<input type="button" value="發送" οnclick="s()">
</form>
</body>
chatRoomOpreation.jsp 聊天室邏輯頁面
<!-- 聊天業務邏輯頁面 -->
<%
request.setCharacterEncoding("UTF-8");
//擷取使用者名,使用者名要拼接在發送的消息的前面
String uname=session.getAttribute("uname").toString();
//擷取application中記錄
String all="";
Object o=application.getAttribute("all");
if(o!=null){
all=o.toString();
}
//1.擷取要發送的内容
String sendInfo=request.getParameter("sendInfo").toString();
if(sendInfo==null){
request.setAttribute("flage","YES");
request.getRequestDispatcher("chatRoom.jsp").forward(request, response);
//response.sendRedirect("chatRoom.jsp");
}
//将内容拼接
if("admin".equals(uname)){
all=all+"<br/>"+uname+":<span style='color:red'>"+sendInfo+"</span>";
}
else if("sa".equals(uname)){
all=all+"<br/>"+uname+":<span style='color:green'>"+sendInfo+"</span>";
}
//富文本編輯器内容拼接
// all=all+"\r\n"+uname+":"+sendInfo;
//2.将擷取的内容存到application中
application.setAttribute("all",all);
//3.跳轉到chatRoom.jsp頁面(重定向)
response.sendRedirect("chatRoom.jsp");
%>