servlet编写留言板

package servlet1;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ChatServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		
		//获取客户端的ip及时间
		String ip=request.getRemoteAddr();
		SimpleDateFormat date=new SimpleDateFormat("HH-mm-ss");
		String time=date.format(new Date());
		//获取每条留言,并组合起来
		String msg=request.getParameter("text");
		String mmsg="";
		if(msg!=null&&msg.trim().length()>0){
			//System.out.println(msg);
		    mmsg=(String) this.getServletContext().getAttribute("mmsg");
			if(mmsg==null){
				mmsg="";
				//System.out.println("11111111");
			}
			mmsg+=ip+":"+time+"</br>"+msg+"</br>";
			getServletContext().setAttribute("mmsg", mmsg);
		}
		String div="<div style='border:#ff0 solid 1px; width:400px; height:150px; overflow:auto'>";
		//第一次进入留言板,就给该mmsg参数赋"";以便第一条留言显示出来
		String context=(String) getServletContext().getAttribute("mmsg");
		if(context==null){
			context="";
			getServletContext().setAttribute("mmsg", context);
		}
		 div+=context;
		out.print(div+"</div>");
		String chat="<form action='chat'method='post'><input type='text' name='text'/><input type='submit' value='留言'/></form>";
		out.print("<hr/>");
		out.println(chat);
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值