他是用户访问web服务器时,服务器在用户硬盘上存放的信息,好像是服务器给客户端的“点心”。比如:是否记录用户名密码。其中,A服务器不允许访问B服务器存在客户端的cookie
一个cookie包含一对key/value
如:service将信息写入cookie,响应给客户端
具体代码如下:Cookie theCookie = new Cookie("CookieName",cookieValue);
response.addCookie(theCookie);
jsp与servlet区别:
jsp擅长于网页制作,不容易跟踪与排错
servlet主要处理流程和业务逻辑,生成动态网页不直观(servlet是纯java语言)
问题:
(1)HttpServletRequest对象是由谁来创建的?
A.由servlet容器负责创建,对于每个HTTP请求,servlet容器都会创建一个HttpServletRequest对象
b.由javaweb应用程序的servlet或jsp组件创建,当servlet或jsp组件响应http请求时,先创建HttpServletRequest对象
(2)servletContext对象是由谁来创建的?
A.由servlet容器负责创建,对于每个HTTP请求,servlet容器都会创建一个servletContext对象
B.由servlet容器负责创建,对于每个javaweb应用,在启动的时,servlet容器都会创建一个servletContext对象
1 package com.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.Cookie; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import org.apache.tomcat.util.http.Cookies; 12 13 public class CookieServlet extends HttpServlet 14 { 15 private int count1; 16 17 private int count2; 18 19 @Override 20 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 21 throws ServletException, IOException 22 { 23 Cookie cookie = new Cookie("cookieName:" + count1++ ,", cookieValue:" +count2++); 24 25 cookie.setMaxAge(10); 26 27 resp.addCookie(cookie); 28 29 Cookie[] cookies = req.getCookies(); 30 31 if(null == cookies) 32 { 33 return; 34 }else 35 { 36 for(Cookie c : cookies) 37 { 38 System.out.println("CookiesName:" + c.getName()); 39 System.out.println("CookiesValue:" + c.getValue()); 40 } 41 } 42 43 44 45 } 46 }