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.