问题
I have a simple UI class
public class HelloWorldUI extends UI {
@Override
protected void init(VaadinRequest request) {
System.out.println("Initialized !");
final VerticalLayout layout = new VerticalLayout();
layout.addComponent(new Label("Hello World !"));
setContent(layout);
}
@Override
public void detach() {
System.out.println("Detach !");
super.detach();
}
@Override
public void attach() {
System.out.println("Attach !");
super.attach();
}
}
When first time my UI was loaded , I see outputs at my console as
Attach !
Initialized !
It is OK and this is what I expected. But when I refresh the browser , my console outputs were
Attach !
Initialized !
Detach !
Amazing ! I think Detach !
may be produce first because (as I think) when browser was refreshed , detach()
method should be call and attach()
, init()
should be follow . But actually detach()
method will call after attach()
method. What's wrong my thinking ?
回答1:
Browser Refresh = New UI
Instance
When you refresh a browser window or tab, a new UI instance is created. So you see an attach message of a new UI
instance. The old UI
instance will be detached later.
This is default behavior in Vaadin 7. You may change that behavior with an annotation.
@PreserveOnRefresh
Adding @PreserveOnRefresh annotation to the UI
changes the behavior: No new UI
instance won't be created on refresh.
To quote the doc for this annotation:
Marks a UI that should be retained when the user refreshed the browser window. By default, a new UI instance is created when refreshing, causing any UI state not captured in the URL or the URI fragment to get discarded. By adding this annotation to a UI class, the framework will instead reuse the current UI instance when a reload is detected.
来源:https://stackoverflow.com/questions/25009160/does-detach-method-call-after-attach-method