创建一个servlet,向客户端写入一个Cookie对象(写入信息:你的学号与姓名,有效期:一周。特别注意:这里要保存两个Cookie,当然保存一个包含学号和姓名的对象也可以的);
时间: 2024-05-02 17:18:08 浏览: 14
以下是一个创建Cookie的Servlet示例:
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CreateCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentNumber = "123456"; // 学号
String studentName = "张三"; // 姓名
Cookie cookie1 = new Cookie("studentNumber", studentNumber);
cookie1.setMaxAge(7 * 24 * 60 * 60); // 设置Cookie的有效期为一周
response.addCookie(cookie1);
Cookie cookie2 = new Cookie("studentName", studentName);
cookie2.setMaxAge(7 * 24 * 60 * 60); // 设置Cookie的有效期为一周
response.addCookie(cookie2);
response.getWriter().println("Cookie已创建");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
在这个示例中,我们首先定义了学号和姓名的变量,然后创建了两个Cookie对象,一个包含学号信息,一个包含姓名信息。我们设置了Cookie的有效期为一周,并将它们添加到响应中。最后,我们向客户端输出了一条消息,表示Cookie已经创建成功。
注意,当创建Cookie时,我们使用了`addCookie()`方法将它们添加到响应中。这个方法是HttpServletResponse接口中的方法,在Servlet API中定义。当客户端收到响应时,它会将Cookie保存在本地,并在以后的请求中将它们发送回服务器。在服务器端,我们可以使用HttpServletRequest接口的`getCookies()`方法来获取客户端发送的所有Cookie。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)