package com.wxpn.tutorial.servlet;

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

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

/**
 * Servlet implementation class for Servlet: BrowseServlet
 */
public class BrowseServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public BrowseServlet() {
		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");
		
		int pagesize = 10;
		String page = request.getParameter("page");
		BBSMsgMgr mgr = new BBSMsgMgr();
		int count = mgr.getCount();// ¼ÇÂ¼×ÜÊ?
		int totalPageNum = count / pagesize;// Âß¼­Ò³Ê?
		// Èç¹û¼ÍÂ¼×ÜÊ?³?ÒÔÃ¿Ò³µÄÏÔÊ¾¸öÊ?,ÓàÊ?´óÓÚ0,ÄÇÃ´
		// Âß¼­Ò³Ê?Ó¦¸ÃÎªÉÌ+1
		if ((count % pagesize) > 0) {
			totalPageNum += 1;
		}
		Collection c = null;
		if (page == null) {
			c = mgr.getAllMessages(pagesize, 1);
		} else {
			c = mgr.getAllMessages(pagesize, Integer.parseInt(page));
		}
		request.setAttribute("totalPageNum", new Integer(totalPageNum));
		request.setAttribute("c", c);
		try {
			request.getRequestDispatcher("/browse.jsp").forward(request,
					response);
		} catch (Throwable t) {
			getServletContext().log(t.getMessage());
		}
	}
}