package com.lh.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lh.bean.Message;
import com.lh.dao.MessageDao;
import com.lh.util.JSONKit;
@WebServlet(name="messageServlet",urlPatterns="/MessageServlet")
public class MessageServlet extends HttpServlet {
	public MessageServlet() {
		super();
	}
	public void destroy() {
		super.destroy(); 
		
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String user = request.getParameter("name");//请求参数中的用户名
		String msg = request.getParameter("message");//消息内容
		Message message = new Message();
		message.setUser(user);//用户名
		message.setMsg(msg);//消息内容
		message.setTime(Calendar.getInstance().getTimeInMillis());//设置时间戳
		response.setContentType("text/xml ; charset=UTF-8");
		PrintWriter out = response.getWriter();
		if(!MessageDao.getInstance().isHasMsgByUserAndText(user, msg)){
			MessageDao.getInstance().saveMsg(message);//保存信息
			int rows = MessageDao.getInstance().selectMsgCount();//查询数据行数
			if(rows>10){//如果数据库表的数据超过10条，进行删除处理
				MessageDao.getInstance().deleteMsg(rows);
			}	
		}
		out.println("<?xml version='1.0' encoding='UTF-8'?>");
		out.println("<response>");
		out.println("<status>1</status>");
		out.println("<time>"+message.getTime()+"</time>");			
		out.println("<message>");
		out.println("<user>"+message.getUser()+"</user>");
		out.println("<text>"+message.getMsg()+"</text>");
		out.println("</message>");			
		out.println("</response>");	
	}
	public void init() throws ServletException {
	
	}

}
