日期:2014-05-16  浏览次数:20373 次

3-2 JSP中的请求、响应、Cookie、会话HttpSession

1 JSP中的请求与响应

1.1 请求与响应的基本概念

请求:当用户在浏览器中输入 URL并提交或提交表单时,一个请求即被创建并送到服务器上。

响应:当服务器接收到用户的请求时,会根据用户的具体请求做相应的处理操作,并将操作结果返回给用户。

1.2 request对象的常用方法

  • object getAttribute(String name) 返回指定属性的属性值 
  • Enumeration getAttributeNames() 返回所有可用属性名的枚举
  • String getCharacterEncoding() 返回字符编码方式 
  • int getContentLength() 返回请求体的长度(以字节数) 
  • String getContentType() 得到请求体的MIME类型 
  • ServletInputStream getInputStream() 得到请求体中一行的二进制流 
  • String getParameter(String name) 返回name指定参数的参数值
  • Enumeration getParameterNames() 返回可用参数名的枚举
  • String[] getParameterValues(String name) 返回包含参数name的所有值的数组 
  • String getProtocol() 返回请求用的协议类型及版本号 
  • String getScheme() 返回请求用的计划名,如:http.https及ftp等 
  • String getServerName() 返回接受请求的服务器主机名 
  • int getServerPort() 返回服务器接受此请求所用的端口号 
  • BufferedReader getReader() 返回解码过了的请求体 
  • String getRemoteAddr() 返回发送此请求的客户端IP地址 
  • String getRemoteHost() 返回发送此请求的客户端主机名
  • void setAttribute(String key,Object obj) 设置属性的属性值 
  • String getRealPath(String path) 返回一虚拟路径的真实路径
  • void setCharacterEncoding(String charset) 指定请求的编码

1.3 response对象的常用方法

  • String getCharacterEncoding() 返回响应用的是何种字符编码 
  • ServletOutputStream getOutputStream() 返回响应的一个二进制输出流 
  • PrintWriter getWriter() 返回可以向客户端输出字符的一个对象 
  • void setContentLength(int len) 设置响应头长度 
  • void setContentType(String type) 设置响应的MIME类型 
  • sendRedirect(java.lang.String location) 重新定向客户端的请求

2 Cookie

Cookie是指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)。

2.1 Cookie的使用

  • 创建Cookie
Cookie c= new Cookie("name","value");

 

其中,name为创建的Cookie名称,将来读取这个Cookie时使用;value为Cookie对象的值。

  • 读取Cookie
Cookie cookies[] = request.getCookies();

 

得到的是一个Cookie数组,使用for循环遍历:

for(int i=0;i<cookies.length;i++)
System.out.println(cookies[i].getValue()); 

 

  • 向客户端添加Cookie

将cookie放入到HTTP响应报头,可以使用HttpServletResponse的addCookie方法

response.addCookie(c);

 

  • 删除Cookie

删除Cookie时,只需要将Cookie的最大时效设置为0

 

for(int i=0;i<cookies.length;i++){
cookies[i].setMaxAge(0);
response.addCookie(cookies[i])}

3 会话HttpSession

3.1 会话的常用方法

  • Object getAttribute(String name)   根据name获取设置的属性值。
  • void setAttribute(String name,Object value)   设置session对象属性值  
  • void removeAttribute(String name)   删除session对象的name属性
  • Enumeration getAttributeName()    返回捆绑到当前会话的所有属性名
  • long getCreationTime()   返回表示会话创建的一个长整型值     
  • long getLastAccessedTime()  最后访问日期和时间的一个长整型值       
  • String getId()  返回会话ID      
  • int getMaxIn