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
Articles
CreateManager_it
ValidationAndList_it




JSPWiki v2.2.33

[RSS]


Hide Menu

CreateActions_it


Difference between version 10 and version 3:

At line 12 changed 1 line.
* __<span style="color: green">Spring:</span>__ [Creating Spring Controllers and JSPs|SpringControllers]
* __<span style="color: green">Spring:</span>__ [Creazione Controller Spring e JSP|SpringControllers_it]
At line 31 changed 1 line.
Now let's generate our PersonForm object for Struts and our web tier. To do this, we need to add XDoclet tags to the Person.java Object to create our Struts ActionForm. In the JavaDoc for the Person.java file, add the following @struts.form tag (use User.java if you need an example):
Ora generiamo il nostro oggetto PersonForm per Struts ed il nostro strato web. Per far questo, dobbiamo aggiugere dei tag XDoclet all'oggetto Person.java per creare la nostra ActionForm di Struts. Nel JavaDoc del file Person.java, aggiungi il seguente tag @struts.form (vedi User.java per un esempio):
At line 38 changed 1 line.
;:''We extend org.appfuse.webapp.form.BaseForm because it has a toString() method that allows us to call log.debug(formName) to print out a reader-friendly view of the Form object.''
;:''Estendiamo org.appfuse.webapp.form.BaseForm perché ha un metodo toString() che ci permette di chiamare log.debug(formName) per stampare una visualizzazione più leggibile dell'oggetto Form.''
At line 40 changed 1 line.
;:''If you haven't renamed the "org.appfuse" packages to "com.company" or otherwise don't have your model class in the default package, you may need to fully-qualify the reference to org.appfuse.webapp.form.BaseForm in the @struts.form tag.''
;:''Se non hai rinominato i package "org.appfuse" in "com.company" o in alternativa non hai la tua classe di modello nel package di default, può rivelarsi necessario specificare completamente il riferimento a org.appfuse.webapp.form.BaseForm nel tag @struts.form.''
At line 42 changed 1 line.
Now if you run __ant gen-forms__, Ant (and XDoclet) will generate a PersonForm.java for you in build/web/gen/**/form.
Ora se esegui __ant gen-forms__, Ant (ed XDoclet) genererà un PersonForm.java per te in build/web/gen/**/form.
At line 45 changed 1 line.
In this step, you'll generate a JSP page to display information from the Person object. It will contain Struts' JSP tags that render table rows for each property in Person.java. The [AppGen] tool that's used to do this is based off a StrutsGen tool - which was originally written by [Erik Hatcher|http://www.blogscene.org/erik/]. It's basically just a couple of classes and a bunch of XDoclet templates. All these files are located in extras/appgen.
In questo passo, genererai una pagina JSP per visualizzare le informazioni presenti nell'oggetto Person. Conterrà tag JSP di Struts per visualizzare righe di una tabella per ogni proprietà in Person.java. Lo strumento [AppGen] che viene utilzzato per far questo è basato su uno strumento StrutsGen - che è stato scritto in origine da [Erik Hatcher|http://www.blogscene.org/erik/]. Si tratta in poche parola di giusto un paio di classi ed un po' di template XDoclet. Tutti questi file si trovano in extras/appgen.
At line 47 changed 1 line.
Here are the simple steps to generating the JSP and a properties file containing the labels for the form elements:
Ecco i semplici passi per generare una JSP ed un file properties contenente le etichette per gli elementi del form:
At line 49 changed 6 lines.
* From the command-line, navigate to "extras/appgen"
* Execute __ant -Dobject.name=Person -Dappgen.type=pojo__ to generate a bunch of files in extras/appgen/build/gen. In fact, it'll generate all the files you need to complete this tutorial. However, let's just grab the ones you need.
** web/WEB-INF/classes/Person.properties (labels for your form elements)
** web/pages/personForm.jsp (JSP file for viewing a single Person)
** web/pages/personList.jsp (JSP file for viewing a list of People)
* Copy the contents of Person.properties into web/WEB-INF/classes/ApplicationResources.properties. These are all the keys you will need for titles/headings and form properties. Here is an example of what you should add to ApplicationResources.properties:
* Dalla linea di comando, naviga in "extras/appgen"
* Esegui __ant -Dobject.name=Person -Dappgen.type=pojo__ per generare una serie di file in extras/appgen/build/gen. Infatti, genererà tutti i file di cui hai bisogno per completare questo tutorial. Tuttavia, prendiamo solo quelli di cui abbiamo bisogno.
** web/WEB-INF/classes/Person.properties (etichette per gli elementi del tuo form)
** web/pages/personForm.jsp (file JSP per visualizzare una singola Persona)
** web/pages/personList.jsp (file JSP per visualizzare un elenco di Persone)
* Copia il contenuto di Person.properties in web/WEB-INF/classes/ApplicationResources.properties. Queste sono tutte le chiavi di cui avrai bisogno per titoli/intestazioni e proprietà del form. Ecco un esempio di quello che dovrai aggiungere ad ApplicationResources.properties:
At line 75 changed 1 line.
* Copy personForm.jsp to web/pages/personForm.jsp. Copy personList.jsp to web/pages/personList.jsp.
* Copia personForm.jsp in web/pages/personForm.jsp. Copia personList.jsp in web/pages/personList.jsp.
At line 77 changed 1 line.
;: ''The files in the "pages" directory will end up in "WEB-INF/pages" at deployment time. The container provides security for all files below WEB-INF. This applies to client requests, but not to forwards from Struts' ActionServlet. Placing all JSPs below WEB-INF ensures they are only accessed through Actions, and not directly by the client or each other. This allows security to be moved up into the Action, where it can be handled more efficiently, and out of the base presentation layer.''
;: ''I file nella directory "pages" finiranno in "WEB-INF/pages" al momento del deployment. Il container mette in sicurezza tutti i file sotto WEB-INF. Ciò si applica alle richieste del client, ma non ai forward dalla ActionServlet di Struts. Mettere tutte le JSP sotto WEB-INF assicura che queste siano accedute solo tramite Action, e non direttamente dal client o fra loro. Ciò consente di spostare la sicurezza nella Action, dove può essere gestita in modo più efficiente, e fuori dallo strato di presentazione di base.''
At line 79 changed 1 line.
The web application security for AppFuse specifies that all *.html url-patterns should be protected (except for /signup.html and /passwordHint.html). This guarantees that clients must go through an Action to get to a JSP (or at least the ones in ''pages'').
La sicurezza a livello di web application per AppFuse specifica che tutti le url del tipo *.html siano protette (ad eccezione di /signup.html e /passwordHint.html). Ciò garantisce che i client passino attraverso una Action per arrivare ad una JSP (o almeno a quelle in ''pages'').
At line 81 changed 1 line.
%%note __NOTE:__ If you want to customize the CSS for a particular page, you can add &lt;body id="pageName"/> to the top of the file. This will be slurped up by SiteMesh and put into the final page. You can then customize your CSS on a page-by-page basis using something like the following:
%%note __NOTA:__ Se vuoi personalizzare il CSS per una pagina particolare, puoi aggiungere &lt;body id="pageName"/> in cima al file. Questo verrà risucchiato da SiteMesh e messo nella pagina finale. Dopo puoi personalizzare il tuo CSS pagina per pagina usando qualcosa del tipo seguente:
At line 84 changed 2 lines.
* Add keys in ApplicationResources.properties the titles and headings in the JSPs
In the generated JSPs, there are two keys for the title (top of the browser window) and the header (heading in the page). These fields are provided above with key names of personDetail.title and personDetail.heading.
* Aggiungi le chiavi ApplicationResources.properties relative a titoli ed intestazioni nelle JSP
Nelle JSP generate, ci sono due chiavi per il titolo (in cima alla finestra del browser) e l'intestazione (in testa alla pagina). Questi campi sono forniti sopra con i nomi di chiavi di personDetail.title personDetail.heading.
At line 87 changed 1 line.
''Just above, we added "personForm.*" keys to this file, so why do I use personDetail instead of personForm for the titles and headings? The best reason is because it gives a nice separation between form labels and text on the page. Another reason is because all the *Form.* give you a nice representation of all the fields in your database.
''Appena sopra, abbiamo aggiunto delle chiavi del tipo "personForm.*" a questo file, per cui per quale motivo ora uso personDetail invece di personForm per i titoli e le intestazioni? Il motivo migliore è che dà una buona separazione fra le etichette del form ed il testo nella pagina. Un altro motivo è perché tutti i *Form.* ti danno una buona rappresentazione give di tutti i campi nel tuo database.
At line 89 changed 1 line.
I recently had a client who wanted all fields in the database searchable. This was fairly easy to do. I just looked up all the keys in ApplicationResources.properties which contained "Form." and then put them into a drop-down. On the UI, the user was able to enter a search term and select the column they wanted to search. I was glad I followed this Form vs. Detail distinction on that project!''
Recentemente ho avuto un cliente che voleva tutti i campi nel database ricercabili. Ciò è stato piuttosto semplice da fare. Ho semplicemente cercato tutte le chiavi in ApplicationResources.properties che contenessero "Form." e le ho messe un un menu a discesa. Sulla UI, l'utente poteva inserire un termine da cercare e selezionare la colonna in cui volesse effettuare la ricerca. Sono stato contento di aver seguito questa distinzione Form vs. Detail in quel progetto!''
At line 94 changed 1 line.
To create a StrutsTestCase Test for PersonAction, start by creating a PersonActionTest.java file in the test/web/**/action directory:
Per creare un Test StrutsTestCase per PersonAction, inizia con il creare un file PersonActionTest.java nella directory test/web/**/action:
At line 156 changed 1 line.
You will need to add __PERSON_KEY__ as a variable to the src/dao/**/Constants.java class. The name, "personForm", matches the name given to the form in the struts-config.xml file.
Devi aggiungere __PERSON_KEY__ come variabile alla classe src/dao/**/Constants.java. Il nome, "personForm", corrisponde al nome dato al form nel file struts-config.xml.
At line 166 changed 1 line.
If you try to run this test, you will get a number of NoSuchMethodErrors - so let's define the edit, save, and delete methods in the PersonAction class.
Se provi ad eseguire questo test, otterrai una serie di NoSuchMethodErrors - pertanto definiamo i metodi edit, save, e delete della classe PersonAction.
At line 170 changed 1 line.
In src/web/**/action, create a PersonAction.java file with the following contents:
In src/web/**/action, crea un file PersonAction.java con il seguente contenuto:
At line 289 changed 2 lines.
You'll notice in the code above that there are many calls to to ''convert'' a PersonForm or a Person object. The ''convert'' method is in BaseAction.java (which calls ConvertUtil.convert()) and
uses
Noterai che nel codice sopra ci sono molte chiamate per ''convertire'' un oggetto PersonForm o Person. Il metodo ''convert'' è BaseAction.java (la quale richiama ConvertUtil.convert()) ed
usa
At line 292 changed 1 line.
to convert POJOs &rarr; ActionForms and ActionForms &rarr; POJOs.
per convertire i POJO &rarr; ActionForm ed ActionForm &rarr; POJO.
At line 294 changed 1 line.
;:''If you are running Eclipse, you might have to "refresh" the project in order to see PersonForm. It lives in build/web/gen, which should be one of your project's source folders. This is the only way for Eclipse to see and import PersonForm, since it is generated by XDoclet and does not live in your regular source tree. You can find it at build/web/gen/org/appfuse/webapp/form/PersonForm.java.''
;:''Se stai eseguendo dentro Eclipse, potresti aver bisogno di fare un "refresh" sul progetto in modo da vedere PersonForm. Si trova in build/web/gen, che dovrebbe essere una delle cartelle sorgenti del tuo progetto. Questo è l'unico modo per Eclipse do vedere ed importare PersonForm, in quanto viene generato da XDoclet e non fa parte del tuo albero sorgenti regolare. Puoi trovarlo in build/web/gen/org/appfuse/webapp/form/PersonForm.java.''
At line 296 changed 1 line.
;:''In [BaseAction|http://raibledesigns.com/downloads/apptracker/api/org/appfuse/webapp/action/BaseAction.java.html] you can register additional Converters (i.e. [DateConverter|http://raibledesigns.com/downloads/apptracker/api/org/apptracker/util/DateConverter.java.html]) so that BeanUtils.copyProperties knows how to convert Strings &rarr; Objects. If you have Lists on your POJOs (i.e. for parent-child relationships), you will need to manually convert those using the {{convertLists(java.lang.Object)}} method.''
;:''In [BaseAction|http://raibledesigns.com/downloads/apptracker/api/org/appfuse/webapp/action/BaseAction.java.html] puoi registrare ulteriori Converter (i.e. [DateConverter|http://raibledesigns.com/downloads/apptracker/api/org/apptracker/util/DateConverter.java.html]) in modo che BeanUtils.copyProperties sappia come convertire String &rarr; Object. Se hai delle List nei tuoi POJO (i.e. per relazioni genitore-figlio), dovrai convertirle manualmente usando il metodo {{convertLists(java.lang.Object)}} .''
At line 298 changed 1 line.
Now you need to add the ''edit'' forward and the ''savePerson'' action-mapping, both which are specified in in the PersonActionTest. To do this, add a couple more XDoclet tags to the top of the PersonAction.java file. Do this right above the class declaration. You should already have the XDoclet tag for the ''editPerson'' action-mapping, but I'm showing it here so you can see all the XDoclet tags at the top of this class.
Ora devi aggiungere il forward ''edit'' e l'action-mapping ''savePerson'', entrambi specificati in PersonActionTest. Per farlo, aggiungi un altro paio di tag XDoclet in cima al file PersonAction.java. Fai questo subito sotto la dichiarazione della classe. Dovresti avere di già il tag XDoclet per l'action-mapping ''editPerson'', ma te lo mostro qui in modo che tu possa vedere tutti i tag XDoclet in cima a questa classe.
At line 314 changed 1 line.
The main difference between the ''editPerson'' and ''savePerson'' action-mappings is that ''savePerson'' has validation turned on (see validation="true") in the XDoclet tag above. Note that the "input" attribute must refer to a forward, and cannot be a path (i.e. /editPerson.html). If you'd prefer to use the save path for both edit and save, that's possible too. Just make sure validate="false", and then in your "save" method - you'll need to call form.validate() and handle errors appropriately.
La differenza principale fra gli action-mapping ''editPerson'' e ''savePerson'' è che ''savePerson'' ha la validazion attiva (vedi validation="true") nel tag XDoclet sopra. Nota che l'attributo "input" deve riferirsi ad un forward, e non può essre un path (i.e. /editPerson.html). Se preferisci usare il path di save sia per edit che per save, è possibile anche quello. Controlloa solo che sia impostato validate="false", poi nel tuo metodo "save" - dovrai richiamare form.validate() e gestire gli errori in modo appropriato.
At line 316 changed 1 line.
You might notice that the code you're using to call the PersonManager is the same as the code used in the PersonManagerTest. Both PersonAction and PersonManagerTest are ''clients'' of PersonManagerImpl, so this makes perfect sense.
Potresti notare che il codice che stai usando per richiamare il PersonManager è lo stesso codice usato nel test PersonManagerTest. Sia PersonAction che PersonManagerTest sono ''client'' di PersonManagerImpl, pertanto ciò ha perfettamente senso.
At line 318 changed 1 line.
Everything is almost done for this tutorial, let's get to running the tests!
É quasi tutto fatto per questo tutorial, andiamo ad eseguire i test!
At line 323 changed 1 line.
If you look at our PersonActionTest, all the tests depend on having a record with id=1 in the database (and testRemove depends on id=2), so add that to our sample data file (metadata/sql/sample-data.xml). I'd add it at the bottom - order is not important since it (currently) does not relate to any other tables.
Se guardi il nostro PersonActionTest, tutti i test dipendono dall'avere un record con id=1 nel database (e testRemove dipende da id=2), pertanto aggiungilo al nostro file dati di esempio (metadata/sql/sample-data.xml). Lo aggiungerei in coda - l'ordine non è importante poiché (attualmente) non ha relazioni con altre tabelle.
At line 343 changed 1 line.
DBUnit loads this file before we run any of our tests, so this record will be available to the PersonActionTest.
DBUnit carica questo file prima dell'esecuzione di uno qualsiasi dei nostri test, pertanto questo record sarà disponibile al PersonActionTest.
At line 345 changed 1 line.
Now if you run __ant test-web -Dtestcase=PersonAction__ - everything should work as planned. Make sure Tomcat isn't running before you try this.
Ora se esegui __ant test-web -Dtestcase=PersonAction__ - tutto dovrebbe funzionare come previsto. Controlla che Tomcat non sia in esecuzione prima di provare questo.
At line 352 changed 1 line.
Now let's clean up the generated personForm.jsp. Change the ''action'' of the &lt;html:form&gt; to be "savePerson" so validation will be turned on when saving. Also, change the ''focus'' attribute from focus="" to focus="firstName" so the cursor will be in the firstName field when the page loads (this is done with JavaScript).
Ora ripuliamo la pagina personForm.jsp generata. Modifica la ''action'' di &lt;html:form&gt; in "savePerson" in modo che la validazione sia attiva quando si registra. Modifica anche l'attributo ''focus'' da focus="" a focus="firstName" in modo che il cursore sia nel campo firstName quando la pagina viene caricata (questo viene fatto con JavaScript).
At line 354 changed 1 line.
Another thing you will need to do is comment out the following lines at the bottom of the personForm.jsp. This is because the Validator will throw an exception if a formName is specified and no validation rules exist for it.
Un'altra cosa che devi fare è scommentare le righe seguenti al termine si personForm.jsp. Questo è perché il Validator lancerà un'eccezione se viene specificato un formName e non esistono regole di validazione per esso.
At line 356 changed 1 line.
;:''Personally, I think this is [a bug|http://nagoya.apache.org/bugzilla/show_bug.cgi?id=27316], but the Struts Committers disagreed.''
;:''Personalmente, credo che questo sia [un bug|http://nagoya.apache.org/bugzilla/show_bug.cgi?id=27316], ma i Committer di Struts non erano d'accordo.''
At line 363 changed 1 line.
Now if you execute __ant db-load deploy__, start Tomcat and point your browser to [http://localhost:8080/appfuse/editPerson.html?id=1], you should see something like this:
Ora se esegui __ant db-load deploy__, fai partire Tomcat e punti il tuo browser si [http://localhost:8080/appfuse/editPerson.html?id=1], dovresti vedere qualcosa del genere:
At line 370 changed 1 line.
%%note __NOTE:__ Use the __deploy-web__ target if you've changed any files under the ''web'' directory. Otherwise, use __deploy__ which compiles and deploys.%%
%%note __NOTA:__ Usa il target __deploy-web__ se hai modificato un qualsiasi file sotto la directory ''web''. Altrimenti, usa __deploy__ che compila ed effettua il deploy.%%
At line 372 changed 1 line.
Finally, to make this page more user friendly, you may want to add a message for your users at the top of the form, which can easily be done by adding text (using &lt;fmt:message&gt;) at the top of the personForm.jsp page.
Infine, per rendere questa pagina più user friendly, potresti voler aggiungere un messaggio per i tuoi utenti in cima al form, il che può essere facilmente fatto aggiungenfo del testo (usando &lt;fmt:message&gt;) in cima alla pagina personForm.jsp.
At line 383 changed 3 lines.
* Modifica - [http://localhost:8080/appfuse/editPerson.html?id=1] (make sure and run __ant db-load__ first).
* Elimina - [http://localhost:8080/appfuse/editPerson.html?method=Delete&amp;id=1] (or edit and click on the Delete button).
* Registra - Click [edit|http://localhost:8080/appfuse/editPerson.html?id=1] and then click the Save button.
* Modifica - [http://localhost:8080/appfuse/editPerson.html?id=1] (assicurati di aver eseguito orima __ant db-load__).
* Elimina - [http://localhost:8080/appfuse/editPerson.html?method=Delete&amp;id=1] (o modifica e fai clic sul pulsante Delete).
* Registra - Click [edit|http://localhost:8080/appfuse/editPerson.html?id=1] e fai clic sul pulsante Save.
At line 387 changed 1 line.
I test du Canoo sono piuttosto slick in quanto si configurano tramite un semplice file XML. Per aggiungere test per aggiungi, modifica, registra ed elimina, apri test/web/web-tests.xml ed aggiungi il seguente XML. Noterai che questo frammento ha un target che si chiama ''PersonTests'' per eseguire tutti i test correlati.
I test di Canoo sono piuttosto immediati in quanto si configurano tramite un semplice file XML. Per aggiungere test per add, edit, save e delete, apri test/web/web-tests.xml ed aggiungi il seguente XML. Noterai che questo frammento ha un target che si chiama ''PersonTests'' per eseguire tutti i test correlati.
At line 389 changed 1 line.
;:''I use CamelCase target names (vs. the traditional lowercase, dash-separated) because when you're typing ''-Dtestcase=Name'', I've found that I'm used to doing CamelCase for my JUnit Tests.''
;:''Io uso nomi CamelCase per i target (controlo il tradizionale minuscolo, separato da trattini) perché quando digiti ''-Dtestcase=Name'', ho scoperto che sono solito fare il CamelCase per i miei Test JUnit.''
At line 471 changed 1 line.
After adding this, you should be able to run __ant test-canoo -Dtestcase=PersonTests__ with Tomcat running or __ant test-jsp -Dtestcase=PersonTests__ if you want Ant to start/stop Tomcat for you. To include the PersonTests when all Canoo tests are run, add it as a dependency to the "run-all-tests" target.
Dopo aver aggiunto questo, dovresti essere in grado di eseguire __ant test-canoo -Dtestcase=PersonTests__ con Tomcat in esecuzione o __ant test-jsp -Dtestcase=PersonTests__ se vuoi che Ant faccia lo start/stop di Tomcat per te. Per includere i PersonTests quando vengono eseguiti tutti i test Canoo, aggiungilo come dipendenza al target "run-all-tests".
At line 473 changed 1 line.
You'll notice that there's no logging in the client-side window by Canoo. If you'd like to see what it's doing, you can add the following between &lt;/webtest&gt; and &lt;/target&gt; at the end of each target.
Noteria che no c'è alcun log nella finestra lato client di Canoo. Se vuoi vedere cosa sta facendo, puoi aggiungere le righe seguenti fra &lt;/webtest&gt; e &lt;/target&gt; alla fine di ciascun target.
At line 485 changed 1 line.
''Next Up:'' __Part IV:__ [Adding Validation and List Screen|ValidationAndList] - Adding validation logic to the personForm so that firstName and lastName are required fields and adding a list screen to display all person records in the database.
''Prossima Puntata:'' __Parte IV:__ [Aggiungere la Validazione ed una Schermata Elenco|ValidationAndList_it] - Aggiungere una logica di validazione al personForm in modo che firstName e lastName siano campi obbligatori ed aggiungere una schermata di elenco per visualizzare tutti i record di tipo person nel database.

Back to CreateActions_it, or to the Page History.