温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Java后端实现一个Cookie

发布时间:2020-12-11 14:32:46 来源:亿速云 阅读:419 作者:Leah 栏目:开发技术

怎么在Java后端实现一个Cookie?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

一、简单介绍

Cookie 是一些数据, 存储于你电脑上的文本文件中。

当 web 服务器向浏览器发送 web 页面时,在连接关闭后,服务端不会记录用户的信息。

Cookie 的作用就是用于解决 "如何记录客户端的用户信息":

  • 当用户访问 web 页面时,他的名字可以记录在 cookie 中。

  • 在用户下一次访问该页面时,可以在 cookie 中读取用户访问记录

怎么在Java后端实现一个Cookie

(博客园cookie界面)

二、简单实现

0.maven引入依赖

servlet和jsp的依赖

1.java代码编写

package com.lei; 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 java.io.IOException; import java.io.PrintWriter; import java.util.Date; public class CookieDemo01 extends HttpServlet {   @Override   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {     req.setCharacterEncoding("utf-16");     resp.setCharacterEncoding("utf-16");     PrintWriter out =resp.getWriter();     Cookie[] cookies=req.getCookies();     if(cookies!=null)     {       out.write("您上一次访问时间为:");       for(int i=0;i< cookies.length;i++)       {         Cookie cookie=cookies[i];         if(cookie.getName().equals("lastLoginTime"))         {           long lastLoginTime=Long.parseLong(cookie.getValue());           Date date=new Date(lastLoginTime);           out.write(date.toString());         }       }     }     else{       out.write("first time come to this website!");     }     Cookie cookie=new Cookie("lastLoginTime",System.currentTimeMillis()+"");     resp.addCookie(cookie);   }   @Override   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {     doGet(req, resp);   } }

2.设置web-xml里面加入 servlet注册和映射

<!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 xmlns="http://xmlns.jcp.org/xml/ns/javaee"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee            http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"      version="4.0"      metadata-complete="true"> <servlet>   <servlet-name>cookie</servlet-name>   <servlet-class>com.lei.CookieDemo01</servlet-class> </servlet> <servlet-mapping>   <servlet-name>cookie</servlet-name>   <url-pattern>/cookie</url-pattern> </servlet-mapping> </web-app>

三、运行效果

第一次cookie数组为空 不显示登陆时间

按理说应该会显示else里面的内容first time come to this website!

但是显示的是

只是因为下面的第二张图 是因为浏览器(我的是edge浏览器)默认还有一个cookie

也就是说我们第一次在执行页面(如果是从8080页面输入url跳转的)时 有别的cookie存在

第二次才会显示

怎么在Java后端实现一个Cookie

怎么在Java后端实现一个Cookie

看完上述内容,你们掌握怎么在Java后端实现一个Cookie的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI