---
# System prepended metadata

title: Cookie的知識
tags: [Java Web-常用知識點]

---

# Cookie的知識
###### tags: `Java Web-常用知識點`

### Cookie是什麼
Cookie：在客戶端保存的數據，在與服務器連接時，發送給服務器

### Cookie的生成步驟
#### 1.創建Cookie對象

#### 2.在客戶端保存Cookie

#### 3.設置Cookie的有效時長(秒為單位)
    cookie.setMaxAge();
    cookie.setDomain(pattern);
    cookie.setPath(uri);
    
#### 4.cookie的應用
4-1:記住用戶名和密碼10天
    setMaxAge(60*60*24*10)
    
4-2:10天免登陸
    
    
    

![](https://i.imgur.com/oNSZuPn.png)

```java=
@WebServlet("/cookie01")
public class CookieServlet01 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建一个Cookie对象
        Cookie cookie = new Cookie("uname","jim");
        //2.将这个Cookie对象保存到浏览器端
        response.addCookie(cookie);



        request.getRequestDispatcher("hello01.html").forward(request,response);

    }
}
```

