该案例通过servlet对于Session与Cookie的一些用法所完成
java类
@WebServlet("/loveCaht")
public class chat extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求报文的中文乱码
req.setCharacterEncoding("utf-8");
//获取聊天发言
String ip = req.getRemoteAddr();
//获取ip地址
String chat = req.getParameter("chat");
//根据发言次数,确定聊天表情
HttpSession session = req.getSession();
Integer chatCount = (Integer) session.getAttribute("chat_count");
if (chatCount==null){
chatCount=1;
session.setAttribute("chat_count",chatCount);
}
//根据不同的发言次数,使用不同的表情图片
String face ="";
if(chatCount>=5){
face="<img src='pic/face1.png'/>";
}else if (chatCount>=3){
face="<img src='pic/face2.png'/>";
}else {
face="<img src='pic/face3.png'/>";
}
session.setAttribute("chat_count",chatCount+1);
String chatMsg = String.format("%s%s说:%s[%s]", ip,face,chat, LocalTime.now());
//application应用程序范围存储
ServletContext application = req.getServletContext();
//获取application范围内存存储的聊天记录
List<String> messageList = (List<String>) application.getAttribute("chat_message_list");
if (messageList==null){
messageList =new ArrayList<String>();
application.setAttribute("chat_message_list",messageList);
}
//添加聊天记录
messageList.add(chatMsg);
//使用cookie统计发言次数
//获取Cookie
Cookie[] cookies = req.getCookies();
int total =1;
if (cookies!=null){
//查找知道Cookie
Cookie cookieTotal =null;
for (Cookie cookie : cookies) {
if (cookie.getName().equals("total")){
cookieTotal =cookie;
total=Integer.parseInt(cookie.getValue());
break;
}
}
if (cookieTotal==null){
cookieTotal = new Cookie("total",String.valueOf(total));
}else {
cookieTotal = new Cookie("total",String.valueOf(total+1)) ;
}
cookieTotal.setMaxAge(-1);
resp.addCookie(cookieTotal);
}
//显示聊天记录
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("<h3>总发言次数"+total+"<h3/>");
for (String s : messageList) {
writer.write("<h5>"+s+"<h5/>");
}
//返回发送消息界面按钮
writer.write("<form action=chat.html ><button>返回</button></form>");
writer.flush();
}
}
chat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>激情聊天室</title>
</head>
<body>
<form action="loveCaht" method="post">
<input name="chat"/>
<button>发言</button>
</form>
</body>
</html>
运行展示