Java Web Development

Time:2020-2-18

Java web development learning notes.

1、 Introduction to JSP

JSP and PHP, ASP, ASP. Net and other languages are similar, running in the server-side language.

JSP (full name java server pages) is a kind of technical standard which is advocated by Sun Microsystems company and participated by many companies to enable software developers to respond to client requests and dynamically generate HTML, XML or other format documents.

JSP technology is based on Java language as script language. JSP Web page provides an interface for the whole Java library unit on the server side to serve HTTP applications.

JSP file suffix is*.jsp

The web application developed by JSP can be used across platforms, running on Linux and windows.

JSP is a java servlet,Mainly used to implement the user interface part of Java Web Application。 Web developers write JSPS by combining HTML code, XHTML code, XML elements, and embedded JSP operations and commands.

Java learning roadmap:
Java Web Development

2、 Directory structure of Tomcat server

Java Web Development

Tomcat catalog file
Java Web Development

WEB-INF
The bytecode file generated in the classes directory
Jar package in lib directory

Tomcat installation directory

➜  tomcat pwd
/WEB/java/tomcat

Start the Tomcat command:

➜  sudo sh ./bin/startup.sh

WEB-INF directory structure

  1. WEB-INF is the safe directory of Java Web applications. The so-called security directory is a directory that the client cannot access, and only the server can access.
  2. Web.xml, project deployment file
  3. Classes folder to place *. Class files
  4. Lib folder, used to store the required jar package

Web.xml configuration default welcome file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

3、 JSP syntax

1. JSP instruction

Java Web Development

Java Web Development

For example: index.jsp

<%--
  Created by IntelliJ IDEA.
  User: kaiyiwang
  Date: 18/3/5
  Time: 00:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  $END$
  </body>
</html>

2. JSP comments

Java Web Development

//HTML comments
<! -- HTML comment, page not displayed, visible in client code -- >

//JSP comments
[% -- JSP comment, page not displayed, not visible in client code --% >

<%
//Single line notes

/*Multiline comment*/
%>

3. JSP script

Code executed in JSP script

Syntax:

<% java code% >

Example:

<%--
  Created by IntelliJ IDEA.
  User: kaiyiwang
  Date: 18/3/5
  Time: 00:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%
    //Single line notes
    /*
      multiline comment
     */

    Out. Println ("script code test here");

  %>
  </body>
</html>

4. JSP declaration

Declaring a variable or method in a JSP page
Syntax:

<%! Java code% >
<body>

  <%!
    
    
    String name = "Jacky Cheung"; // declare a string variable


      /**
       *Declare a function that returns an integer value
       * @param x
       * @param y
       * @return
       */
    int add(int x, int y)
    {
       return x + y;
    }
  %>

  <%
    //Single line notes
    /*
      multiline comment
     */

    Out. Println ("here is script code test, ha ha");

    out.println(name);
    int sum = add(2, 3);
    out.println(sum);


  %>
  </body>

5. JSP expression

The script language expression contained in a JSP expression is first converted to string and then inserted where the expression appears.

Since the value of the expression is converted to a String, you can use the expression in a line of text regardless of whether it is an HTML tag.

An expression element can contain any expression that conforms to the Java language specification, but you cannot use a semicolon to end the expression.

Expressions executed in JSP pages
Syntax:

<% = expression% > // Note: expression does not end with a semicolon

Example:

<body>

  <%!


    String name = "Jacky Cheung"; // declare a string variable


      /**
       *Declare a function that returns an integer value
       * @param x
       * @param y
       * @return
       */
    int add(int x, int y)
    {
       return x + y;
    }
  %>

  <%
    //Single line notes
    /*
      multiline comment
     */

    Out. Println ("here is script code test, ha ha");

    out.println(name);
    int sum = add(2, 3);
    out.println(sum);
  %>
  <br/>

  Hello, < name% > < br / >
  x+y=<%=add(1, 10)%>

  </body>

4、 JSP page lifecycle

Java Web Development

Java Web Development

Q & A:
When a user requests a JSP page for the first time, the first method to be executed is ()

  • A: Construction method
  • B: jspInit()
  • C:jspService()
  • D:jspDestroy()


Choose a for the answer.
Analysis:
When a user requests a JSP page for the first time, the first method to be executed is the construction method.
After converting to class file, he will create an instance of Servlet, then call the construction method of Servlet, then call jspInit () method.

(1) the JSP engine first converts the JSP file into a java source file (servlet). If any syntax error is found in the JSP file during the conversion, the conversion process will be interrupted and the error information will be output to the server and client.

(2) If the conversion is successful, the JSP engine uses javac to compile the Java source file into the corresponding class file.

(3) Create an instance of the servlet (JSP page conversion result). The JSP init() method of the servlet is executed, and the JSP init() method is executed only once in the servlet life cycle.

Small test knife

Using expression and script to print multiplication table

Java Web Development

Example:

<%--
  Created by IntelliJ IDEA.
  User: kaiyiwang
  Date: 18/3/5
  Time: 00:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    < title > Print multiplication table
  </head>
  <body>

  <%!

      /**
       *Print multiplication table
       * @return
       */
    String printMultiTable()
    {
      String s = "";

      for(int i=1; i <= 9; i++)
      {
        for(int j=1; j <= i; j++)
        {
          s += i + "*" + j + "=" + (i * j) + "&nbsp;&nbsp;&nbsp;&nbsp;";
        }

        s += "<br/>";
      }

      return s;

    }
    
    
      /**
       *JSP built-in out object, called in script mode, print the multiplication table
       *
       * @param out
       */
    void printMultiTable2(JspWriter out) throws Exception
    {
      for(int i=1; i <= 9; i++)
      {
        for(int j=1; j <= i; j++)
        {
          out.println(i + "*" + j + "=" + (i * j) + "&nbsp;&nbsp;&nbsp;&nbsp;");
        }

        out.println("<br/>");
      }

    }


  %>

<span>Expression printing</span>
<%=printMultiTable() %>
  
  
<br/>
 <span>Script printing, note that there is semicolon after function call</span>
<% printMultiTable2(out); %>


  </body>
</html>

Print results:

1*1=1    
2*1=2    2*2=4    
3*1=3    3*2=6    3*3=9    
4*1=4    4*2=8    4*3=12    4*4=16    
5*1=5    5*2=10    5*3=15    5*4=20    5*5=25    
6*1=6    6*2=12    6*3=18    6*4=24    6*5=30    6*6=36    
7*1=7    7*2=14    7*3=21    7*4=28    7*5=35    7*6=42    7*7=49    
8*1=8    8*2=16    8*3=24    8*4=32    8*5=40    8*6=48    8*7=56    8*8=64    
9*1=9    9*2=18    9*3=27    9*4=36    9*5=45    9*6=54    9*7=63    9*8=72    9*9=81    

5、 JSP built in objects

JSP built-in object, also known as implicit object, is the Java object provided by JSP container for each page,Developers can use them directly without explicitly declaring them。 JSP implicit objects are also known asPredefined variables

Nine implicit objects supported by JSP:

Java Web Development

JSP built-in object is a set of objects created by web container, which is not applicable to the built-in objects that can be used when new is created.

<%
    int[] value = {60, 20, 25};
    
    for(int i:value){
      out.println(i);
    }
  %>

6、 JSP Fundamentals

The essence of JSP is servlet. When the user sends the request to the specified servlet, the servlet uses the output stream to generate the HTML page dynamically, including each static HTML tag and all the content appearing in the HTML page.

Example code:
http://localhost:8080/webDemo/index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
     <meta charset="UTF-8">
    < title > my first JSP page < / Title >
</head>
<body>
<h1>Welcome to my first JSP page. </h1>

<! -- here is the java script -- >
<%
for(int i = 0; i < 5; i++)
{
    // out.println("<font size='" + i + "'>");
    // out.println(i);
%>
JSP principle analysis < / font > < br / >
<%}%>


</body>
</html>

Output results:

Java Web Development

On the surface, JSP pages no longer need Java classes,It seems to be completely divorced from Java's object-oriented characteristics。 In fact, the essence of JSP is still servlet (a special Java class). Every JSP page is a servlet instance – JSP page is compiled into servlet by the system, and servlet is responsible for responding to user’s request. For tomcat, the servlet generated by JSP page is placed under the web application corresponding to the work path.

After Tomcat is started, you canwork/Catalina/localhost/webDemo/org/apache/jspFind the following file in the directory (the name of this web application is webdemo, and the name of the JSP page above is index. JSP):index_jsp.javaandindex_jsp.class

Java Web Development

These two files are generated by Tomcat. Tomcat generates java files and class files corresponding to the servlet according to the JSP page

Below isindex_jsp.javaFile source code, which is a special Java class, is a servlet class.
index_jsp.java

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.73
 * Generated at: 2018-04-15 16:46:57 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;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("\n");
      out.write("<html>\n");
      out.write("<head>\n");
      out.write("\t <meta charset=\"UTF-8\">\n");
      Out. Write ("\ T < title > my first JSP page < / Title > \ n");
      out.write("</head>\n");
      out.write("<body>\n");
      Out. Write ("< H1 > welcome to my first JSP page. </h1>\n "";
      out.write("\n");
      Out. Write ("<! -- here is the java script -- > \ n");

for(int i = 0; i < 5; i++)
{
    // out.println("<font size='" + i + "'>");
    // out.println(i);

      out.write("\n");
      Out. Write ("JSP principle analysis < / font > < br / > \ n");
}
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("</body>\n");
      out.write("</html>");
    } 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);
    }
  }
}

Related article: Java Web basic learning

Recommended Today

Laravel service container must know

The article was forwarded from the professional laravel developer community. Original link: https://learnku.com/laravel/t To learn how to build an application with laravel is not only to learn how to use different classes and components in the framework, but also to remember allartisanCommand or all helper functions (we have Google). Learning to code with laravel is […]