package com.wxpn.tutorial.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: ReadServlet
 */
public class ReadServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public ReadServlet() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("text/html;charset=UTF-8");
		String _id = request.getParameter("id");
		if (_id == null) {
			request.setAttribute("error", "<h1>ÔÄ¶ÁÁôÑÔÊ§°Ü!</h1>");
			try {
				request.getRequestDispatcher("/error.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		} else {
			int id = Integer.parseInt(_id);
			BBSMsgMgr mgr = new BBSMsgMgr();
			mgr.read(id);

			Collection c = mgr.getChildren(id);
			if (c == null) {
				request.setAttribute("error", "<h1>²»´æÔÚ¸ÃÁôÑÔ!</h1>");
				try {
					request.getRequestDispatcher("/error.jsp").forward(request,
							response);
				} catch (Throwable t) {
					getServletContext().log(t.getMessage());
				}
			} else {
				request.setAttribute("c", c);
				try {
					request.getRequestDispatcher("/read.jsp").forward(request,
							response);
				} catch (Throwable t) {
					getServletContext().log(t.getMessage());
				}
			}
		}
	}
}