分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

[02] JSP内置对象

发布时间:2023-09-06 01:32责任编辑:熊小新关键词:内置对象

1、内置对象的来历

JSP是由一些内置对象的,即不需要定义,也不需要我们主动创建,就可以直接使用的对象。当然,其对象名称也是固定的,无法修改,我们可以直接调用其相关方法。

在 [01] JSP的基本认识 已经说过JSP的本质,并明白了其运行的流程,容器会帮我们将JSP翻译成为Java类,其中会有一些“固定”代码,我们还是先看其核心方法:
  1. public void _jspService(HttpServletRequest request, HttpServletResponse response)
  2. ???????throws java.io.IOException, ServletException {
  3. ???PageContext pageContext = null;
  4. ???HttpSession session = null;
  5. ???ServletContext application = null;
  6. ???ServletConfig config = null;
  7. ???JspWriter out = null;
  8. ???Object page = this;
  9. ???JspWriter _jspx_out = null;
  10. ???PageContext _jspx_page_context = null;

  11. ???try {
  12. ???????response.setContentType("text/html");
  13. ???????pageContext = _jspxFactory.getPageContext(this, request, response,
  14. ???????????????null, true, 8192, true);
  15. ???????_jspx_page_context = pageContext;
  16. ???????application = pageContext.getServletContext();
  17. ???????config = pageContext.getServletConfig();
  18. ???????session = pageContext.getSession();
  19. ???????out = pageContext.getOut();
  20. ???????_jspx_out = out;
  21. ???????//我们自定义的Java代码会被翻译到这个位置
  22. ???} catch (Throwable t) {
  23. ???????if (!(t instanceof SkipPageException)) {
  24. ???????????out = _jspx_out;
  25. ???????????if (out != null && out.getBufferSize() != 0)
  26. ???????????????try {
  27. ???????????????????out.clearBuffer();
  28. ???????????????} catch (java.io.IOException e) {
  29. ???????????????}
  30. ???????????if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
  31. ???????}
  32. ???} finally {
  33. ???????_jspxFactory.releasePageContext(_jspx_page_context);
  34. ???}
  35. }

可以看到,在方法的开头中定义了一系列变量,在 try catch 块中对变量进行了赋值。根据容器翻译JSP文件的流程我们知道,我们自定义的Java代码都是加载在“固定”代码之后,也就是变量赋值之后,所以我们完全可以使用该方法体中内部定义的变量,以及方法的参数,并且可以顺利执行。

于是我们常用的JSP内置对象就这么有了:
类型    变量名    备注
HttpServletRequest    
request    

HttpServletResponse    response    
PageContext    pageContext    JSP上下文对象,可以由此获取其他内置对象
HttpSession    session    
ServletContext    application    
ServletConfig    config    
JspWriter    out    可以像客户端输出内容,然而<%= %>更便捷
Object    pagepage = this 指翻译后当前类的对象,很少使用
Throwable    exception错误页面才可使用

注:在某个页面抛出异常时(需页面定义 errorPage="xxx.jsp"),将转发至JSP错误页面。提供exception对象是为了在JSP中进行处理,只有在错误页面中才可以使用该对象。所以如果是作为错误页面则必须定义 <%@page isErrorPage="true" %>

那么内置对象的使用也很简单,直接在JSP页面的<% %>中嵌入即可,如 <%=request.getParameter("title)%>

至于内置对象的作用域,从他们的类型来说,已经不言而喻了,详情可以参考Servlet部分的作用域知识点。

[02] JSP内置对象

原文地址:https://www.cnblogs.com/deng-cc/p/8124540.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved