JavaWeb實現簡單的自動登錄功能

本文實例為大傢分享瞭JavaWeb實現簡單的自動登錄功能的具體代碼,供大傢參考,具體內容如下

用最近所學的知識點實現自動登錄,主要有:

1、Filter過濾器

2、session & cookie

一、需求分析

二、準備工作

1. 項目目錄

2. 導入相應的jar包

三、代碼實現

1. 搭建環境

1.1 搭建數據庫、數據庫表

數據庫【user】,數據庫表【t_user】

1.2 搭建頁面

登錄頁面【login.jsp】

<body>

 <form action="LoginServlet" method="post">
  賬號:<input type="text" name="username"><br>
  密碼:<input type="password" name="password"><br>
  <input type="checkbox" name="auto_login">自動登錄<br>
  <input type="submit" value="登錄">
 </form>

</body>

首頁【index.jsp】
註意:導入<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>

<body>
 這是首頁,
 <c:if test="${not empty userBean }">
  歡迎你,${userBean.username }
 </c:if>
 <c:if test="${empty userBean }">
  你好,請登錄!
 </c:if>
 
</body>

2. 登錄servlet代碼【LoginServlet.java】

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  try {
   String userName = request.getParameter("username");
   String password = request.getParameter("password");
   String autoLogin = request.getParameter("auto_login");
   
   UserBean user = new UserBean();
   user.setUsername(userName);
   user.setPassword(password);
   
   UserDao dao = new UserDaoImpl();
   UserBean userBean = dao.login(user);
   
   if(userBean != null) {
    //成功瞭,進入首頁
    
    request.getSession().setAttribute("userBean", userBean);
    response.sendRedirect("index.jsp");
   }else {
    //不成功
    request.getRequestDispatcher("login.jsp").forward(request, response);
   }
  } catch (SQLException e) {
   
   e.printStackTrace();
}

3. 過濾器filter代碼【AutoLoginFilter.java】

實現思路:

1、先判斷session是否有效,如果有效,就不用取cookie瞭,直接放行;
2、如果session失效瞭,那麼就取cookie。

a. 取出cookie的值,然後完成登錄;
b. 把這個用戶的值存儲到session中;
c. 放行。

public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  
  try {
   HttpServletRequest request = (HttpServletRequest) req;
   
   //先判斷,session中還有沒有userBean
   UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
   //有---session有效
   if(userBean != null) {
     chain.doFilter(request, response);
   }else {//session失效瞭----看cookie
    
    //1.來請求的時候,先從請求裡面取出cookie,但是cookie裡有很多的key-value
    Cookie[] cookies = request.getCookies();
    //2.從一堆的cookie裡面找出以前給瀏覽器發的那個cookie
    Cookie cookie = CookieUtil.findCookie(cookies, "auto_login");
    
    //第一次登錄
    if(cookie == null) {
     chain.doFilter(request, response);
    }else {//不是第一次登錄
     String value = cookie.getValue();
     String username = value.split("#")[0];
     String password = value.split("#")[1];
     
     //完成登錄
     UserBean user = new UserBean();
     user.setUsername(username);
     user.setPassword(password);

     UserDao dao = new UserDaoImpl();
     userBean = dao.login(user);
     
     //將session值存到域中,方便下一次未過期前還可以用
     request.getSession().setAttribute("userBean", userBean);
     
     chain.doFilter(request, response);
    }    
    
   }

  } catch (Exception e) {
   e.printStackTrace();
   chain.doFilter(req, response);
  }
 }

4. 其他代碼

4.1 方法findCookie()

作用:從一堆的cookie裡面找出以前給瀏覽器發的那個cookie
【CookieUtil.java】

public class CookieUtil {

 public static Cookie findCookie(Cookie[] cookies,String name) {
  if(cookies != null) {
   for(Cookie cookie: cookies) {
    if(name.equals(cookie.getName())) {
     return cookie;
    }
   }
  }
  return null; 
 } 
}

4.2 Bean類

【UserBean.java】

public class UserBean {
 
 private int id;
 private String username;
 private String password;
 
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 
 
}

4.3 UserDao & UserDaoImpl

UserDao.java

public interface UserDao {
 /**
  * 執行登錄,並且返回該用戶所有的信息
  * @param user  執行登錄的用戶信息
  * @return
  */
 UserBean login(UserBean user) throws SQLException;
}

UserDaoImpl.java

public class UserDaoImpl implements UserDao {

 @Override
 public UserBean login(UserBean user) throws SQLException {
  
  QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
  String sql = "select * from t_user where username = ? and password = ?";
  return runner.query(sql, new BeanHandler<UserBean>(UserBean.class),user.getUsername(),user.getPassword());
  
 }

}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: