🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
![](https://box.kancloud.cn/7d4e3caa5fc89d58ef48b1f37257e0d8_444x338.png) CookieServlet.java ~~~ package zyw.cookie; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "CookieServlet",urlPatterns = "/cookie") public class CookieServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie =new Cookie("gooods","cup");//不能使用中文 cookie.setMaxAge(60*10);//10分钟 cookie.setPath("/hello/getCookie");//指定路径 //cookie.setMaxAge(0);//持久化时间为0则为删除cookie Cookie cookie1=new Cookie("username","zyw"); response.addCookie(cookie1); response.addCookie(cookie); } } ~~~ GetCookieServlet.java ~~~ package zyw.cookie; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "GetCookieServlet",urlPatterns = "/getcookie") public class GetCookieServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cookies =request.getCookies();//返回cookie数组 for (Cookie cookie : cookies) {//遍历数组 String name=cookie.getName(); if(name.equals("username")){ String value=cookie.getValue(); response.getWriter().write("username:"+value); } } } } ~~~ 先执行CookieServlet.java,再执行GetCookieServlet.java得到 ![](https://box.kancloud.cn/f6db955535d303712452f9d6980ed6e4_436x122.png)