Hanno Fietz
Hanno Fietz

Reputation: 31370

Where does session data belong in Wicket?

Since Wicket automatically manages session state by serializing the components in my page, I'm left wondering, at which level I should attach my state data. More specifically, it seems like a bug I'm having is caused by the WebApplication object being shared among sessions.

I'm guessing, the third bullet point depends on object identity. What does Wicket use to determine that, equals() (like, is it using a Map)?

The data I attached to the application object is state I would need in many pages, so I didn't attach it to the page objects. Is that the correct way to do it in Wicket?

Upvotes: 2

Views: 5254

Answers (1)

biziclop
biziclop

Reputation: 49744

  1. Yes, that's the point of having an Application object. You can store and access application-wide data (usually config) through your Application subclass at any point.
  2. No. There are cases when you need to share session data across multiple pages where storing it in a Session object is more adequate. (An example could be a user login, which definitely belongs to the session and may be used by any page.) Of course you can pass the data around between the pages but it's not a very good strategy. Where the cutoff point is will be your decision: if data is shared between two pages, you might want to pass it from one to the other, if there are 20 pages, you definitely won't want to.
  3. You're not supposed to reuse component instances across different pages. Of course you'll reuse the class but you'll have to construct a new one on each page. This is exactly where storing data in the Session object might come handy.

To clarify: The number of pages sharing state is an indication of where to put the data, but what really matters is how tightly you want the items sharing data to be coupled:

If you pass data as parameters between pages, they will form a tightly coupled group. Depending on what the pages represent, this might be desirable. An example for this may be a wizard-like sequence of pages, with each page knowing what the pages before and after are.

But in the login example we see the opposite: the component populating the login name (probably some kind of login form) must not know about what other components are going to use it. So the logical solution is to store the login name in the session and let each component fetch it as and when they need it.

There are multiple ways to get hold of the current Session object. Check the documentation of the class to see how.

To summarize the information there: Wicket discourages type-unsafe session properties by not providing generic setProperty-like methods. Instead, you are supposed to extend Session, or for most projects, more adequately, WebSession and place typesafe properties in that class. You then override newSession on your application class.

Upvotes: 7

Related Questions