package com.wxpn.tutorial.ec.servlet;

import java.io.IOException;
import java.sql.SQLException;

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

import com.wxpn.tutorial.ec.bean.ECMember;
import com.wxpn.tutorial.ec.bean.ECMemberMgr;

/**
 * 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#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=GB2312");
		String result = "";

		// 获取提交的用户名：
		String strUserName = request.getParameter("logname");
		// 获取提交的密码：
		String strPassword = request.getParameter("logpass");

		String random = request.getParameter("random");
		String random2 = request.getSession().getAttribute("random").toString();
		if (!random.equals(random2)) {
			request.setAttribute("error", "输入的随机码不正确！");
			try {
				request.getRequestDispatcher("/member/login.jsp").forward(
						request, response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
		ECMemberMgr mgr = new ECMemberMgr();
		ECMember memeber = mgr.get(strUserName, strPassword);
		if (memeber != null) {
			// 登录成功时,把strUserName设成session变量UserName
			request.getSession(true).setAttribute("username", strUserName);
			try {
				request.getRequestDispatcher("/index.jsp").forward(request,
						response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		} else {
			// 否则（记录集为空），表明失败：
			request.setAttribute("error", "用户名与密码不匹配,登录失败,请重试！");
			try {
				request.getRequestDispatcher("/member/login.jsp").forward(
						request, response);
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
	}
}