Java Web JSP

Keywords: Java JSP Tomcat IntelliJ IDEA

9.JSP

reference resources: https://www.bilibili.com/video/BV12J411M7Sj?p=22

9.0 introduction

Many predecessors said that because of the separation of front and back ends, MVC has essentially become MC, JSP has no value of learning. Therefore, the content of JSP is only a superficial understanding, even for JSTL tags.

9.1 what is JSP

Java Server Pages: Java server-side pages, like servlets, are used for dynamic Web technology.

characteristic:

  • Writing JSP is like writing HTML
  • difference:
    • HTML only provides users with static data;
    • Java code can be embedded in JSP page to provide dynamic data for users;

9.2 JSP principle

Idea: how to execute JSP

  • There is no problem at the code level

  • Server internal work

    There is a work directory in tomcat;

    If IDEA uses tomcat, it will generate a work directory in Tomcat of IDEA

C:\Users \ username \. IntelliJIdea2019.3\system\tomcat \ any project \ work \ Catalina \ localhost \ 0006 \ session \ war \ ORG \ Apache \ JSP

Or open Tomcat's directory

Tomcat\work\Catalina\localhost\ROOT\org\apache\jsp

You can see that the page turns into a Java program

The browser sends requests to the server. No matter what resources are accessed, they are actually accessing the Servlet

JSP will eventually be converted into a Java class

Open the index? Jsp.java file, and you can find that this class inherits org.apache.jasper.runtime.HttpJspBase

Create a Maven and add the following dependencies. You can see the inheritance of HTTPJspBase:

<dependency>
    <groupId>tomcat</groupId>
    <artifactId>jasper-runtime</artifactId>
    <version>5.5.23</version>
</dependency>

JSP is essentially a Servlet. Look down:

As you can see, when writing JSP, it will be converted into this kind of tedious form that previous programmers have to do. JSP simplifies this process.

Take a look at the position of about the seventy seventh line:

// initialization
public void _jspInit() {
}

// Destruction
public void _jspDestroy() {
}

// JSPService
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response){...}
  1. Judgment request;

  2. Built in objects:

    final javax.servlet.jsp.PageContext pageContext;	// Page context
    javax.servlet.http.HttpSession session = null;		// session
    final javax.servlet.ServletContext application;		// applicationContext
    final javax.servlet.ServletConfig config;			// config
    javax.servlet.jsp.JspWriter out = null;				// out
    final java.lang.Object page = this;					// page: current
    javax.servlet.jsp.JspWriter _jspx_out = null;				// For the time being
    javax.servlet.jsp.PageContext _jspx_page_context = null;	// For the time being
    
    HttpServletRequest request							// request
    HttpServletResponse reponse							// response
    
  3. Code added before output page:

    response.setContentType("text/html");			//Set the page type of the response
    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;
    
  4. The above objects can be directly used in the JSP page with ${....}:

Hello JSP

Create a Maven project. The template is webapp. And create Hello.jsp in the webapp directory

As follows:

The code of Hello.jsp is as follows:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/21
  Time: 23:59
  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>
    <%
        String name = "duzhuan";
    %>
    name = <%= name %>
</body>
</html>

Except for lines 14 to 17, the rest are templates created automatically by IDEA.

Another recommendation: In JSP pages, <%!% > and <%% > and <% =% >

After Tomcat is configured, you can directly access Hello.jsp to view the effect:

Now go

C:\Users\user name\.IntelliJIdea2019.3\system\tomcat\Unnamed_JavaWeb_3\work\Catalina\localhost\0007_JSP_war\org\apache\jsp

View the situation (please note the corresponding location of user name and unnamed Java Web 3)

Open hello? Jsp.java

In the JSP page:

  • As long as it's Java code, it'll output intact
  • If it is HTML code, it will be converted to out.write(...) format and output to the front end

9.3 basic syntax of JSP

In the project of 9.2, the final file path is as follows:

rely on

Add the following dependency to pom.xml of the project in 9.2:

<!--   Servlet rely on     -->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
    <scope>provided</scope>
</dependency>

<!--   JSP rely on     -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

<!--   JSTL Expression dependency     -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>

<!--   stadard Label Library     -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

Only these dependencies are used in the following chapter.

Preface

Recommended links Hot deployment of Idea configuration , convenient for debugging

9.3.1 JSP expression

Any language has its own syntax, JSP as an application of Java technology, and some of its own extended syntax (you can understand, do not need to go deep), and JSP supports all of Java's syntax.

<% -- this is the comment for JSP --% >

<% = variable or expression% >
<%= new java.util.Date()%>

For example, create a new Fori.jsp in the webap directory, path:

The contents are as follows:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/22
  Time: 2:15
  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>
    <%
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        out.println("<h1>"+sum+"</h1>");
    %>
</body>
</html>

After deployment, visit Fori.jsp to get the following:

9.3.2 JSP script fragment

JSP can do some fun things. Add the following script fragments to Fori.jsp:

<%
	for(int i = 0; i< 5; i++){
%>
	<h1>Hello,World  <%=i%> </h1>
<%
	}
%>

Redeploy, visit Fori.jsp:

You can see the following code by opening the Fori_jsp.class:

9.3.3 JSP declaration

Reading forI ﹣ jsp.class, we can see that the code so far is written in the try {} of ﹣ JSP service method

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

How to write the code outside? Use <%!% >

Add the following code to Fori.jsp:

<hr>

<%!
    static {
    System.out.println("Loading Servlet!");
	}

	private int globalVar = 0;

	public void Saying(){
    	System.out.println("Sgt. Pepper's Lonely Heart's Club Band");
	}
%>

Redeploy to Tomcat, spooling:

Open forI ﹣ jsp.class to find the following code:

JSP declaration: will be compiled into JSP generated Java classes. Others will be generated into the JSP service method

9.4 JSP instructions

9.4.1 error page

9.4.1.1 modify in jsp page

  • Path of each file:

  • 1.jsp

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/22
  Time: 17:54
  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>
    <%
        int a = 1/ 0;
    %>
</body>
</html>

Obviously, there is an error. When visiting, the following page will be displayed:

It can be replaced with JSP.

Therefore, modify 1.jsp:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/22
  Time: 17:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="error/500.jsp" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        int a = 1/ 0;
    %>
</body>
</html>

Added <% @ page errorpage = "error / 500.jsp"% > so that 500.jsp can be displayed when an error occurs.

  • 500.jsp
<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/22
  Time: 19:20
  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>
    <img src="img/500.jpg" alt="Error 500">
</body>
</html>

If there is no graph for accessing 1. JSP, try changing line 14 to < img SRC = ".. / img / 500. JPG" ALT = "error 500" >. According to the tutorial, it should be < img SRC = ".. / img / 500. JPG" ALT = "error 500" >, but the actual operation here can't access the picture of 500.jpg, so it needs to be changed to the path of 500.jpg relative to 1.jsp. If there is a way to solve the problem of inconsistent relative paths in the future, it is not necessary to tangle.

This is due to the static introduction of JSP. You can see from the source code of 1.jsp:

That is to say, the HTML content of 500.jsp is copied and pasted directly.

The JSP problem should be solved by JSP. The corresponding statement of 500.jsp can be changed to:

<img src="<%=request.getContextPath()%>/img/500.jpg" alt="500Error">

EL expressions, which I'll talk about later.

  • 500.jpg is a picture of 500Error found on the Internet.

Visit 1.jsp. At this time, the page displays as follows:

9.4.1.2 by modifying web.xml

Obviously, the above method is very cumbersome. At least compared with this method, the first way is to write an errorPage on each page.

The same effect can be achieved by modifying web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                               http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">
  
  <error-page>
    <error-code>404</error-code>
    <location>/error/404.jsp</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/error/500.jsp</location>
  </error-page>
</web-app>

Delete the <% @ page errorpage = "error / 500. JSP"% >

404.jsp any page, for example:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/22
  Time: 22:45
  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>
    <h1>Error 404</h1>
</body>
</html>

Restart Tomcat (for non hot deployment, you need to restart Tomcat to modify web.xml and Java code). Visit 1.jsp to display:

Visit any address that doesn't exist:

9.4.1.3 public page

For example, in this part of station B, each page has.

This is the public page. It is usually placed in the common folder. Here is the path:

header.jsp

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/23
  Time: 22:57
  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>
    <h1>Header</h1>
</body>
</html>

footer.jsp

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/23
  Time: 22:57
  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>
    <h1>Footer</h1>
</body>
</html>

2.jsp

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/23
  Time: 22:59
  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>
    <%@include file="/common/footer.jsp"%>
    <h1>Network subject</h1>
    <%@include file="common/footer.jsp"%>
</body>
</html>

Redeploy Tomcat and visit 2.jsp. You can see:

Of course, you can do the same with jsp tags. Modify 2.jsp, only lines 18 to 23 are added:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/23
  Time: 22:59
  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>
    <%@include file="common/header.jsp"%>
    <h1>Network subject</h1>
    <%@include file="common/footer.jsp"%>

    <hr>

    <%-- JSP Label --%>
    <jsp:include page="/common/header.jsp"></jsp:include>
    <h1>Web body</h1>
    <jsp:include page="/common/footer.jsp"></jsp:include>

</body>
</html>

although

Visit 2.jsp after redeployment to see:

Open the file ﹣ 2 ﹣ jsp.java generated by it, and find the following statements:

Therefore, <% @ include% > will combine the two pages into one (explain the problem that the previous path does not show the picture), and the < jsp: include > splicing page is essentially several different pages. Generally, it is more flexible to use < jsp: include > (but now no one uses JSP...).

9.5 JSP's 9 built-in objects and their scopes

9.5.1 built in objects

  • PageContext store
  • Request store
  • Response
  • Session storage
  • Application [ServletContext] store
  • config[ServletConfig]
  • out
  • page
  • exception

Create a pageContextDemo01.jsp file in the webapp directory. The content is as follows:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/23
  Time: 23:54
  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>
    <%
      pageContext.setAttribute("name1","a1");
      request.setAttribute("name2","a2");
      session.setAttribute("name3","a3");
      application.setAttribute("name4","a4");
    %>
    <%
    // Take out the value (the code will be changed to java code unchanged here, and apply / / for comments)
    // In order to learn, do not take directly, but through the way to find
        String  naem1 = (String) pageContext.findAttribute("naem1");
        String  naem2 = (String) pageContext.findAttribute("naem2");
        String  naem3 = (String) pageContext.findAttribute("naem3");
        String  naem4 = (String) pageContext.findAttribute("naem4");
        String  naem5 = (String) pageContext.findAttribute("naem5");
    %>

    <%--  Use EL Expression access  --%>
    <h1>${name1}</h1>
    <h1>${name2}</h1>
    <h1>${name3}</h1>
    <h1>${name4}</h1>

    <%--  The following value does not exist  --%>
    <h1>${name5}</h1>

</body>
</html>

Redeploy Tomcat and visit pageContextDemo01.jsp to see:

If line 37 is changed to the form of < H1 > <% = name5% > < H1 >, the access after redeployment can see:

9.5.2 scope

<%
// Saved data is only valid on one page
pageContext.setAttribute("name1","a1");

// The saved data is only valid in one request, and the request forwarding will carry this page
request.setAttribute("name2","a2");

// Saved data is only valid in one session, from opening browser to closing browser
session.setAttribute("name3","a3");

// The saved data is valid in the server, from opening the server to shutting down the server
application.setAttribute("name4","a4");
%>

Create pageDemo02.jsp in the webapp directory. The code is as follows. Just copy and paste the part from pageContextDemo01.jsp:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/24
  Time: 0:27
  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>
    <%
        // Take out the value (the code will be changed to java code unchanged here, and apply / / for comments)
        // In order to learn, do not take directly, but through the way to find
        String  naem1 = (String) pageContext.findAttribute("naem1");
        String  naem2 = (String) pageContext.findAttribute("naem2");
        String  naem3 = (String) pageContext.findAttribute("naem3");
        String  naem4 = (String) pageContext.findAttribute("naem4");
        String  naem5 = (String) pageContext.findAttribute("naem5");
    %>
    
    <%--  Use EL Expression access  --%>
    <h1>${name1}</h1>
    <h1>${name2}</h1>
    <h1>${name3}</h1>
    <h1>${name4}</h1>
    
    <%--  The following value does not exist  --%>
    <h1><%=naem5%></h1>
</body>
</html>

After deployment, visit pageDemo02.jsp to see (for cold deployment, you need to visit pageContextDemo01.jsp to assign a value first):

Visit the source code of pageContext.setAttribute(), and find that abstract public void setAttribute(String name, Object value, int scope) exists;

To find its implementation class:

There is a code like this:

public void setAttribute(String name, Object attribute, int scope) {
    switch(scope) {
        case 1:
            this.mPage.put(name, attribute);
            break;
        case 2:
            this.mRequest.put(name, attribute);
            break;
        case 3:
            this.mSession.put(name, attribute);
            break;
        case 4:
            this.mApp.put(name, attribute);
            break;
        default:
            throw new IllegalArgumentException("Bad scope " + scope);
    }

}

At the same time, PageContentImpl inherits PageContent. Open it, and you can see the following code when retrieving:

/**
     * Page scope: (this is the default) the named reference remains available
     * in this PageContext until the return from the current Servlet.service()
     * invocation.
     */
public static final int PAGE_SCOPE		= 1;

/**
     * Request scope: the named reference remains available from the 
     * ServletRequest associated with the Servlet until the current request 
     * is completed.
     */

public static final int REQUEST_SCOPE	= 2;

/**
     * Session scope (only valid if this page participates in a session):
     * the named reference remains available from the HttpSession (if any)
     * associated with the Servlet until the HttpSession is invalidated.
     */

public static final int SESSION_SCOPE	= 3;

/**
     * Application scope: named reference remains available in the 
     * ServletContext until it is reclaimed.
     */

public static final int APPLICATION_SCOPE	= 4;

This means that you can define the scope of something by yourself

Create pageDemo03.jsp in the webapp directory with the following code:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/24
  Time: 0:51
  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>
    <%
        pageContext.setAttribute("hello1","hello1",PageContext.SESSION_SCOPE);
    %>
</body>
</html>

It is equivalent to session.setAttribute().

JSP to get the value is similar to the JVM's parent delegation mechanism.

9.5.3 by the way content - request forwarding

Create pageContentDemo02.jsp in the webapp directory, as follows:

<%--
  Created by IntelliJ IDEA.
  User: HuangDekai
  Date: 2020/4/24
  Time: 2:12
  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>
    <%
        pageContext.forward("/2.jsp");
    %>
</body>
</html>

After restarting Tomcat, access pageContextDemo03.jsp and the result is as follows:

Equivalent to request. Getrequestdispatcher ('/ 2. JSP'). Forward (request, response);

  • Request: the client sends a request to the server, and the generated data is useless after the user finishes reading, such as: news, useless after the user finishes reading

  • session: the client sends a request to the server, and the generated data is useful after the user has used it for a while, such as: shopping cart; Hystrix

  • application: the client sends a request to the server. One user runs out of data. Other users may use it, such as chat data.

Posted by reivax_dj on Fri, 24 Apr 2020 01:51:15 -0700