利用cookie, session 和Filter實現簡單的自動登陸
阿新 • • 發佈:2019-02-17
需求:
1.當用戶請求主頁面時如果沒有登陸轉發到登陸介面
2.將使用者資訊存入到session中,賬號密碼存入cookie。
3.利用Filter過濾全域性檢測cookie,呼叫service實現登陸。
密碼加密,登陸,註冊頁面不能自動登陸
jsp:
主頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
</head>
<body>
<c:if test="${sessionScope.c==null}">
<script type="text/javascript">
location.href = '${pageContext.request.contextPath}/login.jsp';
</script>
</c:if>
<h5>當前使用者:${sessionScope.c.name}</h5 >
</body>
</html>
登陸頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false"%>
<html>
<head>
</head>
<body>
<hr>
${error}
<form action="${pageContext.request.contextPath}/login" method="post">
使用者姓名:<input type="text" name="username"><br>
使用者密碼:<input type="password" name="password"><br> <input type="checkbox" name="autoLogin"value="is">自動登陸<br>
<input type="submit" value="登陸">
</form>
</body>
</html>
登陸servlet
package com.kick.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.ServletException;
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.kick.domain.Customer;
import com.lick.service.KickService;
public class LoginServlet extends HttpServlet {
public void destroy() {
super.destroy();
}
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
String autoLogin = request.getParameter("autoLogin");
if (username != null) {
KickService service = new KickService();//業務層登陸方法 不貼了
try {
Customer c = service.queryCustomer(username, password);
if (c == null) {
request.setAttribute("error", "使用者名稱或密碼錯誤");
request.getRequestDispatcher("/login.jsp").forward(request,
response);
} else {
// 登陸成功 將使用者存入到session中
request.getSession().setAttribute("c", c);
//判斷是否勾選,自動登陸將使用者名稱和密碼存入到cookie中
if("is".equals(autoLogin)){
Cookie cookie=new Cookie("autoLogin",username+","+password);
cookie.setPath("/");
cookie.setMaxAge(60*60*24*7);//儲存7天
//回寫到客戶端
response.addCookie(cookie);
}
//重定向到主頁面 response.sendRedirect(request.getContextPath()+"/success.jsp");
}
} catch (SQLException e) {
e.printStackTrace();
response.getWriter().write("使用者名稱或密碼錯誤");
return;
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void init() throws ServletException {
}
}
Filter
package com.kick.filter;
import java.io.IOException;
import java.sql.SQLException;
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.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kick.domain.Customer;
import com.kick.utils.CookieUtils;
import com.lick.service.KickService;
public class AutoLoginFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 攔截請求進行自動登陸
Customer customer = (Customer) request.getSession().getAttribute("c");
String uri = request.getRequestURI();
String contextpath = request.getContextPath();
String path = uri.substring(contextpath.length());
// 判斷使用者的請求 路徑是否為登陸頁面
if (!path.equals("/login.jsp") || path.equals("/login")) {
// 如果使用者沒有登陸即session沒有超時,還存有使用者資訊進行自動登陸
if (customer == null) {
Cookie cookie = CookieUtils.getCookie(request.getCookies(),
"autoLogin");
if (cookie != null) {
// 獲取使用者名稱和密碼
String username = cookie.getValue().split(",")[0];
String password = cookie.getValue().split(",")[1];
KickService service = new KickService();
// 登陸
try {
Customer c = service.queryCustomer(username, password);
if (c != null) {
request.getSession().setAttribute("c", c);//將使用者資訊存入到session
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
// 登陸之後正常操作
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<filter>
<filter-name>AutoLoginFilter</filter-name>
<filter-class>com.kick.filter.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AutoLoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.kick.web.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>