Raible's Wiki

Raible Designs
Wiki Home
News
Recent Changes

AppFuse

Homepage
  - Korean
  - Chinese
  - Italian
  - Japanese

QuickStart Guide
  - Chinese
  - French
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish
  - Japanese

User Guide
  - Korean
  - Chinese

Tutorials
  - Chinese
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish

FAQ
  - Korean

Latest Downloads

Other Applications

Struts Resume
Security Example
Struts Menu

Set your name in
UserPreferences


Referenced by
SpringControllers_it




JSPWiki v2.2.33

[RSS]


Hide Menu

ValidationAndListSpring_it


Difference between version 7 and version 1:

At line 5 changed 2 lines.
!!About this Tutorial
This tutorial will show you how to add Validation logic (client and server-side) to the Person object using Commons Validator. We'll also create a list screen using the [Display Tag Library|http://displaytag.sf.net] to display all the people in the database.
!!Info su questo Tutorial
Questo tutorial mostra come aggiungere la logica di validazione (sia client che server-side) all'oggetto Person usando Commons Validator. Verrà creata anche una schermata di elenco usando la [Display Tag Library|http://displaytag.sf.net] per visualizzare tutte le persone nel database.
At line 8 changed 1 line.
;:%%(color: blue)''I will tell you how I do stuff in the __Real World__ in text like this.''%%
;:%%(color: blue)''Ti dirò come faccio le cose nel __Mondo Reale__ in un testo come questo.''%%
At line 10 changed 9 lines.
!Table of Contents
* [1] Add XDoclet Validator tags to Person.java
* [2] View JSP with validation added and test
* [3] Add ''testGetPeople'' methods to DAO and Manager Tests
* [4] Add ''getPeople'' methods to PersonDao and Manager
* [5] Create PersonControllerTest
* [6] Create PersonController
* [7] Create personList.jsp and Canoo test
* [8] Add link to menu
!Indice
* [1] Aggiungi i tag XDoclet per il Validator a Person.java
* [2] Vedi JSP con la validazione aggiunta e verifica
* [3] Aggiungi i metodi ''testGetPeople'' ai test di DAO e Manager
* [4] Aggiungi i metodi ''getPeople'' a PersonDao e Manager
* [5] Crea il PersonControllerTest
* [6] Crea il PersonController
* [7] Crea personList.jsp ed il test Canoo
* [8] Aggiungi un collegamento al menu
At line 20 changed 2 lines.
!!Add XDoclet Validator to Person.java [#1]
To use Commons Validator with Spring MVC, normally you have to write a validation.xml file by hand. However, thanks to XDoclet, it's much easier - you just need to add a couple of ''@spring.validator'' tags to our POJO (Person.java). Let's open it up (src/dao/**/dao/Person.java) and modify your setFirstName and setLastName methods to resemble the following:
!!Aggiungi i tag XDoclet per il Validator a Person.java [#1]
Per usare Commons Validator con Spring MVC normalmente devi scrivere un file validation.xml a mano. Tuttavia, grazie a XDoclet, è molto più semplice - devi solo aggiungere un paio di tag ''@spring.validator'' al tuo POJO (Person.java). Apriamo il file (src/dao/**/dao/Person.java) e modifichiamo i metodi setFirstName e setLastName come segue:
At line 40 changed 1 line.
I should mention that you can also add a ''msgkey'' attribute to this tag to override the default message key for this error.
Va inoltre menzionato che puoi anche aggiungere un attributo ''msgkey'' a questo tag per effettuare l'override della chiave messaggio predefinita per questo errore.
At line 47 changed 1 line.
The default key for type="required" is already ''errors.required'', so I usually leave it to the default. This key is defined in web/WEB-INF/classes/ApplicationResources_*.properties.
La chiave predefinita per type="required" è già ''errors.required'', per cui io di solito la lascio al default. Questa chiave è definita in web/WEB-INF/classes/ApplicationResources_*.properties.
At line 49 changed 1 line.
Now if you save Person.java and run __ant clean webdoclet__, a validation.xml file will be generated in build/appfuse/WEB-INF/. It's contents should have now have an entry for "person".
Ora se registri Person.java ed esegui __ant clean webdoclet__, verrà generato un file validation.xml in build/appfuse/WEB-INF/. Il contenuto dovrebbe avere un elemento per "person".
At line 67 changed 1 line.
To enable validation in personForm.jsp, you'll need to make sure your personForm.jsp has the following at the bottom:
Infine, per attivare la validazione in personForm.jsp, devi assicurarti che personForm.jsp contenga quanto segue:
At line 69 changed 1 line.
{{{<html:javascript formName="person" cdata="false"
{{{<v:javascript formName="person" cdata="false"
At line 74 changed 1 line.
You'd also need to uncomment the "validator" property we commented out earlier. Make sure the "personFormController" &lt;bean&gt; in web/WEB-INF/action-servlet.xml has the following XML:
Devi anche decommentare la property "validator" che abbiamo commentato prima. Controlla che il &lt;bean&gt; "personFormController" in web/WEB-INF/action-servlet.xml abbia il seguente XML:
At line 88 changed 1 line.
!!View JSP with validation added and test [#2]
!!Vedi JSP con la validazione aggiunta e verifica [#2]
At line 90 changed 1 line.
Now that we have Validation configured for this form, let's make sure it works. Run __ant db-load deploy__, start Tomcat and go to [http://localhost:8080/appfuse/editPerson.html?id=1]. One thing you might notice is that the "First Name" and "Last Name" labels now have asterisks next to them - indicating required fields. This is achieved with a LabelTag that looks up the validation rules from Commons Validator.
Ora che abbiamo la validazione configurata su questo form, assicuriamoci che funzioni. Esegui __ant db-load deploy__, avvia Tomcat e vai su [http://localhost:8080/appfuse/editPerson.html?id=1]. Un'altra cosa che potresti notare è che le label "First Name" e "Last Name" ora hanno degli asterischi vicino - che indicano i campi come obbligatori. Ciò è ottenuto tramite un LabelTag che legge le regole di validazione da Commons Validator.
At line 92 changed 1 line.
If you erase the values in the firstName and lastName fields and click the save button, you should get the following JavaScript alert.
Se cancelli i valori nei campi firstName e lastName e fai clic sul bottone registra, dovresti avere il seguente JavaScript.
At line 98 changed 1 line.
To make sure things are ''really'' working as expected, you can turn off JavaScript and ensure the server-side validation is working. This is easy in [Mozilla Firebird|http://www.mozilla.org/products/firebird/] (my favorite browser), just go to Tools &rarr; Options &rarr; Web Features and uncheck "Enable JavaScript". Now if you clear the fields and save the form, you should see the following:
Per esser sicuro che tutto funzioni ''davvero'' come atteso, puoi provare a spegnere il JavaScript e controllare che la validazione server-side stia funzionando. Ciò è semplice in [Mozilla Firefox|http://www.mozilla.org/products/firefox/] (il mio browser preferito), basta che vai in Strumenti &rarr; Opzioni &rarr; Contenuti e deselezioni "Attiva JavaScript". Ora se azzeri i campi e invii il form, dovresti vedere quanto segue:
At line 105 changed 1 line.
If you only want server-side validation (no JavaScript), you can remove the ''onsubmit'' attribute of &lt;html:form&gt; (in web/pages/personForm.jsp) as well as the Validator JavaScript tags at the bottom of the page.
Se vuoi solo la validazione lato server (senza JavaScript), puoi eliminare l'attributo ''onsubmit'' da &lt;html:form&gt; (in web/pages/personForm.jsp) ed anche i tag del Validator JavaScript a fine pagina.
At line 109 changed 1 line.
<html:javascript formName="personForm" cdata="false"
<v:javascript formName="personForm" cdata="false"
At line 115 changed 2 lines.
!!Add testGetPeople methods to DAO and Manager Tests [#3]
To create a List screen (also called a master screen), we need to create methods that will return all the rows from our ''person'' table. Let's start by adding tests for these methods to our PersonDaoTest and PersonManagerTest classes. I usually name this method ''getEntities'' (i.e. getUsers), but you could also use ''getAll'' or ''search'' - it's really just a matter of personal preference.
!!Aggiungi i metodi testGetPeople ai Test di DAO e Manager [#3]
Per creare una schermata elenco (chiamata anche schermata master), dobbiamo creare i metodi che restituiranno tutte le righe dalla nostra tabella ''person''. Iniziamo aggiungendo i test oer questi metodi alle nostre classi PersonDaoTest e PersonManagerTest. Di solito io chiamo questi metodi ''getEntities'' (i.e. getUsers), ma potresti usare anche ''getAll'' o ''search'' - si tratta davvero solo di una questione di preferenze personali.
At line 118 changed 1 line.
Open test/dao/**/dao/PersonDaoTest.java and add a ''testGetPeople'' method:
Apri test/dao/**/dao/PersonDaoTest.java ed aggiungi un metodo ''testGetPeople'':
At line 129 changed 1 line.
The reason I'm passing in a person object to the ''getPeople'' method is to allow for filtering (based on values in person) in the future. Adding this parameter in your getPeople() method signature is optional, but the rest of this tutorial assumes you have done this.
Il motivo per cui sto passando un oggetto person al metodo ''getPeople'' è per permettere di filtrare (basandomi sui valori in person) in futuro. Aggiungendo questo parametro alla firma del tuo metodo getPeople() è opzionale, ma il resto di questo tutorial assume che tu lo abbia fatto.
At line 131 changed 1 line.
Now open test/service/**/service/PersonManagerTest.java and add a ''testGetPeople'' method:
Ora apri test/service/**/service/PersonManagerTest.java ed aggiungi un metodo ''testGetPeople'':
At line 140 changed 1 line.
// set expected behavior on dao
// imposta il comportamento atteso sul dao
At line 150 changed 1 line.
In order for these tests to compile, you need to add the ''getPeople()'' method to the PersonDao and PersonManager interfaces, and their implementations.
Affinché questi test possano compilare, devi aggiungere il metodo ''getPeople()'' alle interfacce PersonDao e PersonManager, e la relativa implementazione.
At line 152 changed 2 lines.
!!Add getPeople() method to DAO and Manager [#4]
Open src/dao/**/dao/PersonDao.java and add the getPeople() method signature:
!!Aggiungi il metodo getPeople() a DAO e Manager [#4]
Apri src/dao/**/dao/PersonDao.java ed aggiungi la firma del metodo getPeople():
At line 160 changed 1 line.
Now add the same method signature to src/service/**/service/__PersonManager.java__. Save all your files and adjust the imports in your tests. Next you need to implement the getPeople() method in your implementation classes. Open src/dao/**/dao/hibernate/PersonDaoHibernate.java and add the following method:
Ora aggiungi la stessa firma al metodo src/service/**/service/__PersonManager.java__. Registra tutti i tuoi file ed aggiusta gli import nei tuoi test. Dopo devi implementare il metodo getPeople() nelle tue classi di implementazione. Apri src/dao/**/dao/hibernate/PersonDaoHibernate.java ed aggiungi il seguente metodo:
At line 170 changed 1 line.
You'll notice here that nothing is being done with the ''person'' parameter. This is just a placeholder for now - in the future you may want to filter on it's properties using [Hibernate's Query Language|http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html] (HQL) or using [Criteria Queries|http://www.hibernate.org/hib_docs/reference/en/html/querycriteria.html].
Noterai qui che non si fa nulla con il parametro ''person''. Per ora si tratta solo di un segnaposto - in futuro puoi voler filtrare sulle sue proprietà usando l'[Hibernate Query Language|http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html] (HQL) o le [Criteria Queries|http://www.hibernate.org/hib_docs/reference/en/html/querycriteria.html].
At line 172 changed 1 line.
''An example using a Criteria Query:''
''Un esempio con uso di Criteria Query:''
At line 177 changed 2 lines.
.excludeZeroes() // exclude zero valued properties
.ignoreCase(); // perform case insensitive string comparisons
.excludeZeroes() // escludi proprietà con valore zero
.ignoreCase(); // esegui confronti fra stringhe case insensitive
At line 191 changed 1 line.
Now implement the ''getPeople()'' method in src/service/**/impl/PersonManagerImpl.java:
Ora implementa il metodo ''getPeople()'' in src/service/**/impl/PersonManagerImpl.java:
At line 200 changed 1 line.
After saving all your changes, you should be able to run both tests by executing the following:
Dopo aver registrato tutte le tue modifiche, dovresti poter lanciare entrambi i test eseguendo quanto segue:
At line 205 changed 1 line.
If everything works - ''nice job!'' Now you need to add this ''retrieve all'' functionality to the web tier.
Se funziona tutto - ''ben fatto!'' Ora devi aggiungere questa funzione ''recupera tutto'' allo strato web.
At line 207 changed 2 lines.
!!Create PersonControllerTest [#5]
In the last couple of tutorials, we've been working with the PersonFormController to interact with our HTML form. Now we need to create a new Controller that'll simply handle getting and displaying a list of people in the database.
!!Crea il PersonControllerTest [#5]
Nell'ultimo paio di tutorial, abbiamo lavorato con il PersonFormController per interagire con la nostra form HTML. Ora dobbiamo creare un nuovo Controller che gestirà semplicemente il recupero e la visualizzazione di un elenco di persone da database.
At line 210 changed 1 line.
;:''You could also use a [MultiActionController|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/multiaction/MultiActionController.html] to handle all your List screens.''
;:''Potresti usare anche un [MultiActionController|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/multiaction/MultiActionController.html] per gestire tutte le tue schermate elenco.''
At line 212 changed 1 line.
To begin, create test/web/**/action/PersonControllerTest.java (extends BaseControllerTestCase) and add the following method:
Per iniziare, crea test/web/**/action/PersonControllerTest.java (extends BaseControllerTestCase) ed aggiungi il seguente metodo:
At line 239 changed 1 line.
This class will not compile until you (1) create the PersonController class and (2) add the PERSON_LIST variable to the src/dao/**/Constants.java file. Some folks have suggested that this class be named ''PersonControllerList'' - the name choice is up to you. I prefer Controller and FormController because it tells me one implements [Controller|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/Controller.html] while the latter extends [SimpleFormController|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/SimpleFormController.html].
Questa classe non compilerà finché non (1) crei la classe PersonController ed (2) aggiungi la variabile PERSON_LIST al file src/dao/**/Constants.java. Alcuni hanno suggerito di chiamare questa classe ''PersonControllerList'' - a te la scelta del nome. Io preferisco Controller e FormController perché mi dice che una classe implementa [Controller|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/Controller.html] mentra la seconda [SimpleFormController|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/SimpleFormController.html].
At line 241 changed 1 line.
;:%%(color: blue)''I usually copy a similar variable that already exists in this file - i.e. USER_LIST.''
;:%%(color: blue)''Di solito copio una variabile simile già esistente in questo file - i.e. USER_LIST.''
At line 246 changed 1 line.
* The request scope attribute that holds the person list
* L'attributo in request scope che contiene l'elenco delle persone
At line 251 changed 1 line.
Now save all your changes. You won't be able to run __ant test-web -Dtestcase=PersonController__ yet since ''PersonController'' does not exist (yet). Let's add it.
Ora registra tutte le tue modifiche. Non sarai ancora in grado di lanciare __ant test-web -Dtestcase=PersonController__ in quanto ''PersonController'' non esiste (per ora). Aggiungiamolo.
At line 253 changed 2 lines.
!!Create PersonController [#6]
Create src/web/**/action/PersonController.java. It should implement {{org.springframework.web.servlet.mvc.Controller}} and read as follows:
!!Crea il PersonController [#6]
Crea il file src/web/**/action/PersonController.java. Dovrebbe implementare {{org.springframework.web.servlet.mvc.Controller}} e leggersi come segue:
At line 295 changed 1 line.
Now add a definition to web/WEB-INF/action-servlet.xml for this Controller.
Ora aggiungi una definizione a web/WEB-INF/action-servlet.xml per questo Controller.
At line 304 changed 1 line.
Now if you run __ant test-web -Dtestcase=PersonController__, the test should pass. Next, create a URL mapping for this controller. To do this, search for the "urlMapping" bean in web/WEB-INF/action-servlet.xml and add the following line to the "mappings" property:
Ora se esegui __ant test-web -Dtestcase=PersonController__, il test dovrebbe passare. Successivamente, crea il mapping come URL per questo controller. Per far ciò, cerca il bean "urlMapping" in web/WEB-INF/action-servlet.xml ed aggiungi la riga seguente alla proprietà "mappings":
At line 311 changed 2 lines.
!!Create personList.jsp and Canoo test [#7]
Open the personList.jsp file in the ''web/pages'' folder of your project. One thing you'll probably want to change is the plural form of the items you're listing. The generated name in this example is "persons" and it should probably be people. At or near line 31, you should have the following line:
!!Crea personList.jsp ed il test Canoo [#7]
Apri il file personList.jsp nella cartella ''web/pages'' del tuo progetto. Una cosa che vorrai probabilmente modificare è la forma plurale degli elementi che stai elencando. Il nome generato in questo esempio è "persons" e probabilmente dovrebbe essere people. Alla riga 31 o lì vicino, dovresti avere quanto segue:
At line 316 changed 1 line.
Change it to:
Modificalo in:
At line 320 changed 1 line.
Finally, add the title and heading keys (personList.title and personList.heading) to web/WEB-INF/classes/ApplicationResources.properties. Open this file and add the following:
Infine, aggiungi le chiavi per titolo ed intestazione (personList.title e personList.heading) a web/WEB-INF/classes/ApplicationResources.properties. Apri questo file ed aggiungi quanto segue:
At line 328 changed 2 lines.
As a reminder, the {{personList.title}} is what ends up in the brower's title bar (the &lt;title&gt; tag) and
{{personList.heading}} will be put into an &lth1&gt; tag before any page content. At this point, you could be able to run "ant deploy", start Tomcat and [open the list screen in your browser|http://localhost:8080/appfuse/people.html].
Come reminder, {{personList.title}} contiene ciò che finisce nella barra del titolo del browser (il tag &lt;title&gt;) e
{{personList.heading}} verrà messo in un tag &lth1&gt; prima di qualsiasi contenuto della pagina. A questo punto, potresti riuscire ad eseguire "ant deploy", avviare Tomcat ed [aprire la schermata elenco nel tuo browser|http://localhost:8080/appfuse/people.html].
At line 331 changed 1 line.
Now that we have a List Screen, let's change the pages that are displayed after adding and deleting a new Person. In web/WEB-INF/action-servlet.xml, change the personFormController's successView property to be "people.html".
Ora che abbiamo una schermata elenco, modifichiamo le pagina visualizzate dopo l'aggiunta e l'eliminazione di una Person. In web/WEB-INF/action-servlet.xml, modifica la property successView di personFormController in modo che valga "people.html".
At line 338 changed 1 line.
You will also need to update the Canoo tests "AddPerson" and "DeletePerson". Open test/web/web-tests.xml and change the following line in the "AddPerson" target:
Devi anche aggiornare i test Canoo "AddPerson" e "DeletePerson". Apri test/web/web-tests.xml e modifica la riga seguente nel target "AddPerson":
At line 343 changed 1 line.
to:
in:
At line 348 changed 1 line.
Then in the "DeletePerson" target, change the following line:
Poi nel target "DeletePerson", modifica la riga seguente:
At line 353 changed 1 line.
to:
in:
At line 357 changed 1 line.
To test that displaying this page works, you can create a new JSP test in test/web/web-tests.xml:
Per verificare che la visualizzazione della pagina funzioni, puoi creare una nuovo test JSP in test/web/web-tests.xml:
At line 377 changed 1 line.
You'll also want to add the "SearchPeople" target to the "PersonTests" target so it will be executed along with all the other person-related tests.
Vorrai anche aggiungere il target "SearchPeople" al target "PersonTests" in modo che venga eseguito insieme a tutti gli altri test relativi alle persone.
At line 382 changed 1 line.
<!-- runs person-related tests -->
<!-- esegui i test relativi alle persone -->
At line 390 changed 1 line.
Now you can run __ant deploy test-canoo -Dtestcase=SearchPeople__ (or ''ant test-jsp'' if Tomcat isn't running) and hopefully it will result in "BUILD SUCCESSFUL". If so - ''nice work!''
Ora puoi eseguire __ant deploy test-canoo -Dtestcase=SearchPeople__ (o ''ant test-jsp'' se Tomcat non è avviato) e se va bene tutto il risultato sarà "BUILD SUCCESSFUL". Se è cosi - ''ottimo lavoro!''
At line 392 changed 2 lines.
!!Add link to menu [#8]
The last step is to make the list, add, edit and delete functions visible to the user. The simplest way is to add a new link to the list of links in web/pages/mainMenu.jsp:
!!Aggiungi il link al menu [#8]
L'ultimo passo è rendere visibili all'utente le funzioni elenco, aggiungi, modifica e cancella. Il modo più semplice è aggiungere un nuovo link all'elenco di link in web/pages/mainMenu.jsp:
At line 402 changed 1 line.
Where ''menu.viewPeople'' is an entry in web/WEB-INF/classes/ApplicationResources.properties.
Dove ''menu.viewPeople'' è una voce in web/WEB-INF/classes/ApplicationResources.properties.
At line 407 changed 1 line.
The other (more likely) alternative is that you'll want to add it to the menu. To do this, add the following to web/WEB-INF/menu-config.xml:
L'altra (più probabile) alternative è che tu voglia aggiungerlo al menu. Per farlo, aggiungi quanto segue a web/WEB-INF/menu-config.xml:
At line 414 changed 1 line.
Make sure the above XML is inside the &lt;Menus&gt; tag, but not within another &lt;Menu&gt;. Then add this new menu to web/common/menu.jsp - which should now looks as follows:
Assicurati che l'XML sopra sia all'interno del tag &lt;Menus&gt;, ma non dentro un altro tag &lt;Menu&gt;. Poi aggiungi questo nuovo menu a web/common/menu.jsp - che ora dovrebbe vedersi come segue:
At line 432 changed 1 line.
Now if you run __ant clean deploy__, start Tomcat and go to [http://localhost:8080/appfuse/mainMenu.html], you should see something like the screenshot below.
Se ora esegui __ant clean deploy__, avvii Tomcat e vai su [http://localhost:8080/appfuse/mainMenu.html], dovresti vedere qualcosa di analogo allo screenshot sotto.
At line 438 changed 1 line.
Notice that there is a new link on the left side (from mainMenu.jsp) and on the right in our menu (from menu.jsp).
Nota che c'è un nuovo link sul lato sinistro (da mainMenu.jsp) a sulla destra nel nostro menu (da menu.jsp).
At line 440 changed 2 lines.
!!That's it!
You've completed the full lifecycle of developing a set of master-detail pages with AppFuse and Spring's MVC framework - __Congratulations__! Now the real test is if you can run all the tests in your app without failure. To test, stop tomcat and run __ant clean test-all__. This will run all the unit tests within your project. As a reminder, it should be easy to setup and test AppFuse from scratch using __ant setup-db setup-tomcat test-all__. Also, if you're looking for more robust examples - checkout [Struts Resume|StrutsResume].
!!È tutto!
Hai completato un ciclo di sviluppo intero di un insieme di pagine master-detail con AppFuse e il framework MVC di Spring - __Congratulazioni__! Ora il test vero è se puoi eseguire tutti i test nella tua applicazione senza che falliscano. Per verificare, ferma tomcat ed esegui __ant clean test-all__. Ciò esegue tutti gli unit test all'interno del progetto. Come promemoria, dovrebbe essere semplice impostare e testare AppFuse da zero usando __ant setup-db setup-tomcat test-all__. Inoltre, se stai cercando degli esempi più consistenti - guarda [Struts Resume|StrutsResume].
At line 443 changed 1 line.
''__Happy Day!__''
''__Buona Giornata!__''

Back to ValidationAndListSpring_it, or to the Page History.