The JSP tag will run repeatedly.

Asked 2 years ago, Updated 2 years ago, 22 views

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JSP & Servlet Practice</title>
</head>
<body>
<%!
    int num = 1;
    String str = "Test string";
    List<String> arr = new ArrayList<>();

    int addNums(int n1, int n2) {
        return n1 + n2;
    }
%>

// [1]
<%
    System.out.println ("Hi JSP!");

    for (int i = 0; i < 5; ++i) {
        arr.add(str + " " + num);
        ++num;
    }

    for (String s : arr) {
        System.out.println(s);
    }
%>

<%
    if (num >= 5) {
%>
<p>If statement action</p>
<%
} } else {
%>
<p>else statement action</p>
<%
    }
%>

The value of num is <%=num%>.<br/>  // [2]
The value of <p>addNum(2, 3) is <%=addNums(2, 3)>.</p>
</body>
</html>

When you run the jsp file above, the final value of num at [2] should be 6, which is output to 11. The for statement should only be rotated 5 times, but the "test string" will be output 10 times more as follows:

 Hi JSP!
Test String 1
Test String 2
Test String 3
Test String 4
Test String 5
Hello, JSP!
Test String 1
Test String 2
Test String 3
Test String 4
Test String 5
Test String 6
Test String 7
Test String 8
Test String 9
Test String 10

[1] I don't know why this part is repeated so much.I ask for your help me.

jsp java

2022-09-21 11:41

1 Answers

The first request after WAS startup will come out as you intended, but every time you reload the page, the value of num will increase, and the number of loops of [1] will increase.

The problem is num and arr JSP declaration <%! It was declared by %>.

jsp as defined in declaratives variables will go into global variables of the jsp Not every request, local variables are initialized, maintaining the status of the global variables ; add arr (+ "" + str num) ++ num and that the result is we can only be over.

If you nag more, JSP is first changed to Java and compiled into class. If you look at how the code in the question changes to real Java:

public final class hashcode9831_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
                 org.apache.jasper.runtime.JspSourceImports {


    int num = 1;
    String str = "Test string";
    List<String> arr = new ArrayList<>();

    int addNums(int n1, int n2) {
        return n1 + n2;
    }

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

  // the outline of a plan

That's what happens. num and arr are the instance variables of the hashcode9831_jsp class.


2022-09-21 11:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.