Static variable initialization is done only once hence static counterPage variable's value increment each time the getCountPage() method is called.
Static variable initialization is done only once hence static counterPage variable's value increment each time the getCountPage() method is called.Description:
In this example there are two files index .jsp and PageCounter.jsp. The index.jsp display the number of time you refresh index.jsp page. Initially the counter in 1. It keep incrementing when you refresh the page.
Static variable initialization is done only once hence static counterPage variable?s value increment each time the getCountPage() method is called.
Code:
index.jsp
<%@page
import="Counter.PageCounter" contentType="text/html"
pageEncoding="UTF-8"%>
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
Count increase everytime when you refresh <br>
<%=PageCounter.getCountPage()%>
</body>
</html>
PageCounter.java
package Counter;
public class PageCounter {
private static int countPage;
public static synchronized int getCountPage()
{
countPage++;
return countPage;
}
}
Output:
In the browser it will show at first time '1' and when you refresh it keep on increasing.