package com.xh.web;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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 com.xh.util.DBUtil;
/**
*检查用户名和密码是否正确
*/
@WebServlet(name="LoginCheck",urlPatterns="/check")
public class LoginCheck extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//获取表单数据
String user=req.getParameter("user").trim();
String password=req.getParameter("password").trim();
//把用户名保持在session里面,以实现会话跟踪
HttpSession session=req.getSession();
session.setAttribute("user",user);
//如果用户名密码正确
if(check(user, password)){
//获取记住密码的值 复选框会传递一个(on/off)
String remember=req.getParameter("remember");
//把用户名和密码加起来
String value=user+"&"+password;
//用Cookie保存记住密码和自动登录
Cookie save=new Cookie("remember_pwd",URLEncoder.encode(value, "UTF-8"));//编码
Cookie auto_login=new Cookie("auto_login","auto");
//如果选择记住密码,则把用户名密码保存在cookie中
if("on".equals(remember)){
save.setMaxAge(Integer.MAX_VALUE);
}else{
//不选择,就不保存。关闭浏览器cookie就失效
save.setMaxAge(0);
}
//自动登录的值,复选框会传递一个(on/off)
String autoLogin=req.getParameter("auto_login");
if("on".equals(autoLogin)){
save.setMaxAge(Integer.MAX_VALUE);
auto_login.setMaxAge(Integer.MAX_VALUE);
}else{
auto_login.setMaxAge(0);
}
//保存用户名和密码
resp.addCookie(save);
//自动登录
resp.addCookie(auto_login);
// encodeRedirectURL()方法首先判断session是否失效或者用户没有禁用cookies,如果是直接返回url。如果禁用了cookie则采用url重写方式进行会话跟踪
resp.sendRedirect(resp.encodeRedirectURL("success.jsp"));
}else{
//用户名和密码错误
req.setAttribute("loginIsError","fail");
//转发
this.getServletContext().getRequestDispatcher(resp.encodeRedirectURL("/login.jsp")).forward(req, resp);
//req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
//通过查询数据库,判断输入的用户名和密码是否正确
private boolean check(String username,String password){
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con=DBUtil.getConnection();
String sql="select * from user";
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
if(rs.getString("username").equals(username) && rs.getString("password").equals(password)){
return true;
}
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null!=ps){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
DBUtil.close(con);
}
return false;
}
}