JavaEE小练习-----------留言板

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();
		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>");


		//获取留言
		request.setCharacterEncoding("utf-8");
		//留言者的信息: ip, time
		String ip = request.getRemoteAddr();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		String time = sdf.format(new Date());
		
		//留言
		String msg = request.getParameter("msg");
		String msgs = (String) getServletContext().getAttribute("msgs");
		if(msg!=null && !msg.trim().equals("")){
			msg = time+"  "+ip+": "+msg;
			if(msgs==null){
				msgs = msg;
			}else{
				msgs = msgs +"<br/>"+ msg;
			}
			getServletContext().setAttribute("msgs", msgs);
			//out.println(msgs);
		}
		if(msgs!=null){
			String div="<div style='border:1px solid red; width:600px;height:300px;overflow:auto'>"+msgs+"</div>";
			out.println(div);
		}
		
		out.println("<hr/>");
		//留言提交的表单
		String form ="<form action='chat' method='post'>" +
					"留言:<input type='text' name='msg'/>"+
					"<input type='submit' value='提交'/>"+
				"</form>";
		out.println(form);
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}


}

展开阅读全文

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