JSP9个内置对象解释及常用方法

介绍

jsp 翻译 成 .java 文件后,在 _jspService() 方法中会生成 9个对象,如下图:

9个对象如下:

  • request
  • response
  • session
  • application
  • out
  • pagecontext
  • config
  • page
  • exception

使用

可以在 <% %> 和 <%= %> 中直接使用

request

详见:
https://malaoshi.top/show_1IXrPc05MvN.html
https://malaoshi.top/show_1IXrPo5jGZd.html

response对象

详见:
https://malaoshi.top/show_1IXrVrWarwa.html
https://malaoshi.top/show_1IXrVwsdpni.html

session对象

https://malaoshi.top/show_1IXrg8iBA5r.html

application对象

详见:https://malaoshi.top/show_1IXrhDGfZO0.html

out对象

对应类:JspWriter
说明:向客户端输出内容

常用方法:

  • out.write() 输出字符串,jsp翻译成java代码时,用的该方法
  • out.println() 有很多重载方法,转换成为字符串后调用的 write 输出。
    我们可以调用该方法,更简单
  • void close() 关闭输出流

例子

<%
    int score=95;
    if(score>=90){
        out.println("优");
    }else if(score>=80){
        out.println("良");
    }else if(score>=70){
        out.println("中");
    }else if(score>=60){
        out.println("差");
    }else{
        out.println("不及格");
    }
%>

pageContext对象

对应类:PageContext

说明:查看 jsp 翻译成的 .java 文件可知,通过该对象创建 application、config、session、out 对象

常用方法

  • void setAttribute(key, value); 将 key/value 存入到 pageContext 对象中
  • Object getAttribute(key); 根据key获取value
  • void removeAttribute(String name) 删除key/value
  • JspWriter getOut() 返回当前客户端响应被使用的JspWriter流(out)
  • HttpSession getSession() 返回当前页中的HttpSession对象(session)
  • object getPage() 返回当前页的object 对象(page)
  • Exception getException() 返回当前页的Exception对象(exception)
  • ServletConfig getServletConfig() 返回当前页的ServletConfig对象(config)
  • ServletContext getServletContext() 返回当前页的ServletContext对象(application)

exception对象

对应类:Java.lang.Throwable
说明:exception对象是异常对象,当一个页面在运行过程中发生了例外,就产生这个对象。

注意: 设置 isErrorPage="true" 才能使用,具体如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>

常用方法:

  • String getMessage() 返回描述异常的消息
  • String toString () 返回关于异常的简短描述消息
  • void print StackTrace() 显示异常及其栈轨迹
  • ThrowableFillInStackTrace() 重写异常的执行栈轨迹

page对象

对应类:Object
说明:page对象就是指向当前JSP页面本身,有点象类中的this

config对象

对应类:javax.servlet.ServletConfig

说明:可以像配置 Servlet 那样,将 jsp 配置在 web.xml 中,此时该对象作用:

  1. 可以获取 Servlet 程序的别名 servlet-name 的值
  2. 获取初始化参数 init-param

较少使用

参考以下网址,非常感谢:
http://www.360doc.com/content/16/0505/07/27831725_556371279.shtml
http://blog.csdn.net/yenange/article/details/5949518
http://blog.csdn.net/sona_shi555/article/details/7797068


原文出处:/show_1IXrNSscAyT.html