要自己做一个聊天室
在这里写下思路
聊天室,首先就是要有信息的收发
也就是收集和显示
信息显示
chatinfo.jsp
<body>
<table align="center" cellspacing="10">
<tr>
<td colspan="3"><textarea rows="20" cols="80">${applicationScope.talks}</textarea>
</td>
</tr>
</table>
</body>
信息收集
index.jsp
<body>
<table align="center">
<tr>
<td colspan="2">
<iframe src="chatinfo.jsp" width="800px" height="460px"></iframe>
</td>
</tr>
<tr>
<td align="center">
<form action="chat.do" method="post">
<input type="text" name="chat" size="60">
<input type="submit" value="发言">
</form>
</td>
</tr>
</table>
</body>
前端搞定了,就要想想怎么写后面
由于不用数据库
发送的信息一定要保存在服务器端
根据其存在时间,我觉得用servletcontext来最好
写个监听器监听servletcontext
public class ContextListener implements ServletContextListener {
public static final String Talks = "talks";
//static final 静态最终啥的玩意 其实就是放在application里的数据
//Talks是服务器内部调用的 ContextListener.Talks
//talks是web前端调用的 applicationScope.talks
private StringBuilder talks = new StringBuilder();
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
sce.getServletContext().removeAttribute(Talks);
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
sce.getServletContext().setAttribute(Talks, talks);
}
}
最后上个servlet就好了
其中的dopost方法
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String talk=req.getParameter("talks");
ServletContext sc = this.getServletContext();
StringBuilder sb = (StringBuilder) sc
.getAttribute(ContextListener.Talks);
sb.append(String.format("说:%s%n", talk));
resp.sendRedirect(req.getContextPath() + "/index.jsp");
}
最后web.xml我就不写了