1. 程式人生 > >登入登出,自動登入

登入登出,自動登入

UserLoggingDao:


public interface UserLoggingDao {

	// 根據賬號獲取使用者資訊
		User findByAccount(String account);
}

UserLoggingDaoImpl:



public class UserLoggingDaoImpl implements UserLoggingDao{

	@Override
	public User findByAccount(String account) {
		
		//定義一個User
		User user = null;
		
		try {
			//連線資料庫
			Connection conn = DBUtils.getConnection();
			
			//輸入sql語句
			String sql = "SELECT id, password FROM user WHERE account=?;";
			
			PreparedStatement ps = conn.prepareStatement(sql);
			
			//新增?中的資料
			ps.setString(1, account);
			
			//執行
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()) {
				
				//獲取資料庫中搜索的值
				Integer id = rs.getInt(1);
				String Password = rs.getString(2);
				
				//新增資料到user
				user = new User();

				user.setId(id);
				user.setAccount(account);
				user.setPassword(Password);
			}
			
			//關閉流
			rs.close();
			ps.close();
			conn.close();
			
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		//返回user
		return user;
	}

}

UserLoggingService:


public interface UserLoggingService {

	//根據account和password獲取登入結果
	boolean login(String account,String password);
	
}

UserLoggingServiceImpl:



public class UserLoggingServiceImpl implements UserLoggingService {

	private UserLoggingDao userLoggingDao = new UserLoggingDaoImpl();
	
	@Override
	public boolean login(String account, String password) {
		
		User user = userLoggingDao.findByAccount(account);
		
		if(user == null){
			
			//賬號不存在
			return false;
		}
		
		if (!user.getPassword().equals(password)) { 
			
			// 密碼不相同
			return false;
		}
		
		//密碼一致
		return true;
	}

}

LoginServlet:


/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserLoggingService userLoggingService = new UserLoggingServiceImpl();
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//接收網頁的資料
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		
		//如果相應資料有中文 還需要設定相應頭才能正確顯示
		response.setHeader("content-Type", "text/html;charset=utf-8");
				
		if(userLoggingService.login(account, password)){
			
			// 把賬號存入 session
			HttpSession session = request.getSession(); 
			session.setAttribute("account", account); 
			
			// 自動登入第 1 步:登入成功後把賬號和密碼傳送給瀏覽器,儲存在 cookie 中
			Cookie accountCookie = new Cookie("account", account);
			Cookie passwordCookie = new Cookie("password", password);
						
			accountCookie.setMaxAge(3600);
			passwordCookie.setMaxAge(3600);
						
			// 把 cookie 新增到 response 中,傳送給 client。
			// 如果 client 是瀏覽器,會自動儲存接收到的 cookie
			response.addCookie(accountCookie);
			response.addCookie(passwordCookie);
			
			//登陸成功 重定向到 admin
			response.sendRedirect("admin.jsp");
			
		}else{
			
			//登入失敗,轉發請求到login
			request.setAttribute("errorMessage", "檢查一下賬號和密碼,再輸入一下哦~");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			
		}
	}

}

LogoutServlet:


/**
 * Servlet implementation class LogoutServlet
 */
public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 清除 session 中儲存的資料
		HttpSession session = request.getSession(); 
		//直接銷燬
		session.invalidate();
		
		// 重定向到 login.jsp
		response.sendRedirect(request.getContextPath() + "/login.jsp");
	}

}

IndexServlet:


/**
 * Servlet implementation class IndexServlet
 */
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserLoggingService userLoggingService = new UserLoggingServiceImpl();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 自動登入第 2 步:獲取 request 的 cookie 中是 account 和 password 的值	
		String cookieAccount = null;  // cookie 中的密碼
		String cookiePassword = null; // cookie 中的賬號
		
		// 獲取請求中的所有 cookie 資訊
		Cookie[] cookies = request.getCookies();
		
		// 如果 cookies 不為 null,遍歷陣列,找出 account 和 password
		if (cookies != null) {
			
			for (Cookie cookie : cookies) {
				
				// 根據 key 尋找 account 和 password 的 value
				String key = cookie.getName();
				
				if ("account".equals(key)) {
					
					cookieAccount = cookie.getValue();
				}else if ("password".equals(key)) {
					
					cookiePassword = cookie.getValue();
				}
			}
		}

		// 如果 cookie 有賬號和密碼,進行登入驗證
		if (cookieAccount != null && cookiePassword != null) {
			
			if (userLoggingService.login(cookieAccount, cookiePassword)) {
				
				// 把賬號存入 session,那麼其它 jsp 和 servlet 都可以使用了
				HttpSession session = request.getSession(); // 獲取當前 client 對應的 session
				session.setAttribute("account", cookieAccount); // 資料以 key=value 的形式存入 session 中
				
				// 登入成功,重定向到 list.jsp
				response.sendRedirect(request.getContextPath() + "/admin.jsp");
			}else {
				
				// 追加錯誤資訊,轉發給 login.jsp 重新輸入賬號密碼
				request.setAttribute("errorMessage", "請重新登入喲!");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
		}else {
			// 如果沒有,重定向到 login.jsp 進行手動登入
			response.sendRedirect(request.getContextPath() + "/login.jsp");
		}
		
	}

}