JSP声明中的静态字段

Sta*_*ust 2 java static jsp

<%!
class father {
    static int s = 0;
}
%>

<%
father f1 = new father();
father f2 = new father();
f1.s++;
out.println(f2.s); // It must print "1"
%>
Run Code Online (Sandbox Code Playgroud)

当我运行该文件时,我收到此错误.谁能解释一下?

The field s cannot be declared static; static fields can only be declared in static or top level types.
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 7

使用<%! ... %>语法,您可以对内部类进行decalre,默认情况下它是非静态的,因此它不能包含static字段.要使用static字段,您应该将类​​声明为static:

<%! 
    static class father { 
        static int s = 0; 
    } 
%>
Run Code Online (Sandbox Code Playgroud)

但是,BalusC的建议是正确的.


Bal*_*usC 5

不要在 JSP 中这样做。如果需要具有 Javabean 的风格,则创建一个真正的 Java 类。

public class Father {
    private static int count = 0;
    public void incrementCount() {
        count++;
    }
    public int getCount() {
        return count;
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用 Servlet 类来完成业务任务:

public class FatherServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Father father1 = new Father();
        Father father2 = new Father();
        father1.incrementCount();
        request.setAttribute("father2", father2); // Will be available in JSP as ${father2}
        request.getRequestDispatcher("/WEB-INF/father.jsp").forward(request, response);
    }
}
Run Code Online (Sandbox Code Playgroud)

你映射web.xml如下:

<servlet>
    <servlet-name>fatherServlet</servlet-name>
    <servlet-class>com.example.FatherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>fatherServlet</servlet-name>
    <url-pattern>/father</url-pattern>
</servlet-mapping>
Run Code Online (Sandbox Code Playgroud)

并创建/WEB-INF/father.jsp如下:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2595687</title>
    </head>
    <body>
        <p>${father2.count}
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

并调用FatherServletby http://localhost:8080/contextname/father。该${father2.count}显示的返回值father2.getCount()

要了解有关以正确方式编程 JSP/Servlet 的更多信息,我建议您阅读这些教程本书。祝你好运。