Static fields in JSP declaration

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

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

When I run the file, I got this error. Can anybody explain?

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

Answers


Don't do this in a JSP. Create a real Java class, if need be in flavor of a Javabean.

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

and use a Servlet class to do the business task:

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);
    }
}

which you map in web.xml as follows:

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

and create /WEB-INF/father.jsp as follows:

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

and invoke the FatherServlet by http://localhost:8080/contextname/father. The ${father2.count} will display the return value of father2.getCount().

To learn more about programming JSP/Servlets the right way, I recommend you to get yourself through those tutorials or this book. Good luck.


Using <%! ... %> syntax you decalre an inner class, which is non-static by default, so it can't contain static fields. To use static fields, you should declare the class as static:

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

However, BalusC's advice is right.


Need Your Help

Does MS Word have an equivalent of Range.GetSpellingSuggestions for grammar?

vba ms-word spell-checking office-2013 word-2013

In Microsoft Word 2013 VBA, you can call GetSpellingSuggestions on a Range that includes a spelling error to get a collection of (a) what the spelling error is and (b) what the proposed suggestions...

Case Sensitivity when querying SQL Server 2005 from .NET using OleDB

c# .net sql-server oledb case-sensitive

I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was ta...