开发者

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 r开发者_运维百科un 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜