Java Spring Recruitment Interview Sprint Series: Summary of JSP Knowledge

JSP knowledge summary

table of Contents

Introduction to JSP

  1. What is Java Server Pages?

JSP stands for Java Server Pages, which is a dynamic web development technology. It uses JSP tags to insert Java code in HTML pages. Tags usually start with <% and end with %>.
JSP is a Java servlet, mainly used to implement the user interface part of a Java web application. Web page developers write JSP by combining HTML code, XHTML code, XML elements, and embedded JSP operations and commands.

JSP obtains user input data through web forms, accesses databases and other data sources, and then dynamically creates web pages.

JSP tags have multiple functions, such as accessing databases, recording user selection information, accessing JavaBeans components, etc., and can also transfer control information and share information in different web pages.

  1. Why use JSP?

JSP programs and CGI programs have similar functions, but compared with CGI programs, JSP programs have the following advantages:

  • The performance is even better, because JSP can dynamically embed elements directly in HTML pages without the need to separately quote CGI files.
  • The server calls the compiled JSP file, instead of loading the interpreter and target script like CGI/Perl.
  • JSP is based on the Java Servlets API. Therefore, JSP has a variety of powerful enterprise-level Java APIs, including JDBC, JNDI, EJB, JAXP, and so on.
  • JSP pages can be used with servlets that process business logic. This mode is supported by the Java servlet template engine.
    Finally, JSP is an indispensable part of Java EE and a complete enterprise-level application platform. This means that JSP can use the simplest way to implement the most complex applications.
  1. Advantages of JSP

The following is a list of other benefits of using JSP:

  • Compared with ASP: JSP has two major advantages. First of all, the dynamic part is written in Java instead of VB or other MS special language, so it is more powerful and easy to use. The second point is that JSP is easy to transplant to non-MS platforms.
  • Compared with pure Servlets: JSP can easily write or modify HTML pages without having to face a large number of println statements.
  • Compared with SSI: SSI cannot use form data and cannot connect to a database.
  • Compared with JavaScript: Although JavaScript can dynamically generate HTML on the client, it is difficult to interact with the server, so it cannot provide complex services, such as database access and image processing.
  • Compared with static HTML: Static HTML does not contain dynamic information.

JSP-Velocity-FreeMarker comparison

  • JSP -> Velocity -> FreeMarker
    • JSP
      • advantage:
        1. Support is good. Official endorsement, numerous tag libraries, support for JSP tags, support for EL expression language, powerful functions, can write JAVA code
        2. Facilitate development and debugging.
      • Disadvantages:
        1. Destroyed the mvc structure
        2. jsp needs to be compiled into a class file for execution
    • Velocity: Produced by Apache, the earliest template language used to replace jsp
      • advantage:
        1. Strict mvc separation can be achieved
        2. It is said that the performance is better than jsp
        3. Easy to learn
      • Disadvantages:
        1. Few third-party tag libraries
        2. Difficult to debug
        3. Poor support for jsp tags
    • FreeMarker : Apache
      • advantage:
        1. Strict mvc separation can be achieved
        2. Built-in commonly used functions are powerful and easy to use
        3. Good support for jsp tags
      • Disadvantages:
        1. There are not as many third-party tag libraries as jsp
        2. Difficult to debug
  1. Pain points of using JSP
  • It is impossible to achieve true separation of dynamics and statics. Dynamic resources (JAVA code embedded in JSP) and static resources (HTML/CSS) are coupled together, and the server pressure is high. Once the server is unstable, the front and back ends will be down together, and the user experience is poor.
  • JSP must run in a web server that supports JAVA. For some purely static resources such as images/CSS/JS, etc., Nginx cannot be used, and the performance cannot be improved.
  • The first request will be slower. When the JSP is requested for the first time, it needs to be compiled into a servlet in the web server.
  • The efficiency is not as high as using html directly. Every time JSP is requested, it visits the servlert and then uses the output stream to output the html page.
  • JSP itself is loaded synchronously. If the page structure is complex, the response will be slow.

JSP structure

  1. JSP processing flow

JSP processing The
following steps show how the web server uses JSP to create web pages:

  • Just like other ordinary web pages, your browser sends an HTTP request to the server.
  • The web server recognizes that this is a request for a JSP web page, and passes the request to the JSP engine. It is done by using URL or .jsp file.
  • The JSP engine loads JSP files from the disk and then converts them into servlets. This conversion simply changes all template text to println() statements, and converts all JSP elements into Java code.
  • The JSP engine compiles the servlet into an executable class and passes the original request to the servlet engine.
  • A certain component of the Web server will call the servlet engine, and then load and execute the servlet class. During the execution process, the servlet generates HTML format output and embeds it in the HTTP response and submits it to the Web server.
  • The web server returns the HTTP response to your browser in the form of a static HTML page.
  • In the end, the web browser processes the HTML webpages dynamically generated in the HTTP response as if it were dealing with static webpages.

Under normal circumstances, the JSP engine checks whether the servlet corresponding to the JSP file already exists, and checks whether the modification date of the JSP file is earlier than the servlet. If the modification date of the JSP file is earlier than the corresponding servlet, then the container can determine that the JSP file has not been modified and the servlet is valid. This makes the entire process more efficient and faster than other scripting languages ​​(such as PHP).

In general, JSP web pages use another way to write servlets without becoming a Java programming master. Except for the interpretation stage, JSP web pages can almost be treated as an ordinary servlet.

JSP life cycle

  • JSP life cycle: compilation phase -> initialization phase -> execution phase -> destruction phase
    • Compilation stage: Servelt container compiles JSP into Servlet source file and generates Servlet class. When the browser requests a JSP page, the JSP engine will first check whether the file needs to be compiled. If this file has not been compiled, or has been changed since the last compilation, compile this JSP file.
    • Initialization stage: Load the Servlet class corresponding to JSP, create its instance, and call its initialization method. After the container loads the JSP file, it will first do some initialization work, calling the jspInit() method, and the initialization only needs to be done once.
    • Execution phase: Invoke the service method of the Servlet instance corresponding to the JSP.
    • Destruction phase: call the destruction method of the Servlet instance corresponding to the JSP, and then destroy the instance.
  • Sample code
<%!
public void jspInit() {
    System.out.println("JSP Init");
}

public void jspDestroy() {
    System.out.println("JSP Destory");
}
%>

JSP syntax

  • JSP declare variable methods, etc.
<%! declaration; [ declaration; ]+ ... %>
<%! int i = 0; %>
<%! int a, b, c; %>
  • JSP expression
<%= 表达式 %>
<p>
   今天的日期是: <%= (new java.util.Date()).toLocaleString()%>
</p>
  • JSP comments
<%-- 该部分注释在网页中不会被显示--%>
  • JSP instructions: JSP instructions are used to set attributes related to the entire JSP page.
<%@ directive attribute="value" %>
<%@ page ... %>	定义页面的依赖属性,比如脚本语言、error页面、缓存需求等等
<%@ include ... %>	包含其他文件
<%@ taglib ... %>	引入标签库的定义,可以是自定义标签
  • JSP behavior
<jsp:action_name attribute="value" />
jsp:include	用于在当前页面中包含静态或动态资源
jsp:useBean	寻找和初始化一个JavaBean组件
jsp:forward	从一个JSP文件向另一个文件传递一个包含用户请求的request对象
jsp:text	用于封装模板数据
...
  • JSP9 built-in objects
application: ServletContext类实例,与应用上下文有关
page: 类似Java类中的this关键字
pageContext: PageContext类的实例,提供对JSP页面所有对象以及命名空间的访问
config: ServletConfig类实例
out: PrintWriter类的实例,用于把结果输出到页面上
request: HttpServletRequest类的实例
respone: HttpServletResponse类的实例
session: HttpSession类的实例
exception: Exception类的对象,代表发生错误的JSP页面中对应的异常对象

JSP-HTTP status code

status code news description
200 OK Request confirmed
201 Created Complete when requested, new resource is created

JSP form processing

  • Form submission: getVSpost
  • Parameter request.getParameter("xxx")read: other has request.getParameterValues(), request.getParameterNames(),request.getInputStream()

JSP encoding settings

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
  • JSP page encoding: the encoding of the jsp file itself
<%@ page pageEncoding="UTF-8" %>
  • Web page display encoding
<%@ page contentType="text/html; charset=UTF-8" %>
  • HTML page encoding
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  • Web server input/output stream setting encoding
request.setCharacterEncoding("UTF-8")
response.setCharacterEncoding("UTF-8")
  • Web server response output stream
response.setContentType("UTF-8")
  • Their mutual influence and scope, and the order of their actions
  1. pageEncoding: It only specifies the encoding format of the JSP page itself, and has nothing to do with the encoding displayed on the page; when the
    container reads (file) or (database) or (string constant), it will be converted to Unicode for internal use, and the page is displayed When the
    internal Unicode is converted to the encoding specified by contentType, the page content is displayed;
    if the pageEncoding attribute exists, then the character encoding of the JSP page is determined by pageEncoding,
    otherwise it is determined by the charset in the contentType attribute. If the charset does not exist, The character encoding of JSP pages uses the
    default ISO-8859-1.

  2. contentType: specifies the MIME type and the character encoding method of the JSP page response. The default value of MIME type is "text/html";
    the default value of character encoding is "ISO-8859-1". MIME type and character encoding are separated by semicolons;

  3. The relationship between pageEncoding and contentType:

    1. The content of pageEncoding is only used for the encoding of jsp output, and will not be sent out as a header; it tells the web Server
      what encoding the jsp page is output according to, that is, the encoding of the response stream output by the web server;
    2. The first stage is to compile jsp into .java. It will read jsp according to the setting of pageEncoding, and the result will be translated
      into a unified UTF-8 JAVA source code (ie. java) from the specified encoding scheme .
    3. The second stage is the compilation from JAVAC's JAVA source code to java byteCode. No matter what encoding scheme is used when JSP is written, the
      result of this stage is all the UTF-8 encoding java source code. JAVAC uses UTF-8 encoding to read Take the
      java source code and compile it into a UTF-8 encoding binary code (ie. class), which is the JVM's specification for constant digit strings
      expressed in the binary code (java encoding).
    4. The third stage is when Tomcat (or its application container) loads and executes the JAVA binary code from stage 2, and the
      output result is what is seen on the client side. At this time, it is hidden in the parameter contentType of stage 1 and stage 2. It worked
  4. The setting method that has the same effect as contentType also has html page charset, response.setCharacterEncoding(),
    response.setContentType(), response.setHeader(); response.setContentType(),
    response.setHeader(); the priority is the best, followed by response.setCharacterEncoding(); The other is
    <%@page contentType="text/html; chareset=gbk"%>, and finally.

  5. Web page input encoding: When setting the page encoding <%@page contentType=“text/html; chareset=gbk”%>, the input encoding of the page is also specified; if the page display is set to UTF-8, then All page input of the user will be encoded in UTF-8; the server-side program must set the input encoding before reading the form input; after the form is submitted, the browser will convert the value of the form field to the byte value corresponding to the specified character set. Then encode the result bytes according to the HTTP standard URL encoding scheme. But the page needs to tell the server the encoding method of the current page; request.setCharacterEncoding() can modify the encoding of the serverlet to obtain the request, response.setCharacterEncoding(), can modify the serverlet to return the result Encoding.

Guess you like

Origin blog.csdn.net/weixin_43314519/article/details/113841357