1. 程式人生 > >Cookie實現長期登陸

Cookie實現長期登陸

lec pda pri package tco tmm apach byte esp

預覽

技術分享圖片

技術分享圖片

項目目錄

技術分享圖片

技術分享圖片
package com.yuanze.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


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 org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.yuanze.bean.Person; import com.yuanze.dao.Dao; import com.yuanze.util.MD5Util; public class LoginServlet extends HttpServlet { public static
Log log = LogFactory.getLog(LoginServlet.class); public void setCookie(HttpServletResponse resp,String zh,String ssid,int timeout) { Cookie zhCookie=new Cookie("zh",zh); zhCookie.setMaxAge(timeout); Cookie ssidCookie=new Cookie("ssid",ssid); ssidCookie.setMaxAge(timeout); resp.addCookie(zhCookie); resp.addCookie(ssidCookie); } @Override
public void init() throws ServletException { // TODO Auto-generated method stub super.init(); List<Person> l=new ArrayList<>(); l.add(new Person("root","admin")); l.add(new Person("123","123")); try { Dao.Insertdata(l); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String action=req.getParameter("action"); if(action!=null) { if(action.equals("login")) { String zh=req.getParameter("zh"); String mm=req.getParameter("mm"); int timeout=new Integer(req.getParameter("timeout")); log.info("賬號:"+zh); log.info("密碼:"+mm); log.info("timeout:"+timeout); String info=null; try { List<Person> l=Dao.Selectdata(zh); if(l.size()==0) { info="該用戶不存在"; } else { if(l.get(0).getMm().equals(mm)) { info="登錄成功"; String ssid=MD5Util.calcMD5(zh+MD5Util.KEY); setCookie(resp, zh, ssid, timeout); resp.sendRedirect(req.getContextPath()+"/"+"login"+"?"+System.currentTimeMillis()); return; } else { info="密碼錯誤"; } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); info=e.getMessage(); } log.info(info); req.getSession(true).setAttribute("info",info); } else if (action.equals("logout")) { setCookie(resp, "", "", 0); resp.sendRedirect(req.getContextPath()+"/"+"login"+"?"+System.currentTimeMillis()); return; } } boolean login=false; String account=null; String ssid=null; if(req.getCookies()!=null) { int x=0; for(Cookie cookie:req.getCookies()) { if(cookie.getName().equals("zh")) account =cookie.getValue(); if(cookie.getName().equals("ssid")) ssid =cookie.getValue(); log.info("cookie"+String.valueOf(++x)+":"+cookie.getValue()); } } if(account !=null &&ssid!=null) { log.info("ssid"+ssid); log.info("md5"+MD5Util.calcMD5(account+MD5Util.KEY)); login =ssid.equals(MD5Util.calcMD5(account+MD5Util.KEY)); } log.info(login); req.getSession(true).setAttribute("login",login); req.getRequestDispatcher("/login.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doGet(req, resp); } }
LoginServlet 技術分享圖片
package com.yuanze.util;
import java.security.MessageDigest;

public class MD5Util {
    public static final String KEY=":[email protected]";
    public final static String calcMD5(String ss) {
        String s=  ss==null ? "":ss;
        char hexDigits[] = {‘0‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘,‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘};
        try {
            byte[] strTemp=s.getBytes();
            MessageDigest mdTemp=MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md=mdTemp.digest();
            int j=md.length;
            char str[]=new char[j*2];
            int k=0;
            for(int i=0;i<j;i++) {
                byte byte0=md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
         }catch(Exception e) {
            return null;
        }
    }
}
MD5Util 技術分享圖片
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

</head>
<body>

<%
    String info=String.valueOf(request.getSession().getAttribute("info"));
    request.getSession().removeAttribute("info");
    boolean login=String.valueOf(request.getSession().getAttribute("login")).equals("true")?true:false;
    request.getSession().removeAttribute("login");
%>

<legend><%=login? "歡迎回來":"請先登錄" %></legend>

<% if(login){%>

歡迎你,${ cookie.zh.value } . &nbsp;&nbsp;
<a href="login?action=logout">註銷</a>
<%}else{ %>

<legend><%=info.equals("null")?"":info%></legend>

<form action="login?action=login" method="POST">
<table>
            <tr>
            <td> 賬號:</td>
            <td><input type="text" name="zh" style="width:200px"></td>
            </tr>
            <tr>
            <td> 密碼:</td>
            <td><input type="text" name="mm"></td>
            </tr>

<tr>
<td> 登錄有效期</td>
<td>
    <input type="radio" name="timeout"  value="-1" checked="checked">關閉瀏覽器失效<br>
    <input type="radio" name="timeout"  value="<%= 30*24*60*60 %>" >30天<br>
    <input type="radio" name="timeout"  value="<%=Integer.MAX_VALUE %>">永久有效<br>
</td>
</tr>

<tr>
<td>
<input type="submit" value="登錄" class="button">
</td>
</tr>

</table>


</form>

<%} %>

</body>
</html>
login.jsp

其他文件參考

Servlet二

Servlet一

實現思路:

cookie的存活期 是通過 服務器 response對象中cookie設置實現的,添加cookie對象,並設置時間,-1代表 退出瀏覽器即失效,0代表只用於本次請求,正數值代表存活秒數,正無窮大代表 永久

退出登錄的實現 設置同名 cookie 並設置 timeout 為 0

鏈接:https://pan.baidu.com/s/15sstGWAHlbZEQNg3TT2A7g
提取碼:m7mw

Cookie實現長期登陸