package cn.lijun.web;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.lijun.domain.User1;
import cn.lijun.service.UserService;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
HttpSession se = request.getSession();
//接受数据
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService ser = new UserService();
User1 user=null;
try {
user= ser.login(username,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(user!=null){
//登录尘成功 判断是否勾选
String autoLogin = request.getParameter("autoLogin");
if(autoLogin!=null){
Cookie cookie_username= new Cookie("cookie_username", user.getUsername());
Cookie cookie_password= new Cookie("cookie_password", password);
//设置cookie持续化时间
cookie_username.setMaxAge(60*60*100);
cookie_password.setMaxAge(60*60*100);
// 设置路径
cookie_username.setPath(request.getContextPath());
cookie_password.setPath(request.getContextPath());
//发送cookie
response.addCookie(cookie_username);
response.addCookie(cookie_password);
}
//将登录的用户存储到session域中
se.setAttribute("user", user);
//重定向 地址栏发生变化
response.sendRedirect(request.getContextPath());
}else{
request.setAttribute("loginInfo", "用户名或者密码错误");
//转发 地址栏不变
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}