【servlet】Cookie登陆系统

要求:用户第一次登陆时显示欢迎语句,并且提示这是您的第一次访问;下次登录时显示上次的登录时间


方法

使用cookie记录上次登录时间,下次登录输出


servlet部分:

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "HomeWork", value = "/HomeWork")
public class HomeWork extends HttpServlet {
    public static boolean f = false;
    public static Cookie[] cookies;
    String lasttime = null;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String time = HomeWork.fomat();
        cookies = request.getCookies();

        if(lasttime == null ){
            String encode = URLEncoder.encode(time);
            Cookie cookie = new Cookie("lasttime", encode);
            response.addCookie(cookie);
            request.setAttribute("msg","第一次登录");
            request.getRequestDispatcher("/success.jsp").forward(request,response);
        }
        if(cookies != null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                if(name.equals("lasttime")){
                    lasttime = URLDecoder.decode(value);
                    request.setAttribute("msg","上一次登录时间为"+ lasttime);
                    request.getRequestDispatcher("/success.jsp").forward(request,response);
                }
            }
        }
    }
    public static String fomat(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

jsp部分:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/17
  Time: 14:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登录成功!</h1>
${requestScope.msg}
</body>
</html>

结果:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值