GWT - Lezione di storia

Le applicazioni GWT sono normalmente applicazioni a pagina singola che eseguono JavaScript e non contengono molte pagine, quindi il browser non tiene traccia dell'interazione dell'utente con l'applicazione. Per utilizzare la funzionalità di cronologia del browser, l'applicazione deve generare un frammento di URL univoco per ogni pagina navigabile.

GWT fornisce History Mechanism per gestire questa situazione.

GWT utilizza un termine tokenche è semplicemente una stringa che l'applicazione può analizzare per tornare a uno stato particolare. L'applicazione salverà questo token nella cronologia del browser come frammento di URL.

Ad esempio, un token di cronologia denominato "pageIndex1" verrebbe aggiunto a un URL come segue:

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

Flusso di lavoro per la gestione della cronologia

Passaggio 1: abilitare il supporto della cronologia

Per poter utilizzare il supporto della cronologia GWT, dobbiamo prima incorporare il seguente iframe nella nostra pagina HTML host.

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

Passaggio 2: aggiungi token alla cronologia

Di seguito le statistiche di esempio su come aggiungere token alla cronologia del browser

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

Passaggio 3: recuperare il token dalla cronologia

Quando l'utente utilizza il pulsante Indietro / Avanti del browser, recupereremo il token e aggiorneremo di conseguenza lo stato dell'applicazione.

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);
      }
   }
});

Vediamo ora la classe di storia in azione.

Classe di storia - Esempio completo

Questo esempio ti guiderà attraverso semplici passaggi per dimostrare la gestione della cronologia di un'applicazione GWT. Segui i passaggi seguenti per aggiornare l'applicazione GWT che abbiamo creato in GWT - Capitolo Crea applicazione -

Passo Descrizione
1 Crea un progetto con un nome HelloWorld sotto un pacchetto com.tutorialspoint come spiegato nel capitolo GWT - Crea applicazione .
2 Modifica HelloWorld.gwt.xml , HelloWorld.css , HelloWorld.html e HelloWorld.java come spiegato di seguito. Mantieni il resto dei file invariato.
3 Compilare ed eseguire l'applicazione per verificare il risultato della logica implementata.

Di seguito è riportato il contenuto del descrittore del modulo modificato 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>

Di seguito è riportato il contenuto del file del foglio di stile modificato 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;
}

Di seguito è riportato il contenuto del file host HTML modificato 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>

Cerchiamo di avere il seguente contenuto del file Java src/com.tutorialspoint/HelloWorld.java utilizzando il quale dimostreremo la gestione della cronologia nel codice 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);
   }
}

Una volta che sei pronto con tutte le modifiche apportate, compiliamo ed eseguiamo l'applicazione in modalità sviluppo come abbiamo fatto nel capitolo GWT - Crea applicazione . Se tutto va bene con la tua applicazione, questo produrrà il seguente risultato:

  • Ora fai clic su ciascuna scheda per selezionare pagine diverse.

  • Dovresti notare, quando ogni scheda è selezionata, l'URL dell'applicazione viene modificato e #pageIndex viene aggiunto all'URL.

  • Puoi anche vedere che i pulsanti Avanti e Indietro del browser sono ora abilitati.

  • Usa il pulsante Avanti e Indietro del browser e vedrai le diverse schede selezionate di conseguenza.