01 import javax.servlet.http.HttpServlet;
02 import javax.servlet.http.HttpServletResponse;
03 import javax.servlet.http.HttpServletRequest;
04 import javax.servlet.http.Cookie;
05 import java.io.IOException;
06
07 public class CookieServlet extends HttpServlet {
08
09 public static final String TEST_COOKIE_NAME = "testCookie";
10
11 protected void doGet(HttpServletRequest req,HttpServletResponse res)
12 throws IOException {
13 Cookie cookie = this.getCookie(req);
14 int count = Integer.parseInt(cookie.getValue());
15 count++;
16 cookie.setValue(String.valueOf(count));
17 res.addCookie(cookie);
18 }
19
20 protected Cookie getCookie(HttpServletRequest req) {
21 Cookie[] cookies = req.getCookies();
22 if (cookies != null) {
23 for (int i=0; i < cookies.length; i++) {
24 if (TEST_COOKIE_NAME.equals(cookies[i].getName())) {
25 return cookies[i];
26 }
27 }
28 }
29 return new Cookie(TEST_COOKIE_NAME, "0");
30 }
31 }
|