溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java使用Filter實現(xiàn)自動登錄的方法

發(fā)布時間:2020-10-17 08:33:51 來源:腳本之家 閱讀:177 作者:第九種格調(diào)的人生 欄目:編程語言

本文實例為大家分享了java實現(xiàn)自動登錄的具體代碼,供大家參考,具體內(nèi)容如下

  • 當(dāng)你勾選(記住登錄狀態(tài)),用cookie保存用戶名和密碼。不勾選,cookie失效。
  • 所有的頁面都要經(jīng)過autoLoginFilter.java 的過濾器,在這類中,必須要判斷cookies不為null,獲得所有的cookie,得到name為user的cookie,進行用戶名和密碼的驗證,如果不為null,則將user存入session。
  • 在LoginServlet.java中,獲得username和password參數(shù),進行dao驗證,如果不為空,放入seesion中,進行頁面跳轉(zhuǎn)。
  • 創(chuàng)建cookie對象。setpath("/"),表示本應(yīng)用下的所有路徑都能訪問此cookie。
  • 對于已經(jīng)正確登錄的用戶,再次訪問其他頁面必定會再次經(jīng)過autoLoginFilter,這時,判斷當(dāng)前session中的user是否為null,不為null,直接通過。
  • 對于**login.jsp的有關(guān)頁面,不需要經(jīng)過autoLoginFilter。
package com.learning.web.servlet;

import java.io.IOException;
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 com.learning.domain.User;
import com.learning.service.UserService;

@WebServlet("/servlet/loginServlet")
public class LoginServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  String autologin = request.getParameter("autologin");
  
  UserService userService=new UserService();
  User user = userService.findUser(username, password);
  //user不為null,則登錄成功
  if (user!=null) {
  //創(chuàng)建cookie來保存用戶信息
  Cookie cookie=new Cookie("user", user.getUsername()+"&"+user.getPassword());
  cookie.setPath("/");
  //autologin不為null,則記住了登錄狀態(tài)
  if (autologin!=null) {
   cookie.setMaxAge(1*60*60*24);//一天的有效時間
  }
  else {
   cookie.setMaxAge(0);
  }
  response.addCookie(cookie);
  request.getSession().setAttribute("user", user);
  request.getRequestDispatcher("/home.jsp").forward(request, response);
  }else {
  response.sendRedirect(request.getContextPath()+"/homeLogin.jsp");
  }
  
 }

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

}
package com.learning.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.core.Config;

import com.learning.domain.User;
import com.learning.service.UserService;

@WebFilter(urlPatterns="/*",initParams={@WebInitParam(name="autologin",value="login"),@WebInitParam(name="",value="")})
public class AutoFilter implements Filter{

 private FilterConfig filterConfig;
 @Override
 public void destroy() {
 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  throws IOException, ServletException {
 // 轉(zhuǎn)換對象
 HttpServletRequest httpServletRequest = (HttpServletRequest) request;
 HttpServletResponse httpServletResponse = (HttpServletResponse) response;
 // 獲得訪問的路徑
 String uri = httpServletRequest.getRequestURI();
 String contextPath = httpServletRequest.getContextPath();
 uri = uri.substring(contextPath.length() + 1);
 // 獲得初始化參數(shù)
 String login = filterConfig.getInitParameter("autologin");
 System.out.println("直接通行的路徑:"+login);
 // 不包含"login"的路徑就要進行過濾 (xxxlogin.jsp 不需要自動登錄)
 if (!uri.contains(login)) {
  HttpSession session = httpServletRequest.getSession();
  User u = (User) session.getAttribute("user");
  if (u != null) {
  System.out.println("session不為null");
  chain.doFilter(request, response);
  } else {

  // 處理業(yè)務(wù)邏輯
  // 1.獲得cookie 得到User的信息

  String username = "";
  String password = "";
  UserService userService = new UserService();
  Cookie[] cookies = httpServletRequest.getCookies();
  for (int i = 0;cookies!=null&& i < cookies.length; i++) { 
   if ("user".equals(cookies[i].getName())) {
   String string = cookies[i].getValue();
   String[] values = string.split("&");
   username = values[0];
   password = values[1];
   User user = userService.findUser(username, password);
   
   // 不為空則放入session
   if (user != null) {
    System.out.println("自動登錄了");
    httpServletRequest.getSession().setAttribute("user", user);
   }
   }
  }
  }
 }
 // 2.放行
 chain.doFilter(request, response);
 }


 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
 
 this.filterConfig=filterConfig;
 
 }

}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI