GWT - Cours d'histoire

Les applications GWT sont normalement des applications à page unique exécutant des scripts Java et ne contiennent pas beaucoup de pages, donc le navigateur ne garde pas trace de l'interaction de l'utilisateur avec l'application. Pour utiliser la fonctionnalité d'historique du navigateur, l'application doit générer un fragment d'URL unique pour chaque page navigable.

GWT fournit History Mechanism pour gérer cette situation.

GWT utilise un terme tokenqui est simplement une chaîne que l'application peut analyser pour revenir à un état particulier. L'application enregistrera ce jeton dans l'historique du navigateur en tant que fragment d'URL.

Par exemple, un jeton d'historique nommé "pageIndex1" serait ajouté à une URL comme suit -

http://www.tutorialspoint.com/HelloWorld.html#pageIndex0

Flux de travail de gestion de l'historique

Étape 1 - Activer la prise en charge de l'historique

Afin d'utiliser la prise en charge de l'historique GWT, nous devons d'abord intégrer l'iframe suivant dans notre page HTML hôte.

<iframe src = "javascript:''"
   id = "__gwt_historyFrame"
   style = "width:0;height:0;border:0"></iframe>

Étape 2 - Ajouter un jeton à l'historique

Exemple suivant de statistiques comment ajouter un jeton à l'historique du navigateur

int index = 0;
History.newItem("pageIndex" + index);

Étape 3 - Récupérer le jeton de l'historique

Lorsque l'utilisateur utilise le bouton Précédent / Suivant du navigateur, nous récupérons le jeton et mettons à jour l'état de notre application en conséquence.

History.addValueChangeHandler(new ValueChangeHandler<String>() {
   @Override
   public void onValueChange(ValueChangeEvent<String> event) {
      String historyToken = event.getValue();
      /* parse the history token */
      try {
         if (historyToken.substring(0, 9).equals("pageIndex")) {
            String tabIndexToken = historyToken.substring(9, 10);
            int tabIndex = Integer.parseInt(tabIndexToken);
            /* select the specified tab panel */
            tabPanel.selectTab(tabIndex);
         } else {
            tabPanel.selectTab(0);
         }
      } catch (IndexOutOfBoundsException e) {
         tabPanel.selectTab(0);
      }
   }
});

Voyons maintenant la classe History en action.

Classe d'histoire - Exemple complet

Cet exemple vous guidera à travers des étapes simples pour démontrer la gestion de l'historique d'une application GWT. Suivez les étapes suivantes pour mettre à jour l'application GWT que nous avons créée dans GWT - Chapitre Créer une application -

Étape La description
1 Créez un projet avec un nom HelloWorld sous un package com.tutorialspoint comme expliqué dans le chapitre GWT - Créer une application .
2 Modifiez HelloWorld.gwt.xml , HelloWorld.css , HelloWorld.html et HelloWorld.java comme expliqué ci-dessous. Gardez le reste des fichiers inchangé.
3 Compilez et exécutez l'application pour vérifier le résultat de la logique implémentée.

Voici le contenu du descripteur de module modifié src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>  
   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

Voici le contenu du fichier de feuille de style modifié war/HelloWorld.css.

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

Voici le contenu du fichier hôte HTML modifié war/HelloWorld.html

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>
   
   <body>
      <iframe src = "javascript:''"id = "__gwt_historyFrame"
         style = "width:0;height:0;border:0"></iframe>
      <h1> History Class Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

Laissez-nous avoir le contenu suivant du fichier Java src/com.tutorialspoint/HelloWorld.java à l'aide de laquelle nous démontrerons la gestion de l'historique dans le code GWT.

package com.tutorialspoint.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabPanel;

public class HelloWorld implements EntryPoint {

   /**
    * This is the entry point method.
    */
   public void onModuleLoad() {
      /* create a tab panel to carry multiple pages */  
      final TabPanel tabPanel = new TabPanel();

      /* create pages */
      HTML firstPage = new HTML("<h1>We are on first Page.</h1>");
      HTML secondPage = new HTML("<h1>We are on second Page.</h1>");
      HTML thirdPage = new HTML("<h1>We are on third Page.</h1>");

      String firstPageTitle = "First Page";
      String secondPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";
      tabPanel.setWidth("400");
      
	  /* add pages to tabPanel*/
      tabPanel.add(firstPage, firstPageTitle);
      tabPanel.add(secondPage,secondPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

      /* add tab selection handler */
      tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
         @Override
         public void onSelection(SelectionEvent<Integer> event) {
            /* add a token to history containing pageIndex 
             History class will change the URL of application
             by appending the token to it.
            */
            History.newItem("pageIndex" + event.getSelectedItem());
         }
      });
      
      /* add value change handler to History 
       this method will be called, when browser's 
       Back button or Forward button are clicked 
       and URL of application changes.
       */
      History.addValueChangeHandler(new ValueChangeHandler<String>() {
         @Override
         public void onValueChange(ValueChangeEvent<String> event) {
            String historyToken = event.getValue();
            /* parse the history token */
            try {
               if (historyToken.substring(0, 9).equals("pageIndex")) {
                  String tabIndexToken = historyToken.substring(9, 10);
                  int tabIndex = Integer.parseInt(tabIndexToken);
                  /* select the specified tab panel */
                  tabPanel.selectTab(tabIndex);
               } else {
                  tabPanel.selectTab(0);
               }
            } catch (IndexOutOfBoundsException e) {
               tabPanel.selectTab(0);
            }
         }
      });

      /* select the first tab by default */
      tabPanel.selectTab(0);

      /* add controls to RootPanel */
      RootPanel.get().add(tabPanel);
   }
}

Une fois que vous êtes prêt avec tous les changements effectués, laissez-nous compiler et exécuter l'application en mode développement comme nous l'avons fait dans le chapitre GWT - Créer une application . Si tout va bien avec votre application, cela produira le résultat suivant -

  • Cliquez maintenant sur chaque onglet pour sélectionner différentes pages.

  • Vous devriez remarquer que lorsque chaque onglet est sélectionné, l'URL de l'application est modifiée et #pageIndex est ajouté à l'url.

  • Vous pouvez également voir que les boutons Précédent et Suivant du navigateur sont désormais activés.

  • Utilisez le bouton Précédent et Suivant du navigateur et vous verrez les différents onglets être sélectionnés en conséquence.