JSP 内置对象

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38500325/article/details/82988933

JSP提供了九个内置对象

  • request:请求对象
  • response:响应对象
  • session:会话对象
  • application:应用程序对象
  • out:输出对象
  • page:页面对象
  • config:配置对象
  • exception:异常对象
  • pageContext:页面上下文对象

request对象

当客户端请求一个JSP页面时,JSP容器会将客户端的请求信息包装在这个request对象中.

封装的数据大概有如下几种:

  • HTTP报文头部数据.
  • 客户端提交的数据.
  • 网络层协议数据.

主要方法

  • getParameter(String name)//返回指定参数,不存在则返回空
  • getParameterValues(String name)//返回指定参数所有值,不存在则返回空
  • setAttribute(String key,Object obj)
  • getAttribute(String name)
  • getAttributeNames()
  • getSession()//获取request对应的session对象,不存在则创建一个
  • getInputStream()
  • getRemoteAddr()
  • getCharacterEncoding()

response对象

向客户端发送数据,设置HTTP报文头,写入cookie信息,将处理结果返回客户端

主要方法

  • setRedirect(String location)//对画面进行跳转.
  • setCharacterEncoding(String charset)//设置响应字符编码
  • setContenType(String type)//设置响应头信息
  • reset()//清除缓存中任何数据.
  • isCommitted()//返回响应是否已经提交到客户端
  • addCookie(Cookie c)
  • getCookie(Cookie c)

cookie的操作

向客户端发送cookie

Cookie c = new Cookie("username","u1");
c.setMaxAge(60*60*24*7);
response.addCookie(c);

从客户端读取cookie

Cookie [] cookies = request.getCookies();
if(cookies!=null){
    for(int i=0; i<cookies.length;i++){
        Cookie cookie=cookies[i];
        if(cookit.getName().equals("userName"))
            dosomething(cookie.getValue());
        }
    }
}

session对象

客户端和服务器之间的交互称为会话,session存储对象信息.用于临时存储多个页面的共享数据.

session对象会在以下情况失效

  • 客户关闭浏览器.
  • 会话超时,即超过session对象的生存时间.默认30min
  • 显式的调用invalidate方法

主要方法

  • getId()
  • removeAttribute(String name)
  • setAttribute(String name,Object value)
  • getAttribute(String name)
  • getCreationTime()
  • setMaxInactiveInterval(int n)
  • invalidate()
  • 利用session对象存储数据
  • session对象的生命周期

out对象

向客户端发送数据,发送的内容是浏览器需要显示的内容.类型为JspWriter

写入到tomcat的缓冲区

  • page指定的buffer属性关闭了out对象的缓存功能
  • out对象的缓冲区已满
  • 整个JSP页面结束

主要方法

  • print(datatype data)
  • println(datatype data)
  • newLine()
  • flush()
  • close()
  • clear()
  • getRemaining()

application对象

用于多个程序或用户之间的共享数据

主要方法

  • getInitParameter(String name)
  • getServerInfo()
  • getRealPath(URL)
  • setAttribute(String key,Object obj)
  • getAttribute(String name)

利用application对象存储数据

其他内置对象

page对象,指向当前对象本身

config对象,用于获取配置参数

pageContext对象,代表页面上下文

pageContext主要方法

  • setAttribute(String key,Object value[,int scope])
  • getAttribute(String name)
  • forward(String url)//页面重定向到另外一个页面
  • getRequest()
  • getServletConfig()

猜你喜欢

转载自blog.csdn.net/weixin_38500325/article/details/82988933
今日推荐