JSP声明中的静态字段

时间:2010-04-07 20:29:43

标签: java jsp static

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

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

当我运行该文件时,我收到此错误。有人可以解释一下吗?

The field s cannot be declared static; static fields can only be declared in static or top level types.

2 个答案:

答案 0 :(得分:7)

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

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

然而,BalusC的建议是正确的。

答案 1 :(得分:4)

不要在JSP中执行此操作。如果需要Javabean的风格,请创建一个真正的Java类。

public class Father {
    private static int count = 0;
    public void incrementCount() {
        count++;
    }
    public int getCount() {
        return count;
    }
}

并使用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);
    }
}
您在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>

并按如下方式创建/WEB-INF/father.jsp

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2595687</title>
    </head>
    <body>
        <p>${father2.count}
    </body>
</html>

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

要了解有关以正确方式编写JSP / Servlet的更多信息,建议您完成those tutorialsthis book。祝你好运。