In this example, our goal is to track the number of visits (the number of requests our application received). That count is kept in a bean component. Data represented by the bean is shared among multiple clients, thus we use application-based sharing.

To implement this behavior, we need a bean to store prime numbers, a servlet to populate the bean and store it in the ServletContext, and a JSP page to display the results. Since JSP context remains being single entity on JSP container it is quarantedd that out counter will be instantiated once and then shared between all sessions:

A bean counting context requests:

package test;

public class VisitCounter {

  public double increment() { ... }
  public void getCount() { ... }

A servlet updating counter on requests received:

import javax.servlet.*;
import javax.servlet.http.*;

public class VisitorServlet extends HttpServlet {

  public void doGet(

    HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    ServletContext context = getServletContext();
    VisitCounter counter;
    synchronized(this) {
      counter = 
      if (counter == null) {
        counter = new VisitCounter();
        context.setAttribute("counter", counter);
    String address = "showvisits.jsp";
    RequestDispatcher dispatcher = 

    dispatcher.forward(request, response);

And finally the page:

<jsp:useBean id="sampleBean" type="test.VisitCounter" scope="application" />

		<title>Application sharing</title>

			Request number:
			<jsp:getProperty name="counter" property="count" />