javaweb开发之jsp开发

    一、初始jsp

    在web开发中前台页面需要使用html,css和js渲染页面展示给用户,之前我们学习了Servlet知道如果想要向前台输出内容需要使用HttpServletResponse对象获取打印流然后在一行一行的输出html标签,这对于开发者来说简直就是噩梦。针对这种情况SUN公司定义了一种用于开发动态web资源的技术也就是jsp。JSP全称是Java Server Pages其本质就是servlet但是用户可以在jsp页面里直接写html代码也可以jsp页面中嵌套java代码。jsp的出现大大提高了人们使用java开发软件的效率。

    二、jsp的运行原理

    jsp的本质就是Servlet。浏览器发送请求到服务器也就是tomcat其本质都是在访问Servlet,因为tomcat访问所有的资源,都是用Servlet来实现的。当我们第一次访问jsp时,服务器会把jsp文件转化为一个servlet然后编译成class字节码文件后再执行。jsp被转译为一个java文件后继承了org.apache.jasper.runtime.HttpJspBase这个类,而HttpJspBase 继承了HttpServlet,所以是jsp的本质就是一个servlet。因为jsp在用户第一次访问的时候需要先转译为java文件在转译为class字节码文件,所以jsp页面在用户第一次访问的时候会比较的慢,当用户第二次访问jsp页面时是直接访问的class文件所以速度会比第一次访问快。

图片来源地址:https://upload-images.jianshu.io/upload_images/10077403-8d880f94e33ddbae.png?imageMogr2/auto-orient/strip|imageView2/2/w/425/format/webp

    三、jsp内置的九大对象

    在jsp中内置了九大对象,查看jsp转译后的java文件得知,这九大内置对象分别是:request、response、session、application、out、pagecontext、config、page、exception。代码如下:

 final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=utf-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                  null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();

其中request,response,session对象对应的就是HttpServletRequest,HttpServletResponse,HttpSession对象,application对象就是ServletContext对象,config对象就是ServletConfig对象,pageContext 对象表示当前页面的上下文,通过这个对象可以获取JSP页面的out、request、reponse、session、application 等对象,page对象表示当前jsp页面本身。

猜你喜欢

转载自www.cnblogs.com/suyang-java/p/11511677.html
今日推荐