servlet编写留言板

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_18950313/article/details/49782885
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();
	}

}

展开阅读全文

没有更多推荐了,返回首页