Wicket 8: Comfortable instance variables


This is part 8 of a series about Wicket.

In JSP/Servlets you should not use instance variables; in Wicket it’s a comfort.

Let’s consider this servlet.

public class Servlet1 extends HttpServlet {
   private Integer number = 0;
   public void doGet(HttpServletRequest request, 
      HttpServletResponse response) 
      throws ServletException, IOException {
      number = number + 1;
      response.getWriter().
      println("Instance variable: " + number);
   }
}

If you open two different browsers and hit the refresh button several times, you’ll see that the number is incremented with every request. This happens because a servlet gets initialized once and serves the various requests with different threads.

Let’s see this servlet as well:

public class Servlet1 extends HttpServlet {
   private Integer number = new Random().nextInt();
   public void doGet(HttpServletRequest request, 
      HttpServletResponse response) 
      throws ServletException, IOException {
      response.getWriter().
      println("Instance variable: " + number);
   }
}

Similarly, in this second servlet the number shown is always the same as if the state was static and final.

Fortunately in Wicket every WebPage is a plain Java object.

For example consider Page.html

<html>
   <body>
      <h3 wicket:id="number"></h3>
   </body>
</html>
</pre>

and Page.java

public class Page extends WebPage {
   private Integer number = 0;
   public Page() {
      number = number + 1;
      add(new Label("number", "Instance variable: " + number));
   }
}

The result is what we really expect. How about this.

public class Page extends WebPage {
   private Integer number = new Random().nextInt();
   public Page() {
      add(new Label("number", "Instance variable: " + number));
   }
}

Just deploy it and hit refresh a few times: A new number is shown every time!

Review

Instance variables of a web page are a great convenience, in contrast to what happens with a servlet.

WebPage objects are plain Java objects.

One Response to Wicket 8: Comfortable instance variables

  1. Proactive says:

    Sir, I can curious about the widget you are using. Thank you sir forgive my english.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: