2010-04-07 102 views
2
<%! 
class father { 
    static int s = 0; 
} 
%> 

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

当我运行该文件时,出现此错误。有人可以解释吗?JSP声明中的静态字段

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

回答

4

不要在JSP中这样做。创建一个真正的Java类,如果需要Javabean的味道。

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> 

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

要了解有关正确编程JSP/Servlet的更多信息,我建议您通过those tutorialsthis book。祝你好运。

6

使用<%! ... %>语法可以decalre一个内部类,默认情况下它是非静态的,因此它不能包含static字段。要使用static字段,应声明类为static

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

然而,BalusC的意见是正确的。