编程开发 > JSP > 文章内容

jsp复习资料(24)

2017-1-24编辑:ljnbset

向客户端返回数据
    下面以cookie为例介绍怎样返回数据到客户端。Cookie可以通过HTTP头在浏览器和服务器间传送信息。服务器首先在一个响应中用Set-Cookie头创建一个cookie,随后浏览器请求在cookie头中将此cookie返回到客户端。在将cookie返回到客户端前,可以先设置cookie的属性:Comment、MaxAge、Path、Domain等等。

下面看一段返回数据到客户端的代码:
1 package com.jsp.chap08; 
2 import java.io.IOException;
3 import java.io.PrintWriter; 
4 import javax.servlet.ServletException;
5 import javax.servlet.http.Cookie;
6 import javax.servlet.http.HttpServlet;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9 public class AddCookies extends HttpServlet { 
10     public void doGet(HttpServletRequest request, HttpServletResponse response)
11             throws ServletException, IOException {
12         response.setContentType("text/html;charset=GB2312");
13         PrintWriter pw = response.getWriter();
14         printHeader(request, response);
15         Cookie[] myCookie = new Cookie[3];
16         for (int i = 0; i < 3; i++) {
17             myCookie[i] = new Cookie("Cookie" + i, "Value" + i);
18             myCookie[i].setMaxAge(500);
19             response.addCookie(myCookie[i]);
20         }
21         printFooter(request, response);
22     } 
23     public void doPost(HttpServletRequest request, HttpServletResponse response)
24             throws ServletException, IOException {
25         doGet(request, response);
26     } 
27     public void printHeader(HttpServletRequest request,
28             HttpServletResponse response) throws ServletException, IOException {
29         PrintWriter pw = response.getWriter();
30         pw.println("<html>");
31         pw.println("<head><title>cookie的使用</title></head>");
32         pw.println("<body bgcolor=#FFFFFF>");
33         pw.println("<h1>cookie的使用</h1>");
34         pw.println();
35     } 
36     public void printFooter(HttpServletRequest request,
37             HttpServletResponse response) throws ServletException, IOException {
38         PrintWriter pw = response.getWriter();
39         pw.println("</body>");
40         pw.println("</html>");
41     }
42 }

jsp复习资料(20)

热点推荐

登录注册
触屏版电脑版网站地图