Class Navigator
- java.lang.Object
-
- com.vaadin.navigator.Navigator
-
- All Implemented Interfaces:
Serializable
public class Navigator extends Object implements Serializable
A navigator utility that allows switching of views in a part of an application.The view switching can be based e.g. on URI fragments containing the view name and parameters to the view. There are two types of parameters for views: an optional parameter string that is included in the fragment (may be bookmarkable).
Views can be explicitly registered or dynamically generated and listening to view changes is possible.
Note that
Navigatoris not a component itself but uses aViewDisplayto update contents based on the state.- Since:
- 7.0
- Author:
- Vaadin Ltd
- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classNavigator.ClassBasedViewProviderA ViewProvider which maps a single view name to a class to instantiate for the view.static classNavigator.ComponentContainerViewDisplayA ViewDisplay that replaces the contents of aComponentContainerwith the activeView.static classNavigator.EmptyViewEmpty view component.static classNavigator.PushStateManagerANavigationStateManagerusing path info, HTML5 push state andPage.PopStateEvents to track views and enable listening to view changes.static classNavigator.SingleComponentContainerViewDisplayA ViewDisplay that replaces the contents of aSingleComponentContainerwith the activeView.static classNavigator.StaticViewProviderA ViewProvider which supports mapping a single view name to a single pre-initialized view instance.static classNavigator.UriFragmentManagerANavigationStateManagerusing hashbang fragments in the Page location URI to track views and enable listening to view changes.
-
Field Summary
Fields Modifier and Type Field Description protected ViewDisplaydisplayTheViewDisplayused by the Navigator.protected NavigationStateManagerstateManagerTheNavigationStateManagerthat is used to get, listen to and manipulate the navigation state used by the Navigator.protected UIuiTheUIbound with the Navigator.
-
Constructor Summary
Constructors Modifier Constructor Description protectedNavigator()Creates a navigator.Navigator(UI ui, NavigationStateManager stateManager, ViewDisplay display)Creates a navigator.Navigator(UI ui, ViewDisplay display)Creates a navigator that is tracking the active view using URI fragments of thePagecontaining the given UI.Navigator(UI ui, ComponentContainer container)Creates a navigator that is tracking the active view using URI fragments of thePagecontaining the given UI and replacing the contents of aComponentContainerwith the active view.Navigator(UI ui, SingleComponentContainer container)Creates a navigator that is tracking the active view using URI fragments of thePagecontaining the given UI and replacing the contents of aSingleComponentContainerwith the active view.
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidaddProvider(ViewProvider provider)Registers a view provider (factory).voidaddView(String viewName, View view)Registers a static, pre-initialized view instance for a view name.voidaddView(String viewName, Class<? extends View> viewClass)Registers a view class for a view name.RegistrationaddViewChangeListener(ViewChangeListener listener)Listen to changes of the active view.protected booleanbeforeViewChange(ViewChangeListener.ViewChangeEvent event)Check whether view change is allowed by view change listeners (ViewChangeListener.beforeViewChange(ViewChangeEvent)).protected NavigationStateManagercreateNavigationStateManager(UI ui)Creates a navigation state manager for given UI.voiddestroy()Creates view change event for givenview,viewNameandparameters.protected voidfireAfterViewChange(ViewChangeListener.ViewChangeEvent event)Fires an event after the current view has changed.protected booleanfireBeforeViewChange(ViewChangeListener.ViewChangeEvent event)Fires an event before an imminent view change.StringgetCurrentNavigationState()Returns the current navigation state for which thegetCurrentView()has been constructed.ViewgetCurrentView()Return the currently active view.ViewDisplaygetDisplay()Return theViewDisplayused by the navigator.StringgetState()Returns the current navigation state reported by this Navigator'sNavigationStateManager.protected NavigationStateManagergetStateManager()Returns theNavigationStateManagerthat is used to get, listen to and manipulate the navigation state used by this Navigator.Map<String,String>getStateParameterMap()Returns the current navigation state reported by this Navigator'sNavigationStateManageras Map<String, String> where each key represents a parameter in the state.Map<String,String>getStateParameterMap(String separator)Returns the current navigation state reported by this Navigator'sNavigationStateManageras Map<String, String> where each key represents a parameter in the state.UIgetUI()protected ViewProvidergetViewProvider(String state)Get view provider that handles the givenstate.protected voidinit(UI ui, NavigationStateManager stateManager, ViewDisplay display)Initializes a navigator created with the no arguments constructor.protected voidnavigateTo(View view, String viewName, String parameters)Internal method activating a view, setting its parameters and calling listeners.voidnavigateTo(String navigationState)Navigates to a view and initialize the view with given parameters.protected Map<String,String>parseParameterStringToMap(String parameterString, String separator)Parses the given parameter string to a map using the given separator string.protected Map<String,String>parseStateParameterMap(String separator)Parses the state parameter to a map using the given separator string.protected voidperformNavigateTo(View view, String viewName, String parameters)Internal method for activating a view, setting its parameters and calling listeners.voidremoveProvider(ViewProvider provider)Unregister a view provider (factory).voidremoveView(String viewName)Removes a view from navigator.voidremoveViewChangeListener(ViewChangeListener listener)Deprecated.use aRegistrationobject returned byaddViewChangeListener(ViewChangeListener)to remove a listenerprotected voidrevertNavigation()Revert the changes to the navigation state.voidrunAfterLeaveConfirmation(ViewLeaveAction action)TriggersView.beforeLeave(ViewBeforeLeaveEvent)for the current view with the given action.voidsetErrorProvider(ViewProvider provider)Registers a view provider that is queried for a view when no other view matches the navigation state.voidsetErrorView(View view)Registers a view that is displayed when no other view matches the navigation state.voidsetErrorView(Class<? extends View> viewClass)Registers a view class that is instantiated when no other view matches the navigation state.protected voidswitchView(ViewChangeListener.ViewChangeEvent event)Update the internal state of the navigator to reflect the actual switching of views.protected voidupdateNavigationState(ViewChangeListener.ViewChangeEvent event)Update the internal state of the navigator (parameters, previous successful URL fragment navigated to) when navigation succeeds.
-
-
-
Field Detail
-
stateManager
protected NavigationStateManager stateManager
TheNavigationStateManagerthat is used to get, listen to and manipulate the navigation state used by the Navigator.
-
display
protected ViewDisplay display
TheViewDisplayused by the Navigator.
-
-
Constructor Detail
-
Navigator
public Navigator(UI ui, ComponentContainer container)
Creates a navigator that is tracking the active view using URI fragments of thePagecontaining the given UI and replacing the contents of aComponentContainerwith the active view.All components of the container are removed each time before adding the active
View. Views must implementComponentwhen using this constructor.Navigation is automatically initiated after
UI.init()if a navigator was created. If at a later point changes are made to the navigator,navigator.navigateTo(navigator.getState())may need to be explicitly called to ensure the current view matches the navigation state.- Parameters:
ui- The UI to which this Navigator is attached.container- The ComponentContainer whose contents should be replaced with the active view on view change
-
Navigator
public Navigator(UI ui, SingleComponentContainer container)
Creates a navigator that is tracking the active view using URI fragments of thePagecontaining the given UI and replacing the contents of aSingleComponentContainerwith the active view.Views must implement
Componentwhen using this constructor.Navigation is automatically initiated after
UI.init()if a navigator was created. If at a later point changes are made to the navigator,navigator.navigateTo(navigator.getState())may need to be explicitly called to ensure the current view matches the navigation state.- Parameters:
ui- The UI to which this Navigator is attached.container- The SingleComponentContainer whose contents should be replaced with the active view on view change
-
Navigator
public Navigator(UI ui, ViewDisplay display)
Creates a navigator that is tracking the active view using URI fragments of thePagecontaining the given UI.Navigation is automatically initiated after
UI.init()if a navigator was created. If at a later point changes are made to the navigator,navigator.navigateTo(navigator.getState())may need to be explicitly called to ensure the current view matches the navigation state.- Parameters:
ui- The UI to which this Navigator is attached.display- The ViewDisplay used to display the views.
-
Navigator
public Navigator(UI ui, NavigationStateManager stateManager, ViewDisplay display)
Creates a navigator.When a custom navigation state manager is not needed, use one of the other constructors which use a URI fragment based state manager.
Navigation is automatically initiated after
UI.init()if a navigator was created. If at a later point changes are made to the navigator,navigator.navigateTo(navigator.getState())may need to be explicitly called to ensure the current view matches the navigation state.- Parameters:
ui- The UI to which this Navigator is attached.stateManager- The NavigationStateManager keeping track of the active view and enabling bookmarking and direct navigation or null to use the default implementationdisplay- The ViewDisplay used to display the views handled by this navigator
-
Navigator
protected Navigator()
Creates a navigator. This method is for use by dependency injection frameworks etc. and must be followed by a call toinit(UI, NavigationStateManager, ViewDisplay)before use.- Since:
- 7.6
-
-
Method Detail
-
init
protected void init(UI ui, NavigationStateManager stateManager, ViewDisplay display)
Initializes a navigator created with the no arguments constructor.When a custom navigation state manager is not needed, use null to create a default one based on URI fragments.
Navigation is automatically initiated after
UI.init()if a navigator was created. If at a later point changes are made to the navigator,navigator.navigateTo(navigator.getState())may need to be explicitly called to ensure the current view matches the navigation state.- Parameters:
ui- The UI to which this Navigator is attached.stateManager- The NavigationStateManager keeping track of the active view and enabling bookmarking and direct navigation or null for defaultdisplay- The ViewDisplay used to display the views handled by this navigator- Since:
- 7.6
-
createNavigationStateManager
protected NavigationStateManager createNavigationStateManager(UI ui)
Creates a navigation state manager for given UI. This method should take into account any navigation related annotations.- Parameters:
ui- the ui- Returns:
- the navigation state manager
- Since:
- 8.2
-
navigateTo
public void navigateTo(String navigationState)
Navigates to a view and initialize the view with given parameters.The view string consists of a view name optionally followed by a slash and a parameters part that is passed as-is to the view. ViewProviders are used to find and create the correct type of view.
If multiple providers return a matching view, the view with the longest name is selected. This way, e.g. hierarchies of subviews can be registered like "admin/", "admin/users", "admin/settings" and the longest match is used.
If the view being deactivated indicates it wants a confirmation for the navigation operation, the user is asked for the confirmation.
Registered
ViewChangeListeners are called upon successful view change.- Parameters:
navigationState- view name and parameters- Throws:
IllegalArgumentException- ifnavigationStatedoes not map to a known view and no error view is registered
-
navigateTo
protected void navigateTo(View view, String viewName, String parameters)
Internal method activating a view, setting its parameters and calling listeners.This method also verifies that the user is allowed to perform the navigation operation.
- Parameters:
view- view to activateviewName- (optional) name of the view or null not to change the navigation stateparameters- parameters passed in the navigation state to the view
-
runAfterLeaveConfirmation
public void runAfterLeaveConfirmation(ViewLeaveAction action)
TriggersView.beforeLeave(ViewBeforeLeaveEvent)for the current view with the given action.This method is typically called by
navigateTo(View, String, String)but can be called from application code when you want to e.g. show a confirmation dialog before perfoming an action which is not a navigation but which would cause the view to be hidden, e.g. logging out.Note that this method will not trigger any
ViewChangeListeners as it does not navigate to a new view. UsenavigateTo(String)to change views and trigger all listeners.- Parameters:
action- the action to execute when the view confirms it is ok to leave- Since:
- 8.1
-
performNavigateTo
protected void performNavigateTo(View view, String viewName, String parameters)
Internal method for activating a view, setting its parameters and calling listeners.Invoked after the current view has confirmed that leaving is ok.
This method also verifies that the user is allowed to perform the navigation operation.
- Parameters:
view- view to activateviewName- (optional) name of the view or null not to change the navigation stateparameters- parameters passed in the navigation state to the view- Since:
- 8.1
-
beforeViewChange
protected boolean beforeViewChange(ViewChangeListener.ViewChangeEvent event)
Check whether view change is allowed by view change listeners (ViewChangeListener.beforeViewChange(ViewChangeEvent)). This method can be overridden to extend the behavior, and should not be called directly except bynavigateTo(View, String, String).- Parameters:
event- the event to fire as the before view change event- Returns:
- true if view change is allowed
- Since:
- 7.6
-
revertNavigation
protected void revertNavigation()
Revert the changes to the navigation state. When navigation fails, this method can be called bynavigateTo(View, String, String)to revert the URL fragment to point to the previous view to which navigation succeeded. This method should only be called bynavigateTo(View, String, String). Normally it should not be overridden, but can be by frameworks that need to hook into view change cancellations of this type.- Since:
- 7.6
-
updateNavigationState
protected void updateNavigationState(ViewChangeListener.ViewChangeEvent event)
Update the internal state of the navigator (parameters, previous successful URL fragment navigated to) when navigation succeeds. Normally this method should not be overridden nor called directly from application code, but it can be called by a custom implementation ofnavigateTo(View, String, String).- Parameters:
event- a view change event with details of the change- Since:
- 7.6
-
switchView
protected void switchView(ViewChangeListener.ViewChangeEvent event)
Update the internal state of the navigator to reflect the actual switching of views. This method should only be called bynavigateTo(View, String, String)between showing the view and callingView.enter(ViewChangeEvent). If this method is overridden, the overriding version must call the super method.- Parameters:
event- a view change event with details of the change- Since:
- 7.6
-
fireBeforeViewChange
protected boolean fireBeforeViewChange(ViewChangeListener.ViewChangeEvent event)
Fires an event before an imminent view change.Listeners are called in registration order. If any listener returns
false, the rest of the listeners are not called and the view change is blocked.The view change listeners may also e.g. open a warning or question dialog and save the parameters to re-initiate the navigation operation upon user action.
- Parameters:
event- view change event (not null, view change not yet performed)- Returns:
- true if the view change should be allowed, false to silently block the navigation operation
-
getStateManager
protected NavigationStateManager getStateManager()
Returns theNavigationStateManagerthat is used to get, listen to and manipulate the navigation state used by this Navigator.- Returns:
- NavigationStateManager in use
-
getState
public String getState()
Returns the current navigation state reported by this Navigator'sNavigationStateManager.When the navigation is triggered by the browser (for example by pressing the back or forward button in the browser), the navigation state may already have been updated to reflect the new address, before the
navigateTo(String)is notified.- Returns:
- The navigation state.
-
getStateParameterMap
public Map<String,String> getStateParameterMap()
Returns the current navigation state reported by this Navigator'sNavigationStateManageras Map<String, String> where each key represents a parameter in the state. Uses & as parameter separator. If the state contains #!view/foo&bar=baz then this method will return a map containing foo => "" and bar => baz.- Returns:
- The parameters from the navigation state as a map
- Since:
- 8.1
- See Also:
getStateParameterMap(String)
-
getStateParameterMap
public Map<String,String> getStateParameterMap(String separator)
Returns the current navigation state reported by this Navigator'sNavigationStateManageras Map<String, String> where each key represents a parameter in the state. The state parameter separator character needs to be specified with the separator.- Parameters:
separator- the string (typically one character) used to separate values from each other- Returns:
- The parameters from the navigation state as a map
- Since:
- 8.1
- See Also:
getStateParameterMap()
-
parseStateParameterMap
protected Map<String,String> parseStateParameterMap(String separator)
Parses the state parameter to a map using the given separator string.- Parameters:
separator- the string (typically one character) used to separate values from each other- Returns:
- The navigation state as Map<String, String>.
- Since:
- 8.1
-
parseParameterStringToMap
protected Map<String,String> parseParameterStringToMap(String parameterString, String separator)
Parses the given parameter string to a map using the given separator string.- Parameters:
parameterString- the parameter string to parseseparator- the string (typically one character) used to separate values from each other- Returns:
- The navigation state as Map<String, String>.
- Since:
- 8.1
-
getDisplay
public ViewDisplay getDisplay()
Return theViewDisplayused by the navigator.- Returns:
- the ViewDisplay used for displaying views
-
getUI
public UI getUI()
-
getCurrentView
public View getCurrentView()
Return the currently active view.- Returns:
- current view
- Since:
- 7.6
-
fireAfterViewChange
protected void fireAfterViewChange(ViewChangeListener.ViewChangeEvent event)
Fires an event after the current view has changed.Listeners are called in registration order.
- Parameters:
event- view change event (not null)
-
addView
public void addView(String viewName, View view)
Registers a static, pre-initialized view instance for a view name.Registering another view with a name that is already registered overwrites the old registration of the same type.
Note that a view should not be shared between UIs (for instance, it should not be a static field in a UI subclass).
- Parameters:
viewName- String that identifies a view (not null nor empty string)view-Viewinstance (not null)
-
addView
public void addView(String viewName, Class<? extends View> viewClass)
Registers a view class for a view name.Registering another view with a name that is already registered overwrites the old registration of the same type.
A new view instance is created every time a view is requested.
- Parameters:
viewName- String that identifies a view (not null nor empty string)viewClass-Viewclass to instantiate when a view is requested (not null)
-
removeView
public void removeView(String viewName)
Removes a view from navigator.This method only applies to views registered using
addView(String, View)oraddView(String, Class).- Parameters:
viewName- name of the view to remove
-
addProvider
public void addProvider(ViewProvider provider)
Registers a view provider (factory).Providers are called in order of registration until one that can handle the requested view name is found.
- Parameters:
provider- provider to register, notnull- Throws:
IllegalArgumentException- if the provided view provider isnull
-
removeProvider
public void removeProvider(ViewProvider provider)
Unregister a view provider (factory).- Parameters:
provider- provider to unregister
-
setErrorView
public void setErrorView(Class<? extends View> viewClass)
Registers a view class that is instantiated when no other view matches the navigation state. This implicitly sets an appropriate error view provider and overrides any previoussetErrorProvider(ViewProvider)call.Note that an error view should not be shared between UIs (for instance, it should not be a static field in a UI subclass).
- Parameters:
viewClass- The View class whose instance should be used as the error view.
-
setErrorView
public void setErrorView(View view)
Registers a view that is displayed when no other view matches the navigation state. This implicitly sets an appropriate error view provider and overrides any previoussetErrorProvider(ViewProvider)call.- Parameters:
view- The View that should be used as the error view.
-
setErrorProvider
public void setErrorProvider(ViewProvider provider)
Registers a view provider that is queried for a view when no other view matches the navigation state. An error view provider should match any navigation state, but could return different views for different states. ItsgetViewName(String navigationState)should returnnavigationState.- Parameters:
provider-
-
addViewChangeListener
public Registration addViewChangeListener(ViewChangeListener listener)
Listen to changes of the active view.Registered listeners are invoked in registration order before (
beforeViewChange()) and after (afterViewChange()) a view change occurs.- Parameters:
listener- Listener to invoke during a view change.- Since:
- 8.0
-
removeViewChangeListener
@Deprecated public void removeViewChangeListener(ViewChangeListener listener)
Deprecated.use aRegistrationobject returned byaddViewChangeListener(ViewChangeListener)to remove a listenerRemoves a view change listener.- Parameters:
listener- Listener to remove.
-
getViewProvider
protected ViewProvider getViewProvider(String state)
Get view provider that handles the givenstate.- Parameters:
state- state string- Returns:
- suitable provider
-
destroy
public void destroy()
Creates view change event for givenview,viewNameandparameters.- Since:
- 7.6.7
-
getCurrentNavigationState
public String getCurrentNavigationState()
Returns the current navigation state for which thegetCurrentView()has been constructed. This may differ togetState()in case the URL has been changed on the browser and the navigator wasn't yet given an opportunity to construct new view. The state is in the form ofcurrent-view-name/optional/parameters- Returns:
- the current navigation state, may be
null.
-
-