Software 151--Xun Jiayang
Java's operation of cookies is simple, mainly introduces the establishment of cookies and read cookies, and how to set the life cycle of cookies and the path of cookies.
Create an inanimate cookie that disappears as the browser closes, with the code as follows
| 1234 |
HttpServletRequest request HttpServletResponse responseCookie cookie = newCookie("cookiename","cookievalue");response.addCookie(cookie); |
Create a lifecycle cookie to set his life cycle
| 12345678 |
cookie = newCookie("cookiename","cookievalue"); cookie.setMaxAge(3600); //设置路径,这个路径即该工程下都可以访问该cookie 如果不设置路径,那么只有设置该cookie路径及其子路径可以访问cookie.setPath("/");response.addCookie(cookie); |
Here's how to read a cookie and read the cookie code below
| 12345 |
Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组for(Cookie cookie : cookies){ cookie.getName();// get the cookie name cookie.getValue(); // get the cookie value} |
Above is the basic read and write cookie operation. We'd better do it in real time, like adding a cookie, we're concerned about the cookie's name,value, life cycle, so we're encapsulating a function, and of course passing in a response object, Addcookie () code like this
| 12345678910111213 |
/** * 设置cookie * @param response * @param name cookie名字 * @param value cookie值 * @param maxAge cookie生命周期 以秒为单位 */publicstaticvoid addCookie(HttpServletResponse response,String name,String value,intmaxAge){ Cookie cookie = newCookie(name,value); cookie.setPath("/"); if(maxAge>0) cookie.setMaxAge(maxAge); response.addCookie(cookie);} |
When we read cookies, we want to encapsulate a function to facilitate our operation, so long as we provide the name of the cookie, we can get the value of the cookie, and with that idea, it's easy to think of encapsulating the cookie in the map, and then the following package
| 123456789101112131415161718192021222324252627282930313233 |
/** * 根据名字获取cookie * @param request * @param name cookie名字 * @return */publicstaticCookie getCookieByName(HttpServletRequest request,String name){ Map<String,Cookie> cookieMap = ReadCookieMap(request); if(cookieMap.containsKey(name)){ Cookie cookie = (Cookie)cookieMap.get(name); returncookie; }else{ returnnull; } }/** * 将cookie封装到Map里面 * @param request * @return */privatestaticMap<String,Cookie> ReadCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<String,Cookie>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } returncookieMap;} |
Java operation of Cookies