Basic knowledge and understanding of jsp

Keywords: JSP Java Apache Session

Introduction:

JSP is the full name of JavaServer Pages. Like servlet Technology, JSP is a technology defined by SUN company for developing dynamic web resources.

The biggest feature of JSP technology is that writing JSP is like writing html, but:

Compared with html, html can only provide static data for users, while Jsp technology allows java code to be nested in the page to provide dynamic data for users.

Compared with servlets, servlets are difficult to typeset data, while JSP can generate dynamic data with java code, it is also easy to typeset data. Both JSP and servlet can be used to develop dynamic web resources. However, due to the characteristics of these two technologies, in the long-term software practice, people gradually use servlet as a controller component in web applications, and JSP technology as a data display template.

Program data is usually output after beautification: if jsp uses java code to generate dynamic data and beautify it, the page will be difficult to maintain.

The servlet can not only generate data, but also embed html code in it to beautify data, which will also lead to poor readability and difficult to maintain.

So the best way is according to the characteristics of these two technologies, let them each be responsible for their own, servlet is only responsible for responding to the request to generate data, and bring the data to jsp through forwarding technology, data display jsp to do.

How Jsp works:

Objectives:

  • How does the Web server call and execute a jsp page?
  • How is the html typesetting label in the Jsp page sent to the client?
  • How does the java code server in the Jsp page execute?
  • When the Web server calls jsp, what java objects will be provided to jsp?

Thinking: why can JSP be called dynamic web resource development technology like servlet?

In fact, Jsp is a Servlet, so we need to first introduce the relevant technologies of Servlet. When we visit Jsp for the first time, the Jsp engine will translate the Jsp into a Servlet, and the java file will be stored in the work directory of Tomcat. Here, we will create a new MyJsp.jsp page, and then visit the following, let's take a look at the translated source code:

The following is the content of MyJsp.jsp page:

[html] view plain copy
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
      
    <title>My JSP 'MyJsp.jsp' starting page</title>  
      
  </head>  
    
  <body>  
    This is my JSP page. <br>  
  </body>  
</html>

Here is the source code after translation:

[java] view plain copy
package org.apache.jsp;  
  
import javax.servlet.*;  
import javax.servlet.http.*;  
import javax.servlet.jsp.*;  
import java.util.*;  
  
public final class MyJsp_jsp extends org.apache.jasper.runtime.HttpJspBase  
    implements org.apache.jasper.runtime.JspSourceDependent {  
  
  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();  
  
  private static java.util.List _jspx_dependants;  
  
  private javax.el.ExpressionFactory _el_expressionfactory;  
  private org.apache.AnnotationProcessor _jsp_annotationprocessor;  
  
  public Object getDependants() {  
    return _jspx_dependants;  
  }  
  
  public void _jspInit() {  
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();  
    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());  
  }  
  
  public void _jspDestroy() {  
  }  
  
  public void _jspService(HttpServletRequest request, HttpServletResponse response)  
        throws java.io.IOException, ServletException {  
  
    PageContext pageContext = null;  
    HttpSession session = null;  
    ServletContext application = null;  
    ServletConfig config = null;  
    JspWriter out = null;  
    Object page = this;  
    JspWriter _jspx_out = null;  
    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();  
      _jspx_out = out;  
  
      out.write("\r\n");  
      out.write("\r\n");  
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");  
      out.write("<html>\r\n");  
      out.write("  <head>\r\n");  
      out.write("    \r\n");  
      out.write("    <title>My JSP 'MyJsp.jsp' starting page</title>\r\n");  
      out.write("    \r\n");  
      out.write("  </head>\r\n");  
      out.write("  \r\n");  
      out.write("  <body>\r\n");  
      out.write("    This is my JSP page. <br>\r\n");  
      out.write("  </body>\r\n");  
      out.write("</html>\r\n");  
    } catch (Throwable t) {  
      if (!(t instanceof SkipPageException)){  
        out = _jspx_out;  
        if (out != null && out.getBufferSize() != 0)  
          try { out.clearBuffer(); } catch (java.io.IOException e) {}  
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);  
      }  
    } finally {  
      _jspxFactory.releasePageContext(_jspx_page_context);  
    }  
  }  
}  

We see that this class inherits org.apache.jasper.runtime.HttpJspBase. To see the source code of this class, we need to download the source code of tomcat and find this class. The source code is as follows:

[java] view plain copy
/* 
 * Licensed to the Apache Software Foundation (ASF) under one or more 
 * contributor license agreements.  See the NOTICE file distributed with 
 * this work for additional information regarding copyright ownership. 
 * The ASF licenses this file to You under the Apache License, Version 2.0 
 * (the "License"); you may not use this file except in compliance with 
 * the License.  You may obtain a copy of the License at 
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0 
 *  
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */  
  
package org.apache.jasper.runtime;  
  
import java.io.IOException;  
  
import javax.servlet.ServletConfig;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.jsp.HttpJspPage;  
import javax.servlet.jsp.JspFactory;  
  
import org.apache.jasper.compiler.Localizer;  
  
/** 
 * This is the super class of all JSP-generated servlets. 
 * 
 * @author Anil K. Vijendran 
 */  
public abstract class HttpJspBase   
    extends HttpServlet   
    implements HttpJspPage   
          
      
{  
      
    protected HttpJspBase() {  
    }  
  
    public final void init(ServletConfig config)   
    throws ServletException   
    {  
        super.init(config);  
    jspInit();  
        _jspInit();  
    }  
      
    public String getServletInfo() {  
    return Localizer.getMessage("jsp.engine.info");  
    }  
  
    public final void destroy() {  
    jspDestroy();  
    _jspDestroy();  
    }  
  
    /** 
     * Entry point into service. 
     */  
    public final void service(HttpServletRequest request, HttpServletResponse response)   
    throws ServletException, IOException   
    {  
        _jspService(request, response);  
    }  
      
    public void jspInit() {  
    }  
  
    public void _jspInit() {  
    }  
  
    public void jspDestroy() {  
    }  
  
    protected void _jspDestroy() {  
    }  
  
    public abstract void _jspService(HttpServletRequest request,   
                     HttpServletResponse response)   
    throws ServletException, IOException;  
}  

Well, you see, it inherits the HttpServlet class, so in fact, Jsp is a Servlet

JSP script

JSP script is a way for JSP to define java code. There are three forms:

  • The% java code% >, the Java code defined in the script will appear in the service method of the java file generated by the jsp file. So what can be defined in the service method can be defined in the script.
  • %! java code% >, the java code defined in the script, will be in the member location. (rarely used)
  • <% = java code% > the Java code defined in the script will be output to the page. That is, what can be defined in the output statement can be defined here. In the service method of the Java class.

JSP built in objects

In JSP pages, you do not need to get and create objects that can be used directly.

jsp has nine built-in objects. (the first four are domain objects)

  • PageContext pageContext. Share data on the current page. You can also get eight other built-in objects.
  • HttpServletRequest request. Multiple resources in the range of one request access (jump)
  • HttpSession session. Share data between multiple requests in a session.
  • ServletContext application. All users share data.
  • HttpServletResponse response. Response object.
  • Object page. The object of the current page (Servlet), equivalent to this
  • ServletConfig config. The configuration object for the Servlet.
  • Throwable exception. Exception object.
  • JspWriter out. Character stream output object, which can output data to the page.

The difference between out and response.getWriter(): before tomcat responds to the client, it will first find the buffer data of response.getWriter(), and then find the data of out buffer. So the conclusion is: the output of response.getWriter() is always before out, regardless of the writing position. It is recommended to use out to output data uniformly.

After the jsp code is modified, you do not need to restart the server. You can access it directly after refreshing.

JSP directive

Used to configure JSP pages and import resource files. The format is as follows:

There are three instructions:

  1. Page: used to configure JSP pages (required. Without this, it becomes a normal static page)
  2. taglib: import tag resources (often used to import jstl Tag Library)
  3. include: included in the page, import the page file. It is usually used to extract the common content of multiple jsp pages, so as to simplify jsp pages. The included pages only need to write and configure jsp tags and content

For example:

Common properties of page instruction

  • contentType, which sets the MIME type and character set of the response body, and sets the character set of the current page (the latter can only take effect with advanced development tools. If it is a low-level tool, you need to configure the pageEncoding property to set the character set of the current page)
  • Import, which is used to import packages, usually takes up one line of script.
  • errorPage: when an exception occurs to the current page, it will automatically jump to the specified error page.
  • isErrorPage, which identifies whether the current page is an error page. If the value of this property is set to true, the built-in exception object exception can be used directly. The default is false. Exception is not allowed.

taglib instruction, import the required tag library.

  • Prefix attribute is used to define the prefix. If you want to define what you want, you can write "prefix Name:" in the future, you can display the tags in the tag library, which is equivalent to taking an alias for the tag library. But there are some conventional names, such as the prefix c for jstl tag library.
  • The uri property defines the address where the tag library is located.

The include instruction is usually used to extract the repeated jsp part into a new page, and then use the file attribute to contain the page where it is used.

JSP notes

  • The first is to use HTML comments, which can only be used to comment HTML snippets.
  • The second is the JSP specific annotation <% -- Annotation content --% >, which can annotate all.

EL expression

70 original articles published, praised 1, visited 2174
Private letter follow

Posted by gregolson on Sat, 11 Jan 2020 21:56:51 -0800