package web;

import pojo.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    public final UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        User user = userService.selectAll(name,password);
        if(user!=null){
            if("1".equals(remember)){
                Cookie username = new Cookie("username", name);
                Cookie password1 = new Cookie("password", password);
                username.setMaxAge(60*60*24*7);
                password1.setMaxAge(60*60*24*7);
                response.addCookie(username);
                response.addCookie(password1);
            }
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            response.sendRedirect("selectAllServlet");
        } else {
            request.setAttribute("name_err_msg","用户名或密码有误");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
