Java Web Basics JSP: Put on the vest I still know you __java

Source: Internet
Author: User
Tags html tags volatile java web apache tomcat


It's been a servlet for a long time, but because it's just a demo and doesn't show an interface completely, its two flaws are not shown:


All HTML tags and text must be written in a string form through an instance of Servletresponse; all text and style must be hard-coded, that is, if you want to change the display of the front end slightly, you must recompile the servlet instance; In response to these two issues, JSP this technology, generally speaking JSP a bit like HTML file, but you can see there are some other elements, this is the Java code, but relative to the servlet, it is a text file, do not need to compile (in fact, you do not see it), This means that when you add a new JSP page, you do not need to restart the servlet container, and the paging file can be edited using any text editor. JSP pages are generally run in the JSP container, the servlet container is also a JSP container, so that Tomcat can also act as a JSP container.

first, request JSP page

The request to the JSP page is essentially similar to requesting a servlet, but the big advantage of the JSP page we mentioned above is that it doesn't need to be compiled, but it's not strictly correct, it just doesn't need to be statically compiled, that is, it doesn't need to be compiled before the formal deployment runs, However, after the Web application deployment is run, it is dynamically converted to a servlet class and the class is compiled. When a JSP page is requested for the first time, it is converted to a page implementation class, the work of the conversion is done by the servlet container, the name of the generated servlet is determined by the servlet container, and if the conversion error sends an error to the client ; If the conversion succeeds, it is further compiled by the servlet container (this is dynamically compiled) into a servlet class, after which the container loads and instantiates the class and executes the appropriate lifecycle method; The servlet container is not stupid for subsequent requests to the page, and it is tiring to convert it every time. So it checks that the JSP page has been modified since the last conversion, and if it is modified, it will be converted, compiled, and executed, and if not, execute an instance of the JSP class that already exists in memory. From the above description, you can see that the first request for a JSP page is more time-consuming, there is no solution to it. Of course it is. Configure all JSP pages to be converted and compiled when the application starts instead of taking the first request to do the work, precompile the JSP pages and deploy them as a servlet; there are tools available for this and some Web servers that provide this configuration, Here is not to elaborate, but I was using Tomcat, did not find this aspect of the relevant configuration, if the great god advice, thank you ah ...

second, the nature of JSP analysis

First of all, and JSP-related packages, as follows: javax.servlet.jsp: Contains the core interfaces and classes, the servlet container to use these interfaces and classes to convert JSP pages into a servlet, the most important thing is jsppage and httpjsppage;
Javax.servlet.jsp.el: Contains related classes and interfaces that support El Expressions in JSP
Javax.servlet.jsp.tagext: Contains the types used to develop custom tags, i.e. if you want to write a label yourself you must use the API here;
Javax.el: Provides API for Unified El; JSP transformation generated page class must implement or indirectly implement the Javax.servlet.jsp.JspPage interface, as you expected, this interface inherits the Javax.servlet.Servlet interface, as follows:
So that we can believe that the JSP page is really a servlet (I'm not a jive.) )。 In order to be intuitive, we look directly at JSP page conversion after the production of the Servlet class, by contrast to further explain the nature of JSP, the following is a JSP page index.jsp

<html>
<body>
<h2> Hello World! </ h2>
</ body>
</ html>
It can be seen that this is text composed of ordinary HTML tags (you lie to me, this is not JSP, this is HTML). As mentioned earlier, JSP pages are actually composed of HTML elements and Java code. Converted to the corresponding servlet, index_jsp.java is as follows. From the name, you can see that the name when jtomcat converted the jsp page into a servlet is composed of "name_jsp":
/ *
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat / 7.0.68
 * Generated at: 2016-04-16 12:01:36 UTC
 * Note: The last modified time of this file was set to
 * the last modified time of the source file after
 * generation to assist with modification tracking.
 * /
package org.apache.jsp;

import javax.servlet. *;
import javax.servlet.http. *;
import javax.servlet.jsp. *;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory ();

  private static java.util.Map <java.lang.String, java.lang.Long> _jspx_dependants;

  private volatile javax.el.ExpressionFactory _el_expressionfactory;
  private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map <java.lang.String, java.lang.Long> getDependants () {
    return _jspx_dependants;
  }

  public javax.el.ExpressionFactory _jsp_getExpressionFactory () {
    if (_el_expressionfactory == null) {
      synchronized (this) {
        if (_el_expressionfactory == null) {
          _el_expressionfactory = _jspxFactory.getJspApplicationContext (getServletConfig (). getServletContext ()). getExpressionFactory ();
        }
      }
    }
    return _el_expressionfactory;
  }

  public org.apache.tomcat.InstanceManager _jsp_getInstanceManager () {
    if (_jsp_instancemanager == null) {
      synchronized (this) {
        if (_jsp_instancemanager == null) {
          _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager (getServletConfig ());
        }
      }
    }
    return _jsp_instancemanager;
  }

  public void _jspInit () {
  }

  public void _jspDestroy () {
  }

  public void _jspService (final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    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");
      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 ("<html> \ r \ n");
      out.write ("<body> \ r \ n");
      out.write ("<h2> Hello World! </ h2> \ r \ n");
      out.write ("</ body> \ r \ n");
      out.write ("</ html> \ r \ n");
    } catch (java.lang.Throwable t) {
      if (! (t instanceof javax.servlet.jsp.SkipPageException)) {
        out = _jspx_out;
        if (out! = null && out.getBufferSize ()! = 0)
          try {
            if (response.isCommitted ()) {
              out.flush ();
            } else {
              out.clearBuffer ();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context! = null) _jspx_page_context.handlePageException (t);
        else throw new ServletException (t);
      }
    } finally {
      _jspxFactory.releasePageContext (_jspx_page_context);
    }
  }
}
From the above source code, index_jsp inherits the org.apache.jasper.runtime.HttpJspBase class, so what is this class? From the javaDoc of tomcat, it is as follows: JSP of Java Web Basics: I still know __Java in the vest. This class inherits HttpServlet and also implements JspPage and HttpJspPage interfaces. The body code in the JSP is converted into the content in the _jspService () method of the index_jsp class, and this method is called by the service () method in Httpbase, as follows:
    / **
     * Entry point into service.
     * /
    @Override
    public final void service (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        _jspService (request, response);
    }

    @Override
    public abstract void _jspService (HttpServletRequest request,
                                     HttpServletResponse response)
        throws ServletException, IOException;
When index_jsp inherits Httpbase, you must implement _jspService () method, so when the response comes, it can be called by the httpbase instance.
Third, JSP implicit objects. In fact, every time I see this part before, I will be very embarrassed, because I do not know how these implicit objects work And fear). By the way, this time, it is also a urge to myself. We know that every time the servlet initializes or accepts a request, the servlet container will pass some objects to the lifecycle method. Then the question comes, how does the JSP page accept these objects. These objects are implicitly added to the generated servlet class when the JSP page is converted into a servlet. See the servlet class generated by the JSP page above to see this. The following is the correspondence between implicit objects and types relationship:
Object type
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
config javax.servlet.ServletConfig
exception java.lang.Exception
out javax.servlet.jsp.JspWriter
pageContext javax.servlet.jsp.PageContext
page javax.servlet.jsp.HttpJspPage














The above objects can be used directly as if they already exist. Here are mainly three objects: out: The class of this instance directly inherits from java.io.Writer, so you can write the data directly and return it to the client with the response, like What we did in the servlet, response.getWriter (). Write (); page: indicates the page, which is basically useless; pageContext: This class indicates the context of this page, which can be used to manage and store the content used in this page Attributes, and from the source code generated above, several other objects can be obtained through this attribute, as follows;
application = pageContext.getServletContext ();
config = pageContext.getServletConfig ();
session = pageContext.getSession ();
out = pageContext.getOut ();
Another important role for pageContext is that it can store the attributes of various scopes. Since it is directly inherited from javax.servlet.jsp.JspContext, it can be operated in this way, with the following 4 scopes: APPLICATION_SCOPE SESSION_SCOPE REQUEST_SCOPE PAGE_SCOPE role The ranges are listed in descending order. The corresponding API is as follows, the scope can be specified using the above 4 scopes:
abstract public void setAttribute (String name, Object value, int scope)
In addition, you can also set properties that are only used on this page, that is, the page scope, as follows:
abstract public void setAttribute (String name, Object value)
Fourth, the content of JSP pages JSP pages include both template data and syntax elements. Previously, HTML tags and text were template data, and syntax elements were contained by <%%>. It can be said that all except the syntax elements are templates. data. Regarding the template data, we do not elaborate here, not our focus. Here we focus on the syntax elements. The syntax elements are mainly as follows: 1. The instruction is used to play a guiding role when the JSP page is converted into a servlet class. To put it plainly, it is to tell the JSP converter how to convert a JSP page into a servlet class. It can contain some data to add to the class during the conversion process. Since there are too many instructions, here we explain two more important, page instructions and include instructions. Page directive: As the name of this directive implies, this directive is used to explain the information contained in the entire page, how do we use it. The syntax is as follows:
<% @ attribute = value attribute = value%>
It has several important attributes, as follows:
<% @ page contentType = "text / html; charset = UTF-8" pageEncoding = "UTF-8" isErrorPage = "false"%>
<% @ page import = "java.util. *, java.nio.file. *" session = "true" buffer = "8kb" autoFlush = "true"%>
The description is as follows: contentType: This is too familiar to everyone, which is the content-type in http, which is returned by the ServletResponse instance setting each time; pageEncoding: is the page encoding of this page, if you have Chinese, you must be careful about this value, if not Can directly default (ISO-8859-1) isErrorPage: indicates whether this page is a page returned when an error occurs, can be used as the page returned when exception handling; import: it can be seen from the name that it corresponds to the java program Import keyword in the import dependency package; session: This attribute is used to indicate whether the page participates in session management, that is, whether the session plays a role in the page; buffer: specifies the buffer size of the out object, in kb, or Is none, which means no cache is used; autoFlush; indicates whether the buffer is automatically refreshed when the buffer is full, it will be automatically refreshed when true, if false, you must manually call response.getWriter (). Flush () to force a flush, this property If you look at the source code, it is defined in PrintWriter; Pay attention to several aspects: The page directive can be placed anywhere on the page, but note that the encoding involved in the above attributes must be placed first; the page directive can appear multiple times, but if the same attribute appears in multiple directives Their values must be the same, but the exception is import, it is accumulated; include directive: This directive is relatively simple to use, it is used to include another file in the current page, if your page is relatively large, you want to divide into multiple Pages representing different areas can be done using this directive. In addition, if part of the content is referenced in multiple pages, it can be made into a separate page and then included in other pages using this directive. The more familiar uses are as follows:
<html>
<body>
<% @ include file = "title.jsp"%>
<% @ include file = "/ jsp / content.jsp"%>
<% @ include file = "foot.jsp"%>
</ body>
</ html>
There are two issues to be aware of when using this command: The path of the included file: if the file attribute starts with "/", the path of the file starts with the root path of the web application on the server, which is an absolute path ; If not, the path is interpreted as a path relative to the page, that is, the included page file must be in the same folder as the page used by the directive; the type of file included: can be a JSP file, or It is a jspf file, it can also be a static file html 2. Script element Script element is to convert java code into a JSP page, there are three main forms: Scriptlet This is a small piece of Java code embedded in an HTML element, using <% .. ....%> is included as follows:
<%
Enumeration <String> enums = request.getHeaderNames ();
while (enums.hasMoreElements ()) {
String headerName = enums.nextElement ();
out.write (headerName + ":" + request.getHeader (headerName));
}
%>
Note: The variables defined in it are visible after the scriptlet, that is, they can be used directly. Expressions Expressions are actually wrappers for Scriptlets. They are wrapped by <% =%>. In fact, they directly assign the results of java operations or return values to the print () method of the implicit object out, avoiding us. To use out output in a scriptlet, use the following:
Now is <% = new Date (System.currentTimeMillis ())%>
Declarations Declarations are mainly used to declare variables and methods used in JSP pages. This is not recommended, but as a part of the script element, it is necessary to mention that the syntax includes the corresponding declaration section through <%!%>.
<%!
public String hello () {
return "Hello world";
}

%>
<% = hello ()%>
In fact, we said a lot about script elements above, and they are not commonly used in actual development. Those who know a little bit about web development know the MVC pattern. Using script elements obviously violates this pattern. In view of the emergence of EL tools later, more There is no need to use script elements (but some demos are still available). We can disable the use of script elements by configuring in the deployment descriptor, as follows:
<jsp-config>
<jsp-property-group>
<url-pattern> *. jsp </ url-pattern>
<scripting-invalid> true </ scripting-invalid>
</ jsp-property-group>
</ jsp-config>
Many properties can also be configured in jsp-config, which are not introduced here one by one. If you are interested, you can look at the schema file of the deployment descriptor.
3, Action Action will be compiled into Java code to perform an operation, a bit similar to the configuration through the text and then accept the request will be converted into executable code. There are many kinds of actions. They exist in the form of tags. In addition to the standard standards, there are some custom tags. I wo n’t talk about them here. There are too many. If you want to know, you can check the JSTL related information. Learn how to write custom tags. Here are two examples as examples: include: This action is used to dynamically include another resource. This can be a JSP page, a servlet, or an HTML static page. The syntax is as follows:
<jsp: include page = "world.jsp">
<jsp: param value = "name" name = "lmy" />
<jsp: param value = "age" name = "23" />
</ jsp: include>
Note the difference between it and the above include directive. The main instructions are as follows: The include directive occurs when the JSP page is converted into a servlet class. Therefore, the include directive is suitable for the inclusion of static pages, and the include action occurs at each request. Therefore, you can use the include action to pass parameters. The include action occurs when the request is accepted. The response of each included page can be up-to-date according to business logic. However, because the include directive works during page transitions, if the included page does not change, it is returned. The page content is always the same; if you want to use the mechanism of the include action to return the latest response when receiving a request, the included page must end in jsp; the implementation principle of the include directive and include action is actually, The include instruction includes a page, and the inclu action actually includes a URL address, so using the include action actually sends a request to the included page at the bottom (understand it). The specific principle is as follows. forward:
This we have encountered before in the Filter of Java Web Basics: filtering everything you don't want to see, through which you can turn to different resources, including JSP and servlet, the underlying implementation of this tag is through RequestDispatcher.forward () Implementation, the use of this tag is as follows:
<jsp: forward page = "world.jsp">
<jsp: param value = "name" name = "lmy" />
<jsp: param value = "age" name = "24" />
</ jsp: forward>
When forwarding, you can add some new request parameters as shown above. For the difference between forwarding and redirection, see the following link

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.