2010-04-07 6 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로 사용하지 마십시오. Javabean의 풍미가 필요한 경우 실제 Java 클래스를 작성하십시오. 다음과 같이

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에지도 :

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

및 비즈니스 작업을 수행하는 서블릿 클래스를 사용

<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> 

을 입력하고 FatherServlethttp://localhost:8080/contextname/father으로 호출하십시오. ${father2.count}father2.getCount()의 반환 값을 표시합니다.

올바른 방법으로 JSP/Servlet을 프로그래밍하는 방법에 대해 자세히 알아 보려면 those tutorials 또는 this book을 직접 방문하는 것이 좋습니다. 행운을 빕니다.

6

<%! ... %> 구문을 사용하면 기본적으로 비 정적 인 내부 클래스를 decalre하므로 static 필드를 포함 할 수 없습니다. static 필드를 사용하려면 static로 클래스를 선언해야합니다

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

그러나 BalusC의 조언 권리입니다.