java自動登入
阿新 • • 發佈:2018-11-08
溫故而知新。從其他頁面訪問時,如直接訪問index頁面,勾選過自動登入,從session/cookie獲取使用者資訊,沒有勾選,從session中獲取使用者資訊,需要使用filter過濾器
工程結構,採用gradle構建:
public class User { private String username; private String password; public User() { } public User(String username, String password) { this.username = username; this.password = password; } 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; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
import com.yz.filter.LoginFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @description: springboot 登入攔截器配置 * @author: yz * @create: 2018/11/7 18:11 */ @Configuration public class LoginFilterConfig { @Bean public FilterRegistrationBean registrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new LoginFilter()); bean.addUrlPatterns("/*"); return bean; } }
import com.yz.bean.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * @description: 自動登入 * @author: yz * @create: 2018/11/7 16:07 */ @Controller public class UserController { @GetMapping("login") public String login(){ return "login"; } @GetMapping("index") public String index(){ return "index"; } /** * @param request * @param response * @param user * @param auto * @return */ @PostMapping("user_login") public ModelAndView userLogin(HttpServletRequest request,HttpServletResponse response,User user, String auto){ ModelAndView mv = new ModelAndView("redirect:login"); HttpSession session = request.getSession(); // 登入成功 if("admin".equals(user.getUsername()) && "123456".equals(user.getPassword())){ // 存值 session.setAttribute("user",user); // 判斷是否勾選自動登入 if("on".equals(auto)){ System.out.println("有勾選自動登入"); // 將使用者賬號密碼儲存到cookie中 Cookie cookie = new Cookie("account",user.getUsername()+"#"+user.getPassword()); cookie.setMaxAge(60*60*24*7); response.addCookie(cookie); } // 跳轉 mv.setViewName("redirect:index"); return mv; } // 登入失敗 session.setAttribute("msg","使用者名稱或者密碼錯誤!"); // 跳轉到登入頁面,顯示資料 return mv; } }
import com.yz.bean.User; import javax.servlet.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * @description: 登入攔截器 * 單獨使用時,放開註解;使用攔截器配置時注掉註解 * @author: yz * @create: 2018/11/7 17:34 */ //@WebFilter("/*") //@Component //@Order public class LoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } /** * 有登入(session or cookie中有使用者資料)放行,沒有登入就去登入頁面 * @param request * @param response * @param chain * @throws IOException * @throws ServletException */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("來到過濾器了。~!~開始攔截請求"); HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; // 如果是登入有關操作的,不攔截 String path = req.getRequestURI(); System.out.println("path:"+path); if (path.contains("login") || path.endsWith(".ico")){ // 放行 chain.doFilter(request,response); return; } boolean isLogin = false; // 1. session還有效 HttpSession session = req.getSession(); User user = (User) session.getAttribute("user"); if(user != null){ isLogin = true; }else{ // 2.session失效,看cookie // 獲取cookie,遍歷cookie,拿到賬號密碼進行判斷,對了放行,並將使用者物件儲存到session中 Cookie[] cookies = req.getCookies(); if(cookies !=null){ for (Cookie cookie : cookies) { // account=admin#123456; if("account".equals(cookie.getName())){ String[] accountArray = cookie.getValue().split("#"); if("admin".equals(accountArray[0]) && "123456".equals(accountArray[1])){ // 登入成功 , 將使用者物件儲存到session中,以便在會話有效期內訪問,都會放行。 user = new User(accountArray[0], accountArray[1]); req.getSession().setAttribute("user" , user); isLogin = true; } } } } } // 統一對isLogin判斷 if(isLogin){ chain.doFilter(request,response); }else{ resp.sendRedirect("login"); } } @Override public void destroy() { } }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @description: * @author: yz * @create: 2018/11/7 16:07 */ @SpringBootApplication public class LoginApp { public static void main(String [] args){ SpringApplication.run(LoginApp.class , args); } }
index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" > <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <h2>歡迎您,<span th:text="${session.user.username}"></span></h2> </body> </html>
login.html
<!DOCTYPE html> <html xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <h2>登入頁面</h2> <form action="user_login" method="post"> 使用者名稱: <input type="text" name="username"/><br/> 密 碼: <input type="password" name="password"/><br/> <input type="checkbox" name="auto"/>自動登入<br/> <input type="submit" value="登入"/> <!--使用者名稱或者密碼錯誤!!!--> <span style="color:red" th:text="${session.msg}"></span> </form> </body> </html>
application.properties
server.port=8089
build.gradle
plugins { id 'java' } group 'com.yz' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile("org.springframework.boot:spring-boot-starter-web:1.5.10.RELEASE") compile("org.thymeleaf:thymeleaf-spring4:2.1.4.RELEASE") }