package com.wxpn.tutorial.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;

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

import com.wxpn.tutorial.db.ConnectionPool;
import com.wxpn.tutorial.db.DB;

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

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		String result = "";

		// 获取提交的用户名：
		String strUserName = request.getParameter("txtUserName");
		// 获取提交的密码：
		String strPassword = request.getParameter("txtPassword");
		if ((strUserName == null) || (strUserName.equals(""))
				|| (strUserName.length() > 20)) {
			result = "请输入用户名(不超过20字符)";
			request.setAttribute("error_username", result);
			response.sendRedirect("login2.jsp");
		}
		if ((strPassword == null) || (strPassword.equals(""))
				|| (strPassword.length() > 20)) {
			result = "请输入密码(不超过20字符)";
			request.setAttribute("error_password", result);
			response.sendRedirect("login2.jsp");
		}
		// 创建数据库连接对象：
		ConnectionPool connPool = DB.getConnPool();
		Connection conn = connPool.getConnection();
		Statement stmt = null;
		ResultSet rs = null;

		try {
			// sql语句：
			String sql = "select * from userinfo where username='"
					+ strUserName + "' and userpwd='" + strPassword + "'";
			// 创建数据记录集对象：
			stmt = conn.createStatement();
			// 执行sql语句，返回一个记录集到rs：
			rs = stmt.executeQuery(sql);
			// 如果记录集为非空，表明有相匹配的用户名和密码，登录成功：
			if (rs.next()) {
				// 登录成功时,把strUserName设成session变量UserName
				request.getSession(true).setAttribute("userName", strUserName);

				MessageBoardMgr mgr = new MessageBoardMgr();
				Collection c = mgr.getAllMessages(10, 1);
				request.setAttribute("c", c);
				try {
					request.getRequestDispatcher("/browse.jsp").forward(request,
							response);
				} catch (Throwable t) {
					getServletContext().log(t.getMessage());
				}
			} else {
				// 否则（记录集为空），表明失败：
				request.setAttribute("error","登录失败");
				try {
					request.getRequestDispatcher("/login.jsp").forward(request,
							response);
				} catch (Throwable t) {
					getServletContext().log(t.getMessage());
				}
			}
		} catch (SQLException sqlExc) {
			sqlExc.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接，释放数据库资源：
			try {
				if (rs != null) {
					rs.close();
				}
				if (stmt != null) {
					stmt.close();
				}
				connPool.freeConnection(conn);
			} catch (SQLException sqlExc) {
				sqlExc.printStackTrace();
			}
		}
	}
}