Peter
Peter

Reputation: 1894

Wicket: Define Application wide variable

I wanted to make a little "log" on what the user is doing. I have different panels and all of these have Ajax functions such as "onclick", "onevent" and "onchange". What I planned was to define an Application wide ArrayList of Strings to log all the things.

I wrote following into WicketApplication.java

public class WicketApplication extends WebApplication {

private List<String> log = new ArrayList<String>();

@Override
public Class<? extends WebPage> getHomePage() {
    //code
}

@Override
public void init() {
    //code
}

public List<String> getLog() {
    return log;
}

public void setLog(List<String> log) {
    this.log = log;
}}

Then in one of my panels:

public class Foo extends Panel{
private static final long serialVersionUID = 1L;
private WicketApplication wapp = (WicketApplication) Application.get();

public Foo(String id){
    super(id);
}

public void bar(){
    List<String> protocol = wapp.getLog();
    protocol.add(foo.getBarName() + " has been added to " + selectedKontakt.getObject().getName());
    wapp.setLog(protocol);
}
}

In a next panel I tried to create a new reference to WicketApplication. But it seems not to be the same.
Now I have these questions:

wapp <----- field that is causing the problem

Is there any other way to create an Application wide variable?

Upvotes: 0

Views: 462

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

I think you are doing it wrong (on multiple levels).

Firstly: if you want to log, use a Logging framework. E.g. LogBack, preferably accessed through SLF4J

Secondly: if you don't want to use a log framework, create a log service (a dedicated object, not the Wicket Application), use Dependency Injection to inject the log service into all components where you need it. Wicket Supports both Spring and Guice

Third: Static access to the WebApplication as suggested by the accepted answer sounds like a very bad idea (but it is apparently suggested by Wicket, to be fair).

Upvotes: 3

Jacek Cz
Jacek Cz

Reputation: 1906

Normal way of use is (static) method. Its typical, don't be afraid.

MyApllication m = MyApllication.get();

So is genrally easy in every wicket object. Usually "statically overrided" to return correct type, (and can give additional control).

public static MyApllication getMyApplication() {
        return (MyApllication) get();
    }

or

 public static MyApllication get() {
        return (MyApllication ) WebApplication.get();
    }

When this static method returns correct type, Your problem is resolved.

Analyse how is build AuthenticatedWebApplication over WebApplication (or WebApplication over Application) , its from Wicket team and seems be canonical

BTW I You will have idea access / execute actions dependent on user / session similar idea exist : WebSession override in MySession

Upvotes: 2

Related Questions