2010-04-07 97 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的意見是正確的。