Vous êtes sur la page 1sur 127

TUTORIAL

FRAMEWORKS
STRUTS

TUTORIALFRAMEWORKSTRUTS

http://www.railsymas.com

TUTORIALFRAMEWORKSTRUTS

INTRODUCCINASTRUTSCONECLIPSE..............................................................................................7
FORMULARIOLOGINSTRUTSECLIPSE................................................................................................14
ELFICHEROCSSESTILO.CSSESELQUESEVAAUTILIZARPARALAMAQUETACINDELEJEMPLO.....................................17
CDIGODELFICHERODEPROPIEDADESMESSAGERESOURCES_ES_ES....................................................................19
CDIGODELACLASEJAVAPARAELACTIONFORMLALLAMAMOSFORMULARIOFORM...........................................20
CDIGOJAVADELACLASEACTIONLALLAMAMOSACCIONLOGIN......................................................................22
FORMULARIOLOGINSTRUTS2PARTE...............................................................................................26
CDIGOFUENTEDELAPGINACACELADA.JSP...................................................................................................26
CDIGOFUENTEDELAPGINASATISFACTORIA.JSP.............................................................................................27
CONFIGURACINDELFICHEROSTRUTSCONFING.XML.........................................................................................28
ESTEFRAGMENTOYALOTENAMOSDELHOLAMUNDO........................................................................................28
FRAGMENTOCORRESPONDIENTEALMAPEODELOSACTION.................................................................................28
CREARUNAVENTANADEERROR404Y500ENSTRUTSCONECLIPSE.................................................30
PARAELERROR500CLAVESPARAMESSAGERESOURCES.PROPERTIES....................................................................30
PARALAPGINA404.JSP..............................................................................................................................30
PARALAPGINA500.JSP..............................................................................................................................31
ERROR500EJEMPLO...................................................................................................................................31
FORMULARIODYNAACTIONFORMSTRUTSECLIPSE...........................................................................32
VENTANADEREGISTRODINMICO..................................................................................................................32
VENTANADEDATOSPERSONALESUNAVEZELREGISTROHASIDOENVIADO..............................................................32
FICHEROFORMULARIODINAMICO.JSPPARA(PARACREARLOVIENEENPOSTDELOGINSTRUTSANTERIOR)......................33
CLASEACTIONDENTRODELPACKAGEACCIONESACCIONDINAMICA.JAVA................................................................34
VENTANACANCELADA2................................................................................................................................35
PGINAJSPCANCELADA2.JSP.........................................................................................................................35
PGINADATOSPERSONALES.JSP......................................................................................................................36
STRUTSFORMULARIODYNAVALIDATORFORMECLIPSE.....................................................................40
CDIGODELAPGINAEJERCICIOS.JSP.............................................................................................................41
CDIGODELAPGINAFORMDINAVALIDACION.JSP.............................................................................................43
IMAGENDELFORMULARIO.............................................................................................................................44
CDIGOFUENTEDELAPGINAPERSONALESDATOSPERSONALES2.JSP....................................................................45
COFIGURACINDELACTIONENELFICHEROSTRUTSCONFIG.XML..........................................................................46
CLASEACTIONENELPACKAGEDEACCIONES.....................................................................................................47
CDIGODEMESSAGERESOURCES_ES_ES.PROPERTIES........................................................................................47
STRUTSDISPATCHACTIONECLIPSE....................................................................................................49
CDIGOPARALACONFIGURACINDELARCHIVOSTRUTSCONFIG.XML...................................................................49
CDIGOQUEAADIMOSALARCHIVOEJERCICIOS.JSP..........................................................................................49
DECLARACINDELFORMULARIODINMICOENELFICHEROSTRUTSCONFIG.XML.....................................................50
CONFIGURACINDELACTIONENELSTRUTSCONFIG.XMLACTIONDINAMICOLIBRO2..............................................50
CDIGOFUENTEDELFICHERODELFICHEROFORMULARIODISPATCH.JSP..................................................................56
CDIGOFUENTEDELFICHEROEDICION.JSP.......................................................................................................57
CDIGOFUENTEDELFICHERODATOSLIBROS.JSP................................................................................................58
IBATISPROYECTOWEBECLIPSE.........................................................................................................59

http://www.railsymas.com

TUTORIALFRAMEWORKSTRUTS
CLASEBEANLIBRO.JAVA...............................................................................................................................59
FICHERODECONFIGURACINDESQLMAP.......................................................................................................61
STRUTSTILESPROYECTOWEBECLIPSE..............................................................................................66
STRUTSTILESPROYECTOWEBECLIPSE2PARTE.................................................................................71
TUTORIALHTMLSTRUTSTAGS..........................................................................................................74
TUTORIALDELOOKUPDISPATCHACTIONSTRUTS...............................................................................75
CDIGODEPGINAEJERCICIOS.JSPCOMOLOSANTERIORESEJEMPLOS....................................................................75

CONFIGURACIONDELBEANDYNAVALIDATORFORM...........................................................................................76
CONFIGURACINDELARCHIVOSTRUTSCONFIG.XMLPARAACTIONMAPPING.........................................................76
CONFIGURACINDELFICHERODEPROPIEDADESPROPERTIES................................................................................77
CDIGODELAPGINAJSPFORMULARIOLOOKUP.JSP..........................................................................................77
CLASELOOKUPDISPATCHACTIONACCIONLOOKUPDISPATCHACTION.JAVA..............................................................78
DATASOURCESTRUTS1.2.XPROYECTOWEBECLIPSE.........................................................................83
DATASOURCESTRUTS...................................................................................................................................83
CONFIGURACINDELARCHIVOSTRUTSCONFIG.XMLPARAELDATASOURCE............................................................83
CONFIGURACINDELOSACTIONSPARAELSTRUTSCONFIG.XML............................................................................84
CDIGODELAPGINAFALLIDA.JSP.................................................................................................................85
CDIGODELAPGINAREGISTROSATISFACTORIO...............................................................................................86
CDIGODELACLASEJAVAACCIONBASEDATOSDENTRODELPACKAGEDEACCIONES.................................................87
DATASOURCESTRUTS1.3.XPROYECTOWEBECLIPSE.........................................................................90
CONFIGURACINDELAACCINDATASOURCE.DOENELSTRUTSCONFIG.XML..........................................................90

CONFIGURACINDELFICHERODEPROPIEDADES................................................................................................90
CLASECONEXIONDENTRODELPACKAGECONEXIONES........................................................................................92
CONFIGURACINDELFICHEROWEB.XML..........................................................................................................93
FICHEROCONTEXT.XML.................................................................................................................................93
CONFIGURACINDELAACCINFORMULARIODATASOURCE.DO.............................................................................94
FORMULARIODATASOURCE.JSP.......................................................................................................................96
MOSTRARLISTADO.JSP...................................................................................................................................97
MOSTRANDOLISTADODEDATOS....................................................................................................100
DESARROLLOWEBUPLOADFILESTRUTS..........................................................................................102
CDIGODELACLASESUBIRARCHIVO.............................................................................................................103
CDIGODELAPGINAJSPENCARGADADEMOSTRARELFORMULARIODESUBIDADEARCHIVO..................................104
ENELFICHERODEPROPIEDADES...................................................................................................................105
CLASEBEANPARAELFORMULARIO................................................................................................................105
DESARROLLOWEBMLTIPLESARCHIVOSDECONFIGURACINSTRUTS...........................................108
CDIGODELAPGINAENLACEPRIVADO.........................................................................................................108
ENELFICHEROWEB.XMLDELPROYECTO........................................................................................................110
DESARROLLOWEBCOMODINESSTRUTS..........................................................................................111
CONFIGURACINDELARCHIVOSTRUTSCONFIGWILDCARD.XML.........................................................................111
CDIGODEENLACES.JSP..............................................................................................................................112
PGINA1JSP............................................................................................................................................112
PGINA2JSP............................................................................................................................................113

http://www.railsymas.com

TUTORIALFRAMEWORKSTRUTS
CREACINDEUNPLUGINCONSTRUTSXMLDOM...........................................................................114
CLASEOBRERO..........................................................................................................................................117
CONFIGURACINDELACTIONENSTRUTSCONFIG.XML......................................................................................118
INTEGRACINSTRUTSHIBERNATE..................................................................................................119
ARCHIVODECONFIGURACINHIBERNATE.CFG,XML..........................................................................................125

http://www.railsymas.com

TUTORIALFRAMEWORKSTRUTS

http://www.railsymas.com

TUTORIALFRAMEWORKSTRUTS

INTRODUCCINASTRUTSCONECLIPSE

Vamosadescargarnoselproyectostrutsdelapginaweboficial
http://struts.apache.org/download.cgi

escogemoslaversin1.3.10
Laubicamosennuestrosistemadearchivosindependientementedelsistema
operativoqueutilicemosydescomprimimoselficherozip

Dentrodellacarpetadelproyectodestrutshayunfichero.warquecontienela
estructuradeunaaplicacinenblanco.Seutilizaparanotenerqueirincorporandojar
alproyectonitldsparalasetiquetasstruts.
larutaescarpetastrutsproyectoqueparalaversinquehemosdescargadoespath
vuestro\struts1.3.10\apps\strutsblank1.3.10.war

http://www.railsymas.com

TUTORIALFRAMEWORKSTRUTS

Lonicoquetenemosquehaceresabrirnuestroeclipseeimportardichoproyectoen
blancoydarleunnombrenuevoparapoderempezar.
File,importwaryseleccionarlarutadondeestanuestroficheroblank.warparala
version1.3.10

ledamosanextynosapareceotronuevocuadrodedilogodondeledamosnombre
alproyectoyledecimosdondeestaelficheroblank.war

http://www.railsymas.com

TUTORIALFRAMEWORKSTRUTS

pulsamossobreelbotnfinishyenlapestaaexploradordelproyectovemosla
estructuradedirectoriosdelnuevoproyectoenblancoholamundo
Aligualqueenlosproyectosdejeeparaejecutarelproyectovamosarunasrunon
serverescogemostomcatysalelapantalladebienvenidadelproyectostruts

Vamosamodificarelproyectoparaquesalgaunmensajeencastellano,paraello
vamosaconservarlasjspquetieneelproyectopordefectoycrearemosunnuevo
ficherodepropiedadesllamado
MesssageResources_es_ES.propertiesenelquevamosaincluirunaclavesparaque

http://www.railsymas.com

TUTORIALFRAMEWORKSTRUTS

salgaporpantallaunmensajedebienvenida.

Enelnuevoficherodeproperties
1 welcome.title=Holamundo

Struts

2 welcome.heading=Bienvenida!
3 welcome.message=HolamundoStruts

http://www.railsymas.com

10

TUTORIALFRAMEWORKSTRUTS

Ydentrodelficherodeconfiguracinstrutsconfig.xmlponemoslosiguiente
1 <!========================================MessageResourcesDefinitions>
2
3 <messageresourcesparameter="MessageResources_es_ES"/>
4 <messageresourcesparameter="MessageResources"/>

Vamosaentenderunpocoestoqueacabamosdehaceryasentenderel
funcionamientodestruts.DentrodeldirectorioWebCotentqueescomoenjeeel
directoriopblicohayunacarpetapagesdondetenemosunapginawelcome.jspcon
estecontenido
1 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
2 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
3 <%@tagliburi="http://struts.apache.org/tagslogic"prefix="logic"%>
4
5 <html:html>
6 <head>
7 <title><bean:messagekey="welcome.title"/></title>
8 <html:base/>
9 </head>
10 <bodybgcolor="white">
11
12 <logic:notPresentname="org.apache.struts.action.MESSAGE"scope="application">
13 <fontcolor="red">
14 ERROR:Applicationresourcesnotloadedcheckservletcontainer

http://www.railsymas.com

11

TUTORIALFRAMEWORKSTRUTS

15 logsforerrormessages.
16 </font>
17 </logic:notPresent>
18
19 <h3><bean:messagekey="welcome.heading"/></h3>
20 <p><bean:messagekey="welcome.message"/></p>
21
22 </body>
23 </html:html>

Vamosacentrarnossolamenteenporquesaleelmensajeencastellano,deciramodo
decomentarioquestrutstienesuspropiostagshtmlvanprecedidiosdehtm:se
puedenvervarioscasoscomoydespusotrasetiquetas.
vemosquelaetiquetabean:messagetieneunatributokeyconunvalorwelcome.title
paraelcasodelttulo,lomismovaasucederconelencabezadoyconmensaje.Loque
haceestaetiquetaesobtenerelvalordelficherodeconfiguracinreciencreado
elformatodeesteficherodedepropiedadesesclave=valor
Sinosfijamosennavegadoryvemoslaurldelproyectoarrancadoenlocal,
observamosqueterminaenWelcome.do,nosestaindicandoquestrutsest
realizandolaaccinWelcome.
1 <!===========================================GlobalForwardDefinitions>
2
3 <globalforwards>
4 <!Defaultforwardto"Welcome"action>
5 <!Demonstratesusingindex.jsptoforward>
6 <forward
7 name="welcome"
8 path="/Welcome.do"/>
9 </globalforwards>

Quesemapeaenlasecciondeacctionmetiante
1<!===========================================ActionMappingDefinitions>

http://www.railsymas.com

12

TUTORIALFRAMEWORKSTRUTS

2
3 <actionmappings>
4 <!Default"Welcome"action>
5 <!ForwardstoWelcome.jsp>
6 <action
7 path="/Welcome"
8 forward="/pages/Welcome.jsp"/>

LaaccionWelcome.doestamapeadaenlaseccionactionmappingmedianteel
nombredepathigualquelaaccionperosindopath=/Welcomeysereenvalala
pginajspquevieneconelproyectostruts/pages/Welcome.jpdentrodeldirectoria
pblicoWebContent

http://www.railsymas.com

13

TUTORIALFRAMEWORKSTRUTS

FORMULARIOLOGINSTRUTSECLIPSE

ParahacerestetutorialvamosapartirdelproyectowebHolamundorealizado
anteriormenteHolamundo
EnesteejemplosevenconeclipselautilizacindelosActionylosActionFormas
comolaconfiguracindelstrutsconfing,utilizacinycargadeimgenesyutilizacin
dearchivoscssenproyectosstruts.
Nohayconexinparabasededatossedejaparaotrospostynoseutilizael
DynaActionFormquelosveremosenotrospost.
Sepresentaelinterfazgrficodelaapliacinparaunmejorentendimiento,tenemos
unformularioderegistroquetomaelnombreelapellidoyotrosdoscamposclavey
confirmacindeclave,todosestoscamposdebenserrellenadosporelusuarioyse
compruebaquelaclaveysuconfirmacinsoniguales.Elusuariotienelaposibilidadde
cancelarelregistroyvoveralapaginaderegistrodesdeladecancelacin.
Ventanaderegistro

creacindelapginalogin.jspconeclipselasdemspginasserealizarndelamisma
forma(cambiamoselnombredellapgina)

http://www.railsymas.com

14

TUTORIALFRAMEWORKSTRUTS

cdigocorrespondientealficherologin.jspeselcdigoasociadoalaventanade
registro
Unadelascaractersticasdestrutsesquetienesupropiostagsparahtml,vienen
siempreconlapalabrahtml:ydespueselnombredelaetiquetaencuestion.
Paralacategoradej2eedeestesitiowebyahicieronejemplosdeintegracindecss
conj2ee,comentoestoporquehayunadiferenciaimportanteconstruts.Paramucha
gentequevienedeotroslenguajesodehacerjspestaranacostumbradosacolocarel
archivocssenundeterminadodirectorioyenlazarlomediantelaetiquelalink.Bien
paraquelascssolasimgeneslaspodamosincluirenunproyectostrutsesnecesario
incluirenelheaddelapginajspdestrutslaetiqueta.
Sinosfijamosenlasjspvemosqueaparecenentodasellas,loquehaceestaetiqueta
esestablecerelpuntodereferenciadelapginaconrespectoalrestoalrestode
recursosdelproyecto.
Ejemplo,siyosoylapginalogin.jspymedicenquehayunacssen../css/estilo.css
entoncessequetengoque
buscarenmidirectoriopadreybajaraldirectoriocssyalliencuentroestilo.css.Sino
tengolareferenciabasenopuedoencontrarlosrecursoscssnideimagen.

http://www.railsymas.com

15

TUTORIALFRAMEWORKSTRUTS

Ademsenlacabeceradelajspdebemosdeincluirel<%@taglib
uri="http://struts.apache.org/tagshtml"prefix="html"%>
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
3 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
4
5 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
6 "http://www.w3.org/TR/html4/loose.dtd">
7 <html:html>
8 <head>
9
10 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
11
12 <title><bean:messagekey="titulo.login"/></title>
13 <html:base/>
14
15 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
16 </head>
17 <body>
18 <divid="contenedor">
19 <h2><bean:messagekey="titulo.login"/></h2>
20 <divid="errores">
21 <html:errors/>
22 </div>
23
24 <divid="imagen">
25 <html:imgsrcKey="login.imagen"titleKey="login.imagen.alt"/>
26 </div>
27
28 <divid="contenido">
29 <html:formaction="loginAction"focus="nombre"styleId="formulario"method="post">
30
31 <divclass="campo">
32 <bean:messagekey="login.nombre"/>
33 <html:textproperty="nombre"/>
34 </div>
35
36 <divclass="campo">
37 <bean:messagekey="login.apellidos"/>
38 <html:textproperty="apellidos"/>
39 </div>
40
41 <divclass="campo">
42 <bean:messagekey="login.clave"/>
43 <html:passwordproperty="clave"maxlength="8"size="8"/>
44 </div>
45
46 <divclass="campo">
47 <bean:messagekey="login.claveConfirmacion"/>
48 <html:passwordproperty="claveConfirmacion"maxlength="8"size="8"/>
49 </div>
50
51
52 <html:submitstyleClass="boton"value="enviar"/>
53 <html:cancelstyleClass="boton"value="cancelar"/>

http://www.railsymas.com

16

TUTORIALFRAMEWORKSTRUTS

54
55 </html:form>
56 </div>
57
58 <divid="pie">
59 <p>www.railsymas.com</p>
60 </div>
61
62 </div>
63
64 </body>
</html:html>

Secreandoscarpetasnuevasalproyectollamadasimagenesycss(cadaunolas
puedellamarcomoquieramientrasmantengalacorrespondenciaconotraspartesdel
proyecto)
Imagendecreacin,carpetaimagenes

ELFICHEROCSSESTILO.CSSESELQUESEVAAUTILIZARPARALAMAQUETACIN
DELEJEMPLO
1 #contenedor{
2 width:600px;
3 marginleft:auto;

http://www.railsymas.com

17

TUTORIALFRAMEWORKSTRUTS

4 marginright:auto;
5 }
6
7 .campo{
8 margintop:10px;
9 }
10
11 #imagen{
12 float:right;
13 }
14
15
16 .boton{
17 margin:10px5px;
18 backgroundcolor:#554444;
19 color:#fff;
20 width:100px;
21 }
22
23 #formulario{
24
25 margintop:60px;
26 fontsize:16px;
27 }
28 #errores{
29 backgroundcolor:#e6dfd5;
30 color:#424c56;
31 }
32
33 #erroresulli{
34
35 liststyleimage:url("../imagenes/flechaderecha.png");
36
37 }
38
39 #erroresul{
40 bordercolor:#f00;
41
42 }
43
44 h2{
45 textalign:center;
46 }
47
48 #pie{
49 clear:both;
50 height:30px;
51 backgroundcolor:#424c56;
52 }
53
54 #piep{textalign:right;
55 fontsize:14px;
56 backgroundcolor:#e6dfd5;
57 }

http://www.railsymas.com

18

TUTORIALFRAMEWORKSTRUTS

CDIGODELFICHERODEPROPIEDADESMESSAGERESOURCES_ES_ES
1 #clavesparalogin
2 titulo.login=Registrousuario
3 login.nombre=nombre
4 login.apellidos=apellidos
5 login.claveConfirmacion=confirmacindepassword
6 login.clave=password
7 login.imagen.alt=iconousuario
8 login.imagen=../imagenes/usuario.png;
9
10 #clavesdeerror
11 error.login.nombre=faltaelcamponombre
12 error.login.apellidos=faltaelcampoapellidos
13 error.login.clave=faltaelcampoclave
14 error.login.claveConfirmacion=faltaelcampoclaveconfirmacion
15 error.login2=repitelaclave
16
17 #clavesparasatisfactoria
18 satisfactoria.titulo=Resgistrocorrecto
19 satisfactoria.imagen=../imagenes/correcto.png
20 satisfactoria.imagen.alt=imagencorrecto
21 satisfactoria.mensaje=Tehasregistradocorrectamente
22
23 #clavesparacancelada

24 cancelada.titulo=Registrocancelado
25 cancelada.mensaje=Notehasregistradoenelsistema
26 cancelada.imagen.alt=imagencancelado
27 cancelada.imagen=../imagenes/cancelado.png
28 cancelada.login=Cancelacin
29
30 #clavesparawelcome
Struts

31 welcome.title=Holamundo
32 welcome.heading=Bienvenida!
33 welcome.message=HolamundoStruts

CreamoslanuevaclaseFormularioFromdentrodelpackageformularios

http://www.railsymas.com

19

TUTORIALFRAMEWORKSTRUTS

CDIGODELACLASEJAVAPARAELACTIONFORMLALLAMAMOS
FORMULARIOFORM
1 packageformularios;
2
3 importorg.apache.struts.action.ActionForm;
4
5 importorg.apache.struts.action.ActionMapping;
6 importorg.apache.struts.action.ActionErrors;
7 importorg.apache.struts.action.ActionMessage;
8 importjavax.servlet.http.HttpServletRequest;
9
10
11
12 publicclassFormularioFormextendsActionForm{
13
14 staticfinallongserialVersionUID=1L;
15
16 privateStringnombre;
17 privateStringapellidos;
18 privateStringclave;
19 privateStringclaveConfirmacion;
20
21 //mtodosgettersysettersdelformulario
22
23 publicStringgetNombre(){
returnnombre;
24
25 }

http://www.railsymas.com

20

TUTORIALFRAMEWORKSTRUTS

26 publicvoidsetNombre(Stringnombre) {
27
this.nombre=nombre;
28 }
29 publicStringgetApellidos(){
30
returnapellidos;
31 }
32 publicvoidsetApellidos(Stringapellidos){
33
this.apellidos=apellidos;
34 }
35 publicStringgetClave(){
returnclave;
36
37 }
38 publicvoidsetClave(Stringclave){
this.clave=clave;
39
40 }
41 publicStringgetClaveConfirmacion(){
returnclaveConfirmacion;
42
43 }
44 publicvoidsetClaveConfirmacion(StringclaveConfirmacion){
this.claveConfirmacion=claveConfirmacion;
45
46 }
47
48 //mtodoquepermitelavalidacindeloscamposdelformulario
49 publicActionErrorsvalidate(ActionMappingmapping,HttpServletRequestrequest)
50 {
//creamosunnuevoobjetoActionErrors
51
ActionErrorserrores=newActionErrors();
52
53
if(nombre==null||nombre.length()==0)
54
{

55
56

errores.add("nombre",newActionMessage("error.login.nombre"));
57
}
58
59
if(apellidos==null||apellidos.length()==0)
60
{
61

errores.add("apellidos",newActionMessage("error.login.apellidos"));
62
}
63
64
if(clave==null||clave.length()==0)
65
{
66

errores.add("clave",newActionMessage("error.login.clave"));
67
}
68
69
if(claveConfirmacion==null||claveConfirmacion.length()==0)
70
{
71
72

errores.add("claveConfirmacion",new
73 ActionMessage("error.login.claveConfirmacion"));
74
}
75
76
if(!clave.equals(claveConfirmacion))
77
{
78

errores.add("confirmacion",newActionMessage("error.login2"));
79
}
80
81

http://www.railsymas.com

21

TUTORIALFRAMEWORKSTRUTS

82
return errores;
83 }
84
85 //mtodopararesetearloscamposdelformulario
86 publicvoidreset()
87 {
88
this.nombre=null;
89
this.apellidos=null;
90
this.claveConfirmacion=null;
this.clave=null;
91
92 }
93
94
}

CremosunanuevaclaseActiondentrodelpackageAcciones

CDIGOJAVADELACLASEACTIONLALLAMAMOSACCIONLOGIN
1
2
3
4
5
6
7
8

packageacciones;

importorg.apache.struts.action.Action;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionMapping;
importorg.apache.struts.action.ActionForward;

http://www.railsymas.com

22

TUTORIALFRAMEWORKSTRUTS

9
10
11 importformularios.*;
12
13 //claseaction
14 publicclassAccionLoginextendsAction{
15
16
privateStringresultado;
17
18 //creacindelmtodoexecute
publicActionForwardexecute(ActionMappingmapping,ActionFormform
19
20 ,HttpServletRequestrequest,HttpServletResponseresponse)throwsException
{
21
22
23

//sielusuariopulsaelbotndecancelado
24

if(this.isCancelled(request))
25

{
26

//comotenemosenelmtodoexecuteelobjetoActionMapging
27
28 podemosmandaraunreenviodelstrutsconfig

returnmapping.findForward("cancelada");
29

}
30

else
31

{
32

//creamosunobjetoformularioForm
33

FormularioFormformularioform=(FormularioForm)form;
34
35

returnmapping.findForward("satisfactoria");
36
37

}
38

}
}

SiintentamosejecutarunaclaseActionsinsucorrespondienteActionFormnosdael
siguienteerroralejecutarelproyeto(salemuchomsporpantallaperosonlasdos
lneasclaves)
1 javax.servlet.ServletException:Formbeannotspecifiedonmappingforaction: "loginAction"
2
3 org.apache.jasper.JasperException:ExceptioninJSP:/pages/login.jsp

Ventanadeerrorescamposvacos

http://www.railsymas.com

23

TUTORIALFRAMEWORKSTRUTS

Errordeclave(nosoniguales)

http://www.railsymas.com

24

TUTORIALFRAMEWORKSTRUTS

Enlasegundapartedeesteejemploformulariologinstruts2parteeclipse
Sevenlaspginascancelada.jspysatisfactoria.jspascomolacofiguracindelstruts
config.xmlyexplicacionescorrespondientes.
Agradecimientosporlasimgenesutilizadasavawww.webintenta.com
http://www.smashingmagazine.com/2008/08/27/onstageafreeiconset/
http://nick7even.deviantart.com/gallery/

http://www.railsymas.com

25

TUTORIALFRAMEWORKSTRUTS

FORMULARIOLOGINSTRUTS2PARTE

Ventanadecancelacin

Enlacealaprimerapartedeltutorialloginstruts
CDIGOFUENTEDELAPGINACACELADA.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8"
2 pageEncoding="UTF8"%>
3 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
4 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
5 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
6 "http://www.w3.org/TR/html4/loose.dtd">
7 <html:html>
8 <head>
9 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
10
11
12 <title><bean:messagekey="cancelada.titulo"/></title>
13 <html:base/>
14
15 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
16 </head>
17 <body>
18
19 <divid="contenedor">
20 <h2><bean:messagekey="cancelada.login"/></h2>
21 <divid="imagen">
22 <html:imgsrcKey="cancelada.imagen"titleKey="cancelada.imagen.alt"/>
23 </div>

http://www.railsymas.com

26

TUTORIALFRAMEWORKSTRUTS

24 <divid="mensaje">
25 <bean:messagekey="cancelada.mensaje"/>
26 <divclass="campo">
27 <html:linkpage="/pages/login.jsp">Volveralformulariologin
28 </html:link>
29 </div>
30 </div>
31 <divid="pie">
32 <p>www.railsymas.com</p>
33 </div>
34
35 </div>
36
37 </body>
</html:html>

VentanaCorrectocuandoelusuariotienetodosloscamposcorrectos

CDIGOFUENTEDELAPGINASATISFACTORIA.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9 <title><bean:messagekey="satisfactoria.titulo"/></title>
10 <html:base/>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14 <divid="contenedor">
15 <h2><bean:messagekey="satisfactoria.titulo"/></h2>
16 <divid="imagen">

http://www.railsymas.com

27

TUTORIALFRAMEWORKSTRUTS

17 <html:imgsrcKey="satisfactoria.imagen" titleKey="satisfactoria.imagen.alt"/>
18 </div>
19 <divid="mensaje">
20 <bean:messagekey="satisfactoria.mensaje"/>
21
22 <divclass="campo">
23 <bean:writename="loginFormulario"property="nombre"/>
24 </div>
25 </div>
26 <divid="pie">
27 <p>www.railsymas.com</p>
28 </div>
29 </div>
30
31 </body>
</html:html>

CONFIGURACINDELFICHEROSTRUTSCONFING.XML
1
2 <!================================================FormBeanDefinitions>
3
4 <formbeans>
5
6 <formbean
7 name="loginFormulario"
8 type="formularios.FormularioForm"/>
9 </formbeans>

ESTEFRAGMENTOYALOTENAMOSDELHOLAMUNDO
1 <!=========================================== GlobalForwardDefinitions>
2
3 <globalforwards>
4 <!Defaultforwardto"Welcome"action>
5 <!Demonstratesusingindex.jsptoforward>
6 <forward
7 name="welcome"
8 path="/Welcome.do"/>
9 </globalforwards>

FRAGMENTOCORRESPONDIENTEALMAPEODELOSACTION
1 <!=========================================== ActionMappingDefinitions>
2
3 <actionmappings>
4 <!Default"Welcome"action>
5 <!ForwardstoWelcome.jsp>
6 <!modificamoselforwardparaqueapuntealapaginadelogin.jsp>
7 <action
8 path="/Welcome"
9 forward="/pages/login.jsp"/>
10
11 <!creamoslaaccionlogin>
12 <action
13
14 path="/loginAction"

http://www.railsymas.com

28

TUTORIALFRAMEWORKSTRUTS

15 type="acciones.AccionLogin"
16 scope="session"
17 name="loginFormulario"
18 validate="true"
19 input="/pages/login.jsp"
20 >
21 <setpropertyproperty="cancellable"value="true"/>
22 <exceptionkey="errors.cancel"type="org.apache.struts.action.InvalidCancelException"
23 path="/Welcome.do"/>
24 <forwardname="cancelada"path="/pages/cancelada.jsp"/>
25 <forwardname="satisfactoria"path="/pages/satisfactoria.jsp"/>
</action>

http://www.railsymas.com

29

TUTORIALFRAMEWORKSTRUTS

CREARUNAVENTANADEERROR404Y500ENSTRUTSCONECLIPSE

Cuandoseproduceunerror404,muchasvecescuandonavegamosporinternetnos
podemosencontrarconesteerror.Lavisualizacindelmismodependedelnavegador
queestemosutilizandoobiendelagestindedichoerrorporpartedelsitowebal
quequeremosacceder.
Enstrutstambinpodemosgestionardichoserrores,paraellonosvamosalficherode
descriptordedespliegueweb.xmlyescribimoslosiguiente
1 <!declaramoslapginadeerror>
2
3 <errorpage>
4 <errorcode>404</errorcode>
5 <location>/pages/404.jsp</location>
6 </errorpage>
<errorpage>
1
<errorcode>500</errorcode>
2

3
<location>/pages/500.jsp</location>
4
</errorpage>

Lassituacionesenlasqueseproduceesteerrorseriancuandonosbrindanunenlacea
unsitioyelrecursoalqueapuntaelenlacenoexisteobiencuandoescribimos
directamenteunadireccindeunapginasobreunsitiowebylohacemosmal.
PARAELERROR500CLAVESPARAMESSAGERESOURCES.PROPERTIES
1 #error404
2 error.404.titulo=Recursonodisponible
3 error.404.imagen=../imagenes/cancelado.png
4 error.404.imagen.alt=nodisponible
5 error.404.mensaje=pginanoencontrada
6
7 #error500
8 error.500.titulo=Errorenlap&acute;gina
9 error.500.imagen=../imagenes/cancelado.png
10 error.500.imagen.alt=nodisponible
11 error.500.mensaje=Losentimos,sehaproducidounerrorinterno

PARALAPGINA404.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
4
5 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
6 "http://www.w3.org/TR/html4/loose.dtd">
7 <html:html>
8 <head>
9
10 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
11 <title><bean:messagekey="error.404.titulo"/></title>

http://www.railsymas.com

30

TUTORIALFRAMEWORKSTRUTS

12 <html:base/>
13 </head>
14 <body>
15
16 <divstyle="float:left;marginleft:200px">
17 <h1><bean:messagekey="error.404.mensaje"/></h1>
18
19 </div>
20 <html:imgsrcKey="error.404.imagen"titleKey="error.404.imagen.alt"/>
21 </body>
</html:html>

PARALAPGINA500.JSP

Exactamenteigual
<%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
1
<%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
2
<%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
3

4
<!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5
"http://www.w3.org/TR/html4/loose.dtd">
6
<html:html>
7
<head>
8
<metahttpequiv="ContentType"content="text/html;charset=UTF8">
9
<title><bean:messagekey="error.500.titulo"/></title>
10
<html:base/>
11
</head>
12
<body>
13

14
<divstyle="float:left;marginleft:200px">
15
<h1><bean:messagekey="error.500.mensaje"/></h1>
16

17

18
</div>
19
<html:imgsrcKey="error.500.imagen"titleKey="error.500.imagen.alt"/>
20

21
</body>
22
</html:html>

ERROR500EJEMPLO

http://www.railsymas.com

31

TUTORIALFRAMEWORKSTRUTS

FORMULARIODYNAACTIONFORMSTRUTSECLIPSE

Paraestetutorialpartimosdelproyectoholamundocreadoinicialmenteenanteriores
posts,estaimagensecorrespondealaventanadeloginparaelformulariodinmico
VENTANADEREGISTRODINMICO

VENTANADEDATOSPERSONALESUNAVEZELREGISTROHASIDOENVIADO

http://www.railsymas.com

32

TUTORIALFRAMEWORKSTRUTS

LoprimerodetodoqueesDynaActionFormomejorparaquesirve?,buenoestaclase
permiteastrutstrabajarconloscamposdeunformulariosintenerquehaceruna
claseFormBeancomoenelejemplodeloginstrutsanteriormentevisto.
Pasosquehayqueseguiroqueesloquenecesitamos,1formulariojsp,2una
configuracinenelarchivostrutsconfig.xmly3unaclaseDynaActionForm.java
1Elformularioescomosiempreunapginawebconlasetiquetasstruts
2Laconfiguracindelarchivostrutsconfig.xmlconstadedospasos
2.1LaconfiguracindelBeandinmico
aquiseindicalaspropiedadesquevaatenerestenuevobean
2.2LaconfiguacindellaclaseActionresponsabledetratarelformulario
SeestablecelarelacinconelbeandynaActionFormylaclasequetrataloscamposdel
formulariioylosreenviosalaspginasjspsegunsehayanintroducidolosdatosbieno
no.
FICHEROFORMULARIODINAMICO.JSPPARA(PARACREARLOVIENEENPOSTDE
LOGINSTRUTSANTERIOR)
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
3 "http://www.w3.org/TR/html4/loose.dtd">
4 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
5 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9 <title><bean:messagekey="titulo.dinamico"/></title>
10 <html:base/>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14 <divid="contenedor">
15 <h2><bean:messagekey="titulo.dinamico"/></h2>
16
17 <divid="errores">
18 <html:errors/>
19 </div>
20 <divid="imagen">
21 <html:imgsrcKey="dinamico.registro.imagen"titleKey="dinamico.registro.imagen.alt"/>
22 </div>
23
24 <divid="contenido">
25 <html:formaction="dinamicoAction"focus="nombre"styleId="formulario"method="post">
26 <divclass="campo">
27 <bean:messagekey="login.nombre"/>
28 <html:textproperty="nombre"/>
29 </div>
30 <divclass="campo">
31 <bean:messagekey="login.domicilio"/>
32 <html:textproperty="domicilio"/>
33 </div>
34

http://www.railsymas.com

33

TUTORIALFRAMEWORKSTRUTS

35 <divclass="campo">
36 <bean:messagekey="login.edad"/>
37 <html:passwordproperty="edad"maxlength="3"size="3"/>
38 </div>
39 <html:submitstyleClass="boton"value="enviar"/>
40 <html:cancelstyleClass="boton"value="cancelar"/>
41 </html:form>
42 </div>
43 <divid="pie">
44 <p>www.railsymas.com</p>
45 </div>
46 </div>
47
48 </body>
</html:html>

CLASEACTIONDENTRODELPACKAGEACCIONESACCIONDINAMICA.JAVA

Siloscamposestnvacossemapealahacacanceladaysiestncompletoshaciala
1 packageacciones;
2
3 importorg.apache.struts.action.Action;
4 importjavax.servlet.http.HttpServletRequest;
5 importjavax.servlet.http.HttpServletResponse;
6 importorg.apache.struts.action.ActionForward;
7 importorg.apache.struts.action.ActionMapping;
8 importorg.apache.struts.action.ActionForm;
9 importorg.apache.struts.action.DynaActionForm;
10 importorg.apache.struts.action.ActionErrors;
11 importorg.apache.struts.action.ActionMessage;
12
13 publicclassAccionDinamicaextendsAction{
14
15
publicActionForwardexecute(ActionMappingmapping,ActionFormform
16
17 ,HttpServletRequestrequest,HttpServletResponseresponse)throwsException
{
18

//creamosunobjetodynamicactionform
19

DynaActionFormformularioDinamico=(DynaActionForm)form;
20
21

ActionForwardreenvio=null;
22
23
24

ActionErrorsmensajes=newActionErrors();
25
26

if(((String)formularioDinamico.get("nombre")).equals(""))
27

{
28

mensajes.add("nombre",new
29
30 ActionMessage("error.login.nombre"));
31

}
32
33

if(((String)formularioDinamico.get("domicilio")).equals(""))
34

{
35

http://www.railsymas.com

34

TUTORIALFRAMEWORKSTRUTS

36

mensajes.add("domicio",new
37 ActionMessage("error.login.domicilio"));
38

}
39
40

//preguntamossihayerroresparahacerelreenvioalapagina
41
42

if(mensajes.isEmpty())

{
43

reenvio=mapping.findForward("datospersonales");
44

}
45

else
46

{
47

reenvio=mapping.findForward("cancelada");
48
49

}
50
51

System.out.print(reenvio.getPath());
52
53

returnreenvio;

54
55
56

VENTANACANCELADA2

PGINAJSPCANCELADA2.JSP

Pginaquemuestraelmensajedequelaaccinhasidocancelada
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>

http://www.railsymas.com

35

TUTORIALFRAMEWORKSTRUTS

2 <%@tagliburi="http://struts.apache.org/tagsbean" prefix="bean" %>


3 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9
10 <title><bean:messagekey="cancelada.titulo"/></title>
11 <html:base/>
12
13 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
14 </head>
15 <body>
16
17 <divid="contenedor">
18
19 <h2><bean:messagekey="cancelada.login"/></h2>
20 <divid="imagen">
21 <html:imgsrcKey="cancelada.imagen"titleKey="cancelada.imagen.alt"/>
22 </div>
23 <divid="mensaje">
24 <bean:messagekey="cancelada.mensaje"/>
25 <divclass="campo">
26 <html:linkpage="/pages/login.jsp">Volveralformulariologin
27 </html:link>
28 </div>
29 </div>
30 <divid="pie">
31 <p>www.railsymas.com</p>
32 </div>
33
34 </div>
35
36 </body>
</html:html>

PGINADATOSPERSONALES.JSP

Estapginarecuperalosdatosintroducidosporelusuariomediantelaetiqueta
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9 <title><bean:messagekey="titulo.dinamico"/></title>
10 <html:base/>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14 <divid="contenedor">

http://www.railsymas.com

36

TUTORIALFRAMEWORKSTRUTS

15 <h2>Bienvenido<bean:writename="dinamicoFormulario" property="nombre"/></h2>
16 <divid="imagen">
17 <html:imgsrcKey="dinamico.imagen"titleKey="dinamico.imagen.alt"/>
18 </div>
19 <divid="mensaje">
20 <bean:messagekey="dinamico.mensaje"/>
21
22 <divclass="campo">
23 <bean:writename="dinamicoFormulario"property="nombre"/>
24 </div>
25 <divclass="campo">
26 <bean:writename="dinamicoFormulario"property="domicilio"/>
27 </div>
28 <divclass="campo">
29 <bean:writename="dinamicoFormulario"property="edad"/>
30 </div>
31 </div>
32
33 <divid="pie">
34 www.railsymas.com
35 </div>
36 </div>
37
38 </body>
</html:html>

Declaracindelformulariodinmicoenelficherodeconfiguracinstrutsconfig.xml
Enladefinicindelformbeanvemoscomoadiferenciadelejemplodellogincuando
tenamosunformbeanyhacamosunareferenciamedianteelatributotypeauna
clasedenuestroproyectoahoralohacemosaunaclasedestruts
org.apache.struts.action.DynaActionForm.Despusdeclaramoslaspropiedadesdel
beanmediantesutipoysiqueremosunvalorinicialseponeelatributoinitialconun
valor
Enelejemplosedanlosvaloraloscamposnombre=usuarioPepedomicilio=
domicilioPepeysedejasintocarlaedadperocomoestabainicializadaa18salepor
pantalla.Ademsenlaclaseactionnosemirasiestavacaonoyaquepordefecto
tieneelvalor18
1 <!================================================FormBeanDefinitions>
2 <formbean
3 name="dinamicoFormulario"
4 type="org.apache.struts.action.DynaActionForm">
5 <formpropertyname="nombre"type="java.lang.String"/>
6 <formpropertyname="domicilio"type="java.lang.String"/>
7 <formpropertyname="edad"type="java.lang.Integer"initial="18"/>
8 </formbean>

Declaracindelreenvoglobal

http://www.railsymas.com

37

TUTORIALFRAMEWORKSTRUTS

Comofuncionalaaplicacinbienhayunindex.jsppordefectoenelproyectoestoya
vieneasiconfiguradoenelarchivoweb.xml,ficherodedespliegue.Segenera
entonceslaaccinWelcome.doenelreenvoglobal,
1 <!===========================================GlobalForwardDefinitions>
2
3 <globalforwards>
4 <!Defaultforwardto"Welcome"action>
5 <!Demonstratesusingindex.jsptoforward>
6 <forward
7 name="welcome"
8 path="/Welcome.do"/>
9 </globalforwards>

EnlasdefinicionesdelasaccionesenActionMapping,laaccinwelcomerecogidopor
elatributopathesmapeadaalarchivojspformularioDinmico.jspporloqueesla
primerapginaquesalepordefecto.
Cuandoelusuariorellenaloscamposypulsasobrelosbotonesdelformulariose
procesalaacciondinamicoActionqueseestableceenelficherostrutsconfig.xmlpor
elatributopathysemapeaenelproyectoporlaclasejava
acciones.AccionDinmica.
Sesueleponerunpackagesiempreparalasclasesaccionesyotroparalasclasesbean
peroesgustodelconsumidorhacerloono
CuandolaclaseAccionDinmicaprocesaloscamposdelformulariomandamediante
unobjetodelaclaseactionMappingencontrarlareferenciadeunobjetomapeadoen
elstrutsconfig.xmlmediantesiestanbienlosdatossemadaalapagina
datospersonales,jspporqueenlaclaseAccionDinmimatenamos
reenvio=mapping.findForward(datospersonales);ymedianteel
name=datospersonalesobtenimoslapginadatospersonales.jsp.
Delamismaformasiloscamposestanvacostenemoserroresymensajes.isEmpty()
nosdevuelvefalseporloquenosmandaalapginacancelada2.jsp
Unadiferenciadeesteejemploconeldelformulariodelogin,apartedequenos
evitamosunaclaseformbeanesquenonossalenloserroresenelformulariode
recogidadedatos,podramosresolverloconobjetosdelaclaseAcctionMessagespero
existeotravariantedelDynaActionFormquesipermitedeunaformasencillala
validacindeloscamposllamadaDynaActionFormValidatoryloveremosenotro
posts.
1
2
3
4
5
6
7

<!===========================================ActionMappingDefinitions>

<actionmappings>
<!Default"Welcome"action>
<!ForwardstoWelcome.jsp>
<!modificamoselforwardparaqueapuntealapaginadelogin.jsp>
<action

http://www.railsymas.com

38

TUTORIALFRAMEWORKSTRUTS

8 path="/Welcome"
9 forward="/pages/formulariodinamico.jsp"/>
10
11 <action
12 path="/dinamicoAction"
13 type="acciones.AccionDinamica"
14 scope="request"
15 name="dinamicoFormulario"
16 input="/pages/formulariodinamico.jsp">
17 <setpropertyproperty="cancellable"value="true"/>
18
19 <forwardname="cancelada"path="/pages/cancelada2.jsp"/>
20 <forwardname="datospersonales"path="/pages/datospersonales.jsp"/>
21
22 </action>

clavesparaelarchivodepropropiedades.propertiescomosiempreelformatoes
clave=valor
1
2 #clavesparadinamico
3 dinamico.mensaje=Tehasregistradocorrectamente
4 dinamico.imagen=../imagenes/base.jpg
5 dinamico.imagen.alt=imageniconoregistro
6 dinamico.registro.imagen=../imagenes/usuario2.png
7 dinamico.registro.imagen.alt=iconousuario
8 titulo.dinamico=Registrodin&aacute;mico

http://www.railsymas.com

39

TUTORIALFRAMEWORKSTRUTS

STRUTSFORMULARIODYNAVALIDATORFORMECLIPSE

Enelanteriorpostparalacategoradestrutshabamosvistolosformulariosdinmicos
destruts,comorepasodecamosqueeliminabanlacreacindedelaclasedetipo
actionFormmediantelaconfiguracindelformbeanenelficherostrutsconfig.xml.
LoqueocurriaconlaclaseDynaActionFormeraqueaunquetenamoselcdigoparala
validacindeloscamposenlaclasenofuncionabaperoquesepodanimprimirlos
mensajesydevolverlosmedianteelobjetorequestdepeticin.
Lavalidacintambinseraposiblemediantejavascriptcomootroslenguajespero
strutsdisponedeunaclasequefacilitatodoesto,estaclasesellama
DynaValidatorFormypermitelavalidacindeloscamposdeunformulariodinmico.
EnlosejemplosanterioresredirigamoslaaccionWelcome.doalaspginas
correspondientesdecadaejemploconlocualperdamosenelproyectolaposibilidad
deinteractuarconlosanterioresejemplos,paraquenoocurraesosepuedecrearuna
pginaslodeenlaces,alosdiferentesejerciciosamododemen.
1 <globalforwards>
2 <!Defaultforwardto"Welcome"action>
3 <!Demonstratesusingindex.jsptoforward>
4 <forward
5 name="welcome"
6 path="/Welcome.do"/>
7 </globalforwards>
8
9
10 <!===========================================ActionMappingDefinitions>
11
12 <actionmappings>
13 <!Default"Welcome"action>
14 <!ForwardstoWelcome.jsp>
15 <!modificamoselforwardparaqueapuntealapaginadelogin.jsp>
16 <action
17 path="/Welcome"
18 forward="/pages/ejercicios.jsp"/>

loqueestamoshaciendoesredirigirelWelcome.doalapginaejercicios.jspqueest
enlacarpetapages

http://www.railsymas.com

40

TUTORIALFRAMEWORKSTRUTS

paralacssestilo.cssaadido

.enlace{height:40px;}

CDIGODELAPGINAEJERCICIOS.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
3 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9 <title>Ejercicios</title>
10 <html:base/>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14
15 <divid="contenedor">
16
17 <h2><bean:messagekey="ejercicios"/></h2>
18
19 <divclass="enlace">
20 <html:linkpage="/pages/login.jsp">1)formulariologinActionFom</html:link>
21 </div>
22
23 <divclass="enlace">
24 <html:linkpage="/pages/formulariodinamico.jsp">2)formulariodin&aacute;mico</html:link>
25 </div>
26
27 <divclass="enlace">

http://www.railsymas.com

41

TUTORIALFRAMEWORKSTRUTS

28 <html:linkpage="/pages/formdinavalidacion.jsp"> 3) formulariodin&aacute;mico
29 validaci&oacute;n</html:link>
30 </div>
31
32 <divid="pie">
33 <p>www.railsymas.com</p>
34 </div>
35
36 </div>
</body>
</html:html>

Cofiguracinenelstrutsconfig.xmldelbeandynavalidatorformtenemoselnombre
delbeanenelatributonameyenelatributotypelaclasealaquepertenece,despus
tenemoslosmismoscamposqueenelformulariodynaactionform,nombre,domicilio
yedadinicializadoa18
1 <formbeanname="dinamicoValidacion" type="org.apache.struts.validator.DynaValidatorForm">
2
3 <formpropertyname="nombre"type="java.lang.String"/>
4 <formpropertyname="domicilio"type="java.lang.String"/>
5 <formpropertyname="edad"type="java.lang.Integer"initial="18"/>
6 </formbean>

Sinosfijamosenelficherodeconfiguracinstrutsconfig.xmlvienelosiguiente
descomentadoyaenelproyectoenblancostrutsblank.xmldelquepartimos
1 <pluginclassName="org.apache.struts.validator.ValidatorPlugIn">
2 <setpropertyproperty="pathnames"value="/org/apache/struts/validator/validatorrules.xml,
3 /WEBINF/validation.xml"/>
4 </plugin>

Strutsutilizadosficherosxmldeconfiguracinunoquevamosaintroducirdatos
validation.xmlyelotrolodejaremoscomoestycomentaremosmsadelante
validatorrules.xmldondetenemoslaconfiguracintiposdecampos(enterorealetc)
presenciaonodeuncampotodoyaproporcionadoporelframeworkstruts.Estosdos
ficherosestanenlacarpetawebinfdelproyecto.
Dentrodelficherovalidation.xmlintroducimoslosiguiente:
1 <formset>
2
3 <formname="dinamicoValidacion">
4 <field
5 property="nombre"
6 depends="required">
7 <argkey="campo.nombre"/>
8 </field>
9
10 <field
11 property="domicilio"
12 depends="required">

http://www.railsymas.com

42

TUTORIALFRAMEWORKSTRUTS

13 <argkey="campo.domicilio"/>
14 </field>
15
16 </form>
17 </formset>

Comoyavenaesteficheroconbloquesdeclaradosnosfijamosquetienelasiguiente
estructuraydentrosedeclaraelformularioconsuscampos.Elnamedelformtiene
queserelmismodelnombrequeeldeclaradoenlaseccinformbeanparael
formulariodevalidacindinmica.Solamenteparalosdoscamposdelformulario
nombreydomiciliosepidequeseanrellenadosparaelloponemos
depends=requiredestofuncionayaqueelficherovalidatorrules.xmllotieneas
establecido.
CDIGODELAPGINAFORMDINAVALIDACION.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
3 "http://www.w3.org/TR/html4/loose.dtd">
4 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
5 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9 <title><bean:messagekey="titulo.dinamico"/></title>
10 <html:base/>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14 <divid="contenedor">
15 <h2><bean:messagekey="titulo.dinamicoValidacion"/></h2>
16
17 <divid="errores">
18 <html:errors/>
19 </div>
20 <divid="imagen">
21 <html:imgsrcKey="dinamicoValidacion.registro.imagen"
22 titleKey="dinamicoValidacion.registro.imagen.alt"/>
23 </div>
24
25 <divid="contenido">
26 <html:formaction="dinamicoValidacion"focus="nombre"styleId="formulario"method="post">
27 <divclass="campo">
28 <bean:messagekey="login.nombre"/>
29 <html:textproperty="nombre"/>
30 </div>
31 <divclass="campo">
32 <bean:messagekey="login.domicilio"/>
33 <html:textproperty="domicilio"/>
34 </div>
35
36 <divclass="campo">
37 <bean:messagekey="login.edad"/>
38 <html:passwordproperty="edad"maxlength="3"size="3"/>
39 </div>

http://www.railsymas.com

43

TUTORIALFRAMEWORKSTRUTS

40 <html:submitstyleClass="boton"value="enviar"/>
41 <html:cancelstyleClass="boton"value="cancelar"/>
42 </html:form>
43 </div>
44 <divid="pie">
45 <p>www.railsymas.com</p>
46 </div>
47 </div>
48
</body>
</html:html>

IMAGENDELFORMULARIO

Sepuedevercomoalenviarelformularioyavalidalapresenciadeloscamposeneste
casoseenvivacoynosmuestraelavisodelosdoscampos
Cdigodelformulariodecancelacineselmismocdigoqueenelformulario
DynaActionFormyaquenoesnecesariotocarloperosevuelveaincluiraquparaeste
ejemplocdigodecancelada2.jsp
1
2
3
4
5
6
7

<%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
<%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
<%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
<!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html:html>
<head>

http://www.railsymas.com

44

TUTORIALFRAMEWORKSTRUTS

8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9
10
11 <title><bean:messagekey="cancelada.titulo"/></title>
12 <html:base/>
13
14 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
15 </head>
16 <body>
17
18 <divid="contenedor">
19
20 <h2><bean:messagekey="cancelada.login"/></h2>
21 <divid="imagen">
22 <html:imgsrcKey="cancelada.imagen"titleKey="cancelada.imagen.alt"/>
23 </div>
24 <divid="mensaje">
25 <bean:messagekey="cancelada.mensaje"/>
26 <divclass="campo">
27 <html:linkpage="/pages/ejercicios.jsp">Volveralmen&uacute;deejercicios
28 </html:link>
29 </div>
30 </div>
31 <divid="pie">
32 <p>www.railsymas.com</p>
33 </div>
34
35 </div>
36
37 </body>
</html:html>

CDIGOFUENTEDELAPGINAPERSONALESDATOSPERSONALES2.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9 <title><bean:messagekey="titulo.dinamicoValidacion"/></title>
10 <html:base/>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14 <divid="contenedor">
15 <h2>Bienvenido<bean:writename="dinamicoValidacion"property="nombre"/></h2>
16
17 <divid="imagen">
18 <html:imgsrcKey="dinamicoValidacion.imagen"titleKey="dinamicoValidacion.imagen.alt"/>
19 </div>
20 <divid="mensaje">
21 <bean:messagekey="dinamicoValidacion.mensaje"/>
22
23 <divclass="campo">

http://www.railsymas.com

45

TUTORIALFRAMEWORKSTRUTS

24 <bean:writename="dinamicoValidacion" property="nombre"/>
25 </div>
26 <divclass="campo">
27 <bean:writename="dinamicoValidacion"property="domicilio"/>
28 </div>
29 <divclass="campo">
30 <bean:writename="dinamicoValidacion"property="edad"/>
31 </div>
32 </div>
33 <divid="pie">
34 <p>www.railsymas.com</p>
35 </div>
36
37 </div>
38 </body>
</html:html>

Elformulariosehaenviadocorrectamenteysemuestranlosdatos
pasandonombre:manolodomicilio:casademanoloedad59

COFIGURACINDELACTIONENELFICHEROSTRUTSCONFIG.XML
1
2
3
4
5
6
7
8

<action
path="/dinamicoValidacion"
type="acciones.AccionDinamicaValidacion"
scope="request"
name="dinamicoValidacion"
validate="true"
input="/pages/formdinavalidacion.jsp"
>

http://www.railsymas.com

46

TUTORIALFRAMEWORKSTRUTS

9
10 <setpropertyproperty="cancellable"value="true"/>
11
12 <forwardname="cancelada"path="/pages/cancelada2.jsp"/>
13 <forwardname="datospersonales"path="/pages/datospersonales2.jsp"/>
14
15 </action>

CLASEACTIONENELPACKAGEDEACCIONES
packageacciones;
1

2
importorg.apache.struts.action.Action;
3
importorg.apache.struts.action.ActionErrors;
4
importorg.apache.struts.action.ActionMapping;
5
importjavax.servlet.http.HttpServletRequest;
6
importjavax.servlet.http.HttpServletResponse;
7
importorg.apache.struts.action.ActionForward;
8
importorg.apache.struts.action.ActionForm;
9
importorg.apache.struts.validator.DynaValidatorForm;
10

11

12
publicclassAccionDinamicaValidacionextendsAction{
13

14

15

publicActionForwardexecute(ActionMappingmapping,ActionFormform,
16
HttpServletRequestrequest,HttpServletResponseresponse)throwsException
17

{
18

19

DynaValidatorFormformularioValidacion=(DynaValidatorForm)form;
20

21

ActionForwardreenvio=null;
22

23

if(isCancelled(request)){
24

//log.debug("Sehapulsadoelbotoncancel");
25

returnmapping.findForward("cancelada");
26

}
27

28

29

reenvio=mapping.findForward("datospersonales");
30

31

returnreenvio;
32

33

}
34
}

CDIGODEMESSAGERESOURCES_ES_ES.PROPERTIES
1
2
3
4
5
6
7
8
9

#titulopginaejercicios
ejercicios=Ejercicios

#clavesparalapginadeformulario
titulo.dinamicoValidacion=formulariodin&aacute;micoValidaci&oacute;n
dinamicoValidacion.imagen=../imagenes/iconovalidacion.png
dinamicoValidacion.imagen.alt=iconovalidaci&oaccuten
dinamicoValidacion.mensaje=Tehasregistradocorrectamente

http://www.railsymas.com

47

TUTORIALFRAMEWORKSTRUTS

10 dinamicoValidacion.registro.imagen= ../imagenes/usuario2.png
11 dinamicoValidacion.registro.imagen.alt=iconousuario
12
13
14 campo.nombre=elnombre
15 campo.domicilio=eldomicilio
16
17 errors.required={0}esrequerido.

Vemoscomoenelficherodepropiedadespares,clavevalorpropertiesviene
error.requireddonde{0}sesustituyeporelvalorcampodomiciliosegunelfichero
validation.xmlenparaelcasodedomiciliolomismoocurreconelnombre.

http://www.railsymas.com

48

TUTORIALFRAMEWORKSTRUTS

STRUTSDISPATCHACTIONECLIPSE

DispatchAction,laclaseDispatchActionpermitemltiplesoperacionesenunasola
clase,laideaesnotenerquehacerparacadaaccinunaclaseactiondistintaque
proceseunapeticinconcreta.
Sitenemosenunformularioporejemploconaccesoaunabasededatosdelibros,
puedequetengamosdiversosbotonesenesavista,parapoderaccederallistadoo
bienaccederaotromendondepodemoseditardeterminadoscamposdelregistroo
calcularelvolumendeventas.Siutilizamoslaclaseactiontendramosquehacerque
cadaunadeesasaccionesdelavistafueseaunaclasedistintaquelaprocesase.
ParalautilizacindelaclaseDispatchAction,necesitamoscrearunaclasequeampliey
aadaunmtodoparacadafuncinquesenecesite.
Habamosvistoloslinksenstrutsconelatributopagesapuntandohaciaunapginajsp
enlapginadeejerciciosincluimosunnuevoenlacehaciaelformulariopara
dispatchactionperoenestecasoutilizamoselatributoactiondelaetiqueta
hml:link.Estopermitehacerunenlacealaaccionqueasuvezserreenviadaauna
pginajsp.
CDIGOPARALACONFIGURACINDELARCHIVOSTRUTSCONFIG.XML
1 <action
2 path="/dispatchAccion"
3 forward="/pages/formulariodispatch.jsp"/>

CDIGOQUEAADIMOSALARCHIVOEJERCICIOS.JSP
1
2 <divclass="enlace">
3 <html:linkaction="/dinamicolibro">4)formulariodispatchAction</html:link>
4 </div>

ImagenparaEjercicios.jsp

http://www.railsymas.com

49

TUTORIALFRAMEWORKSTRUTS

DECLARACINDELFORMULARIODINMICOENELFICHEROSTRUTSCONFIG.XML
1
2 <!================================FormBeanDefinitions>
3
4
5 <formbeanname="dinamicolibro"type="org.apache.struts.validator.DynaValidatorForm">
6
7 <formpropertyname="titulo"type="java.lang.String"/>
8 <formpropertyname="autor"type="java.lang.String"/>
9 <formpropertyname="cambio"type="java.lang.String"/>
10
11 </formbean>

Elbeandinmicotienedospropiedadestituloyautorquesecompruebanqueexistan
Configuracindelactionparaelficheroderecogidadedatosdellibroelaction
dinamicolibro
elnombredelaaccionvienedeterminadaporelatributopathdinamicolibrolaclase
deaccionvienedeterminadaporelatributotypeelatributoscopedeterminael
mbitoenestecasodepeticinelatributonamehacereferenciaalnombredelbean
alqueestaasociadalaaccinelatributovalidateatrueindicaquesevaaestablecer
unavalidacindeloscamposdelformulariodinmicoelatributoinputindicacualesel
formulariodeentradaparadesarrollarlaaccinyencasodevalidacincualeslajsp
quesemuestra.Losforwardspararealizarlosreenvoscorrespondientes
1 <action
2 path="/dispatchAccion"
3 forward="/pages/formulariodispatch.jsp"/>
4
5 <action
6 path="/dinamicolibro"
7 type="acciones.AccionDispatch"
8 scope="request"
9 name="dinamicolibro"
10 validate="true"
11 input="/pages/formulariodispatch.jsp"
12 parameter="method">
13
14 <setpropertyproperty="cancellable"value="true"/>
15
16 <forwardname="cancelada"path="/pages/cancelada2.jsp"/>
17 <forwardname="editarlibros"path="/pages/edicion.jsp"/>
18 </action>

CONFIGURACINDELACTIONENELSTRUTSCONFIG.XMLACTION
DINAMICOLIBRO2
1
2
3
4
5

<action

path="/dinamicolibro2"
type="acciones.AccionDispatch"
scope="request"

http://www.railsymas.com

50

TUTORIALFRAMEWORKSTRUTS

6 name="dinamicolibro"
7 validate="false"
8 parameter="method">
9
10 <setpropertyproperty="cancellable"value="true"/>
11 <forwardname="cancelada"path="/pages/cancelada2.jsp"/>
12 <forwardname="datoslibro"path="/pages/datoslibros.jsp"/>
13 </action>

Comoestamoshaciendounformulariodinmicoyloqueremosvalidar,tenemosque
crearlassiguientesreglasenelficherovalidation.xml
1 <formset>
2 <formname="dinamicolibro">
3 <field
4 property="titulo"
5 depends="required">
6
7 <argkey="libro.titulo"/>
8 </field>
9
10 <field
11 property="autor"
12 depends="required">
13 <argkey="libro.autor"/>
14 </field>
15 </form>
16
17 </formset>

elnombredelformularioenformname=dinamicolibroeselmismoqueelnamede
laconfiguracindelbeandeclaradoenelstrutsconfig.xml
Imagendelficheroformulariodispatch.jsp,alaintroduccindedatosdellibro

http://www.railsymas.com

51

TUTORIALFRAMEWORKSTRUTS

Imagendelficheroformulariodispatch.jsp

Imagenresultadodelenvodelosdatos

http://www.railsymas.com

52

TUTORIALFRAMEWORKSTRUTS

Introducimostitulo2enelcampodetitulo

resultadofinal

http://www.railsymas.com

53

TUTORIALFRAMEWORKSTRUTS

importorg.apache.struts.actions.DispatchAction;
CdigodelficheroactiondelaclasedispatchActionimportamosimport
org.apache.struts.actions.DispatchAction,esalneadecdigosolamenteconel
proyectodestrutsparalaversin1.3.10queesconlaqueseestanhaciendotodoslos
ejemplosdaerroryaqueelproyectoenblanconolareconoce.Parasolventareste
problema,tenemosqueimportardeldirectoriodondedescomprimimoselproyecto
struts,elficherojarlstrutsextras1.3.10.jardentrodelficherolibdelproyectoweb
eclipse.
lib/strutsextras1.3.10.jar,
1 packageacciones;
2
3 importorg.apache.struts.action.ActionForm;
4 importorg.apache.struts.action.ActionMapping;
5 importorg.apache.struts.action.ActionForward;
6 importorg.apache.struts.actions.DispatchAction;
7 importorg.apache.struts.validator.DynaValidatorForm;
8 importjavax.servlet.http.HttpServletRequest;
9 importjavax.servlet.http.HttpServletResponse;
10
11
12
13 publicclassAccionDispatchextendsDispatchAction{
14
15
privateActionForwardenvio;
16
privateDynaValidatorFormformulario;
17
privateStringtitulo;
18
privateStringautor;
19
20
21
//creamoslosmtodosquerespondenalasacciones
22
publicActionForwardcrear(ActionMappingmapping,ActionFormform,
23

http://www.railsymas.com

54

TUTORIALFRAMEWORKSTRUTS

24 HttpServletRequestrequest,HttpServletResponseresponse) throws Exception


25
{
26
27

//sihemoscanceladolaejecucinmandamosaljspdecancelacin
28

if(isCancelled(request))
29

{
30

envio=mapping.findForward("cancelada");
31

}
32

else
33

{
34

//recuperamoslosdatosdelformulariobeandinmicoValidator

formulario=(DynaValidatorForm)form;
35
36

titulo=formulario.getString("titulo");
37

autor=formulario.getString("autor");
38
39

System.out.println(titulo);
40
41

envio=mapping.findForward("editarlibros");
42

}
43
44

returnenvio;
45
46
}
47
48
publicActionForwardEditarTitulo(ActionMappingmapping,ActionFormform,
49
50 HttpServletRequestresquest,HttpServletResponseresponse)throwsException
{
51
52

//recuperamoslosdatosdelformulariobeandinmicoValidator
53
formulario=(DynaValidatorForm)form;
54
55
Stringcadena="Sehacambiado"+this.titulo+"por"+formulario.getString("titulo");
56
57
formulario.set("cambio",cadena);
58
59
//recargamoselformularioconelvalorguardado
60
formulario.set("autor",this.autor);
61
62
63

envio=mapping.findForward("datoslibro");
64
65

returnenvio;
66
}
67
68
publicActionForwardEditarAutor(ActionMappingmapping,ActionFormform,
69
70 HttpServletRequestrequest,HttpServletResponseresponse)throwsException
71
{
72

//recuperamoslosdatosdelformulariobeandinmicoValidator
73
74

//recuperamoslosdatosdelformulariobeandinmicoValidator
formulario=(DynaValidatorForm)form;
75
76
Stringcadena="Sehacambiado"+this.autor+"por"+formulario.getString("autor");
77
78
79

http://www.railsymas.com

55

TUTORIALFRAMEWORKSTRUTS

80
81
82
83
84
85
86
87
88
89
90
91
}

formulario.set("cambio",cadena);
//recargamoselformularioconel
formulario.set("titulo",this.titulo);

envio=mapping.findForward("datoslibro");

returnenvio;
}

CDIGOFUENTEDELFICHERODELFICHEROFORMULARIODISPATCH.JSP
1
2 <%@pagelanguage="java"contentType="text/html;charset=UTF8"pageEncoding="UTF8"%>
3 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
4 "http://www.w3.org/TR/html4/loose.dtd">
5 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
6 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
7 <html:html>
8 <head>
9 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
10 <title><bean:messagekey="titulo.libro"/></title>
11 <html:base/>
12 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
13 </head>
14 <body>
15 <divid="contenedor">
16 <h2><bean:messagekey="titulo.libro"/></h2>
17
18 <divid="errores">
19 <html:errors/>
20 </div>
21 <divid="imagen">
22 <html:imgsrcKey="libro.imagen"titleKey="libro.imagen.alt"/>
23 </div>
24
25 <divid="contenido">
26 <html:formaction="dinamicolibro"focus="nombre"styleId="formulario"method="post">
27 <divclass="campo">
28 <bean:messagekey="libro.titulo"/>
29 <html:textproperty="titulo"/>
30 </div>
31
32 <divclass="campo">
33 <bean:messagekey="libro.autor"/>
34 <html:textproperty="autor"/>
35 </div>
36
37 <html:hiddenproperty="method"value="crear"/>
38
39 <html:submitstyleClass="boton"value="enviar"/>
40 <html:cancelstyleClass="boton"value="cancelar"/>
41 <html:resetstyleClass="boton"value="borrar"/>

http://www.railsymas.com

56

TUTORIALFRAMEWORKSTRUTS

42 </html:form>
43 </div>
44 <divid="pie">
45 <p>www.railsymas.com</p>
46 </div>
47 </div>
48
49 </body>
</html:html>

CDIGOFUENTEDELFICHEROEDICION.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9 <title><bean:messagekey="editar.titular"/></title>
10 <html:base/>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14 <divid="contenedor">
15 <h2><bean:messagekey="editar.titular"/></h2>
16
17 <divid="imagen">
18 <html:imgsrcKey="editar.imagen"titleKey="editar.imagen.alt"/>
19 </div>
20
21 <divid="mensaje">
22 <bean:messagekey="editar.mensaje"/>
23
24 <html:formaction="dinamicolibro2"styleClass="formulario"method="post">
25 <divclass="campo">
26 <bean:messagekey="editar.valor"/>
27 <br/>
28 <bean:writename="dinamicolibro"property="titulo"/>
29 </div>
30 <html:textproperty="titulo"/>
31
32 <html:hiddenproperty="method"value="EditarTitulo"/>
33 <html:submitstyleClass="boton"value="editar"/>
34
35 </html:form>
36
37 <html:formaction="dinamicolibro2"styleClass="formulario"method="post">
38 <divclass="campo"class="flotaizquierda">
39
40 <bean:messagekey="editar.valor"/>
41 <br/>
42 <bean:writename="dinamicolibro"property="autor"/>
43 </div>
44
45 <html:textproperty="autor"/>

http://www.railsymas.com

57

TUTORIALFRAMEWORKSTRUTS

46
47 <html:hiddenproperty="method"value="EditarAutor"/>
48
49 <html:submitstyleClass="boton"value="editar"/>
50
51 </html:form>
52 </div>
53
54 <divid="pie">
55 <p>www.railsymas.com</p>
56 </div>
57
58 </div>
59 </body>
</html:html>

CDIGOFUENTEDELFICHERODATOSLIBROS.JSP
<%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
1
<%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
2
<%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
3
<!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
4
"http://www.w3.org/TR/html4/loose.dtd">
5
<html:html>
6
<head>
7
<metahttpequiv="ContentType"content="text/html;charset=UTF8">
8
<title><bean:messagekey="resultado.mensaje"/></title>
9
<html:base/>
10
<linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
11
</head>
12
<body>
13
<divid="contenedor">
14
<h2><bean:messagekey="resultado.mensaje"/></h2>
15

16
<divid="imagen">
17
<html:imgsrcKey="resultado.imagen"titleKey="resultado.imagen.alt"/>
18
</div>
19
<divid="mensaje">
20
<bean:messagekey="resultado.mensaje"/>
21

22
<divclass="campo">
23
<bean:writename="dinamicolibro"property="titulo"/>
24
</div>
25
<divclass="campo">
26
<bean:writename="dinamicolibro"property="autor"/>
27
</div>
28
<divclass="campo">
29
<bean:writename="dinamicolibro"property="cambio"/>
30
</div>
31
</div>
32
<divid="pie">
33
<p>www.railsymas.com</p>
34
</div>
35

36
</div>
37
</body>
38
</html:html>

http://www.railsymas.com

58

TUTORIALFRAMEWORKSTRUTS

IBATISPROYECTOWEBECLIPSE

Loprimero,comobiendicelawikipediaibatisesunmarcodetrabajodesarrolladopor
apachequeseocupadelacapadepersistencia,situndoseentrelacapadenegocioy
labasededatos.Ibatisestadisponibleparajava.netyrubyonrails.
Ibatiscumpleunafuncinsimilaraladehibernate,algunosdesarrolladoresconsideran
aibatisunaalternativaporsusencillezypornopresentarunlenguajeespecficopara
consultas.
Enlapginawebdelproyectoibatisenlaceproyectoibatis

Recordarqueesteejemploestarealizadoenlinuxubuntuperoqueestotalmente
compatibleconwindows.
Descargarlaversin2.3.0olaversin2.3.4conlasquesehaprobadoelejemplo,una
vezdescargadoydesempaquetadoelproyectodentrodelacarpetalibtenemosun
fichero.jarconlaversincorrespondiente.Eseficherodebemosdelimportarloel
directoriolibdenuestroproyectowebdinmicodeeclipse.
Partimosdelasituacindelejemplojdbceclipse,noshabamosdescargadomysql,yel
jardriverparajdbccreandolabasededatoslibros_jdbc,conunatablallamadalibros.
Eneseejemplocreabamosunservletquepormtodogetmostrabaunformulario
paraenviardespuslosdatospormtodopost,insertarlosdatosymostrarunlistado
deloalmacenadoenlatabla.
EnlacealejemploanteriorConexinabasesdedatosj2eejdbceclipse
CLASEBEANLIBRO.JAVA
1
2
3
4
5
6

packageconexion;

publicclassLibro{

privateintid_libro;

privateStringtitulo_libro;

http://www.railsymas.com

59

TUTORIALFRAMEWORKSTRUTS

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 }

privateStringautor_libro;
privateStringtematica_libro;
publicintgetId_libro(){

returnid_libro;
}
publicvoidsetId_libro(intid_libro){

this.id_libro=id_libro;
}
publicStringgetTitulo_libro(){

returntitulo_libro;
}
publicvoidsetTitulo_libro(Stringtitulo_libro){

this.titulo_libro=titulo_libro;
}
publicStringgetAutor_libro(){

returnautor_libro;
}
publicvoidsetAutor_libro(Stringautor_libro){

this.autor_libro=autor_libro;
}
publicStringgetTematica_libro(){

returntematica_libro;
}
publicvoidsetTematica_libro(Stringtematica_libro){

this.tematica_libro=tematica_libro;
}

Ficherosdeconfiguracinparaibatissontresylospondremosenunpackage
ibatisMap

Elficherobasedatos.javaeselservletdelanteriorejemplojdbcelutilizadoparaibatis
esBaseDatosIbatis.java
Enelpropioproyectodeapacheibatistienentutorialesindicandolafuncionalidadde
cadaunodelosficherosnecesariosparaibatis

http://www.railsymas.com

60

TUTORIALFRAMEWORKSTRUTS

CreamosunficheroxmlparaelmapeodelbeanLibroLibro.xml,estefichero
contieneelconjuntodeconsultasquevanaserutilizadasparaelbeanasociadoala
tablalibros
<?xmlversion="1.0" encoding="UTF8"?>
1
<!DOCTYPEsqlMap
2
PUBLIC"//ibatis.apache.org//DTDSQLMap2.0//EN"
3
"http://ibatis.apache.org/dtd/sqlmap2.dtd">
4
<sqlMapnamespace="Libro">
5
<selectid="getLibro"parameterClass="int"resultClass="conexion.Libro">
6
SELECT
7
idasid_libro,
8
tituloastitulo_libro,
9
autorasautor_libro,
10
tematicaastematica_libro
11
FROMlibros
12
WHEREid=#value#
13

14
</select>
15

16
<insertid="introducirLibro"parameterClass="conexion.Libro">
17
INSERTINTOlibros(id,titulo,autor,tematica)VALUES
18
(#id_libro#,#titulo_libro#,#autor_libro#,#tematica_libro#)
19
</insert>
20

21
<selectid="getLibros"resultClass="conexion.Libro">
22
SELECT
23
idasid_libro,
24
tituloastitulo_libro,
25
autorasautor_libro,
26
tematicaastematica_libro
27
FROMlibros
28
</select>
29

30
</sqlMap>

ficherodepropiedadesparaelejemplo,sustituyealoquesehaciaenelanterior
ejemplojdbcalcargareldriver
1 driver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/libros_jdbc
3 username=root
4 password=root

FICHERODECONFIGURACINDESQLMAP
1
2
3
4
5
6
7
8
9

<?xmlversion="1.0" encoding="UTF8"?>
<!DOCTYPEsqlMapConfig
PUBLIC"//ibatis.apache.org//DTDSQLMapConfig2.0//EN"
"http://ibatis.apache.org/dtd/sqlmapconfig2.dtd">
<sqlMapConfig>

<propertiesresource="ibatisMap/sqlMapConfig.properties"/>
<settings
cacheModelsEnabled="true"

http://www.railsymas.com

61

TUTORIALFRAMEWORKSTRUTS

10 enhancementEnabled="true"
11 lazyLoadingEnabled="true"
12 maxRequests="32"
13 maxSessions="10"
14 maxTransactions="5"
15 useStatementNamespaces="false"
16 />
17
18
19 <transactionManagertype="JDBC">
20
21 <dataSourcetype="SIMPLE">
22 <propertyname="JDBC.Driver"value="${driver}"/>
23 <propertyname="JDBC.ConnectionURL"value="${url}"/>
24 <propertyname="JDBC.Username"value="${username}"/>
25 <propertyname="JDBC.Password"value="${password}"/>
26 </dataSource>
27 </transactionManager>
28
29 <sqlMapresource="ibatisMap/Libro.xml"/>
30 </sqlMapConfig>

Imagendelosjarsutilizados

CreamosunaclasedentrodelpackageconexionconelnombreBaseDatosIbatis.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

packageconexion;

importjava.io.IOException;
importjava.sql.SQLException;
importjava.io.Reader;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importcom.ibatis.sqlmap.client.SqlMapClient;
importcom.ibatis.sqlmap.client.SqlMapClientBuilder;
importcom.ibatis.common.resources.Resources;
importjava.io.PrintWriter;
importjava.util.List;
importjava.util.Iterator;

/**
*ServletimplementationclassforServlet:BaseDatosIbatis
*
*/
publicclassBaseDatosIbatisextendsjavax.servlet.http.HttpServletimplements
javax.servlet.Servlet{
staticfinallongserialVersionUID=1L;

http://www.railsymas.com

62

TUTORIALFRAMEWORKSTRUTS

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

privateSqlMapClientsqlMap=null;
/*(nonJavadoc)

*@seejavax.servlet.http.HttpServlet#HttpServlet()

*/

publicBaseDatosIbatis(){

super();

publicvoidinit()throwsServletException

super.init();

try

Stringrecursos="ibatisMap/SqlMapConfigLibro.xml";

Readerleer=Resources.getResourceAsReader(recursos);

sqlMap=SqlMapClientBuilder.buildSqlMapClient(leer);

catch(Exceptione)

System.out.print("errormapeo:"+e.getMessage());

/*(nonJavadoc)

*@seejavax.servlet.http.HttpServlet#doGet(HttpServletRequestrequest,
HttpServletResponseresponse)

*/

protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{

//TODOAutogeneratedmethodstub

//mostramosellistadoconelmtodoget

response.setContentType("text/html");

//preparamoselobjetodesalida

PrintWritersalida=response.getWriter();

//creamoslasalida

salida.print("<!DOCTYPEhtmlPUBLIC'//W3C//DTDHTML4.01
Transitional//EN''http://www.w3.org/TR/html4/loose.dtd'>\n");

salida.print("<html>\n");

salida.print("<head>\n");

salida.print("<linkrel='stylesheet'type='text/css'href='css/estilo.css'/>\n");

salida.print("</head>\n");

salida.print("<body>\n");

salida.print("<divid='contenedor'>\n");

salida.print("<h2>Librosjdbc</h2>");

salida.print("<divid='imagen'>");

http://www.railsymas.com

63

TUTORIALFRAMEWORKSTRUTS

79

salida.print("<imgsrc='imagenes/registro.png'title='carpeta'/>");
80

salida.print("</div>");
81

salida.print("<formaction='BaseDatosIbatis'method='post'>\n<br/>");
82

salida.print("<label>Titulo</label>\n<br/>");
83

salida.print("<inputtype='text'name='titulo'/>\n<br/>");
84

salida.print("<label>Autor</label>\n<br/>");

85

salida.print("<inputtype='text'name='autor'/>\n<br/>");

salida.print("<label>Tematica</label>\n<br/>");
86

salida.print("<inputtype='text'name='tematica'/>\n<br/>");
87

salida.print("<inputclass='boton'type='submit'value='enviar'/>\n<br/>");
88

salida.print("</form>\n<br/>");
89

salida.print("<divid='pie'>");
90

salida.print("<p>www.railsymas.com</p>");
91

salida.print("</div>");
92
93

salida.print("</div>\n");
94

salida.print("</body>\n<br/>");
95

salida.print("</html>");
96
97
98
}

99
100
/*(nonJavadoc)
101
*@seejavax.servlet.http.HttpServlet#doPost(HttpServletRequestrequest,
102
103 HttpServletResponseresponse)
*/
104
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
105
106 throwsServletException,IOException{

//TODOAutogeneratedmethodstub
107

Stringtitulo=request.getParameter("titulo");
108

Stringautor=request.getParameter("autor");
109

Stringtematica=request.getParameter("tematica");
110
111
112
113

response.setContentType("text/html");
114
115

PrintWritersalida=response.getWriter();
116
117

//creamoselobjetolibro
118

Librolibro=newLibro();
119
120

libro.setAutor_libro(autor);
121

libro.setTematica_libro(tematica);
122

libro.setTitulo_libro(titulo);
123

libro.setId_libro(0);
124
125
126
//insertamosenlabasededatoselobjetolibro
127

try
128

{
129

//insertamoslosdatosrecibidosde
130

sqlMap.insert("introducirLibro",libro);
131
132

//recuperamoslosdatosdelabasededatos
133

List<Libro>resultado=sqlMap.queryForList("getLibros");
134

http://www.railsymas.com

64

TUTORIALFRAMEWORKSTRUTS

135
136

//mostramoselresultado
137

salida.print("<!DOCTYPEhtmlPUBLIC'//W3C//DTDHTML4.01
138 Transitional//EN''http://www.w3.org/TR/html4/loose.dtd'>\n");
139

salida.print("<html>\n");
140

salida.print("<head><title>Mostramoslosdatos</title></head>\n");
141

salida.print("<linkrel='stylesheet'type='text/css'
142 href='css/estilo.css'/>\n");

143

salida.println("<body>");
144

salida.print("<divid='contenedor'>\n");
145

salida.print("<h2>Librosjdbc</h2>");

salida.println("<tableid='tabla'>");
146

salida.println("<tr>");
147

148
salida.println("<th>titulo</th><th>autor</th><th>tematica</th>");
149

salida.println("</tr>");
150

Iterator<Libro>iterador=resultado.iterator();
151

while(iterador.hasNext())
152

{
153

LibroauxLibro=(Libro)iterador.next();
154
155

salida.println("<tr>");

156

salida.println("<td
157
158 class='impar'>"+auxLibro.getTitulo_libro()+"</td>");

salida.println("<td
159
160 class='par'>"+auxLibro.getAutor_libro()+"</td>");

salida.println("<td
161
162 class='impar'>"+auxLibro.getTematica_libro()+"</td>");

salida.println("</tr>");
163
164
165
166
167

}
168
169

salida.println("</table>");
170

salida.print("<divid='pie'>");
171

salida.print("<p>www.railsymas.com</p>");
172

salida.print("</div>");
173

salida.print("</div>\n");
174

salida.println("</body>");
175

salida.println("</html>");
176

catch(SQLExceptione)

{
System.out.print("errordeconsulta"+e.getMessage());

http://www.railsymas.com

65

TUTORIALFRAMEWORKSTRUTS

STRUTSTILESPROYECTOWEBECLIPSE

Lostilessonplantillasqueutilizastrutsparalaorganizacindelaestructuravisualde
lasvistasdeunproyectoweb.Enrealidadstrutsnohacemsqueintegrarensu
frameworkalgoqueyaexistaenj2ee,queeranlasplantillasconjsp.
Comoyasehizoenunejemplodej2eeutilizabamosladirectiva<%@include
file="xxxx"%>paraincluircontenidoestticoyparalainclusindinmicautizabamos
<%@includepage="xxx"%>.estoltimocomorecordatorioj2ee.
Unavezcreadalaplantillalapodemosreutilizarparacualquierpginaquetengadicho
formatoyasnotenerqueescribirtodocdigocadavezquesehaceunanueva
pgina.

Aligualqueenlosanteriorespost,aadimosunnuevoejercicioalalista,enestecaso
parastrutstilesparaelloenelficheroejercicios.jsp,aadimoselsiguienteenlacepara
laaccinplantillas.
1
2 <divclass="enlace">
3 <html:linkaction="/plantillas">5)strutstiles</html:link>
4 </div>

http://www.railsymas.com

66

TUTORIALFRAMEWORKSTRUTS

Recordarestamosconlaversin1.3.10yestaversintenemosunficherode
configuracinllamadostrutsconfig.xml,
Vemoscomoellinkdelapginadelosejerciciosvalaaccinplantillas,enlaseccin
actionMappingdelficherodeconfiguracinstrutsconfig.xml
1 <action
2 path="/plantillas"
3 forward="plantillatiles"/>

Dentrodelproyectocreamosunacarpetatiles,dondecreamoslaspginasjspquevan
aintervenirenelproyecto

Enestaspginasjsphayunaqueesespecialmenteimportantecdigodepantilla.jsp
1
2 <%@pagelanguage="java"contentType="text/html;charset=UTF8"pageEncoding="UTF8"%>
3 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
4 <%@tagliburi="http://struts.apache.org/tagstiles"prefix="tiles"%>
5 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
6 "http://www.w3.org/TR/html4/loose.dtd">
7 <html:html>
8 <head>
9 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
10 <title><tiles:getAsStringname="titulo"/></title>
11
12 <html:base/>
13 <linktype="text/css"rel="stylesheet"href="../css/estiloplantilla.css"/>
14 </head>
15 <body>
16 <divid="contenedor">
17 <divid="cabecera">
18 <tiles:insertattribute="cabecera"/>
19 </div>
20 <divid="contendido">
21 <divid="menu">
22 <tiles:getname="menu"/>
23 </div>
24 <divid="contenido">
25 <tiles:getname="cuerpo"/>

http://www.railsymas.com

67

TUTORIALFRAMEWORKSTRUTS

26 </div>
27 </div>
28 <divid="pie">
29 <tiles:getname="pie"/>
30 </div>
31 </div>
32 </body>
</html:html>

Imagendelaplantilla

Losdiferentestiles,fragmentosdepginasjspcomoseutilizanetiquetasdestrutses
necesariointegrarlalibreriahtmlentodasellas,recordarqueestanubicadastalcomo
laimagen
Cdigodecabecera.jsp
1 <%@tagliburi="http://struts.apache.org/tagshtml" prefix="html" %>
2 <divid="imagencabecera">
3 <html:imgsrcKey="imagen.cabecera"altKey="imagen.cabecera.alt"/>
4 </div>

Cdigodemenu.jsp

http://www.railsymas.com

68

TUTORIALFRAMEWORKSTRUTS

1 <%@tagliburi="http://struts.apache.org/tagshtml" prefix="html" %>


2 <ulid="menu_lateral">
3 <li><html:linkaction="/objetos">Objetos</html:link></li>
4 <li><html:linkaction="/personajes">Personajes</html:link></li>
5 </ul>
6 <html:imgsrcKey="imagen.libros"altKey="imagen.libros.alt"/>

Cdigodecuerpo.jsp
1 <%@tagliburi="http://struts.apache.org/tagshtml" prefix="html" %>
2 <p>
3 Ejemplodedesarrolloconstrutstiles,tenemosunaplantillabaseydiferentesdefinicionesde
4 p&aacute;ginaenunficheroxmlllamadotilesdef.xml
5 </p>
6 <html:imgsrcKey="imagen.lapices"altKey="imagen.lapices.alt"/>

Cdigodepie.jsp
<%@tagliburi="http://struts.apache.org/tagshtml" prefix="html" %>
1 <pid="pizquierda">
2 <html:linkaction="/Welcome">Ejercicios</html:link>|<html:linkaction="/plantillas">Plantilla
3 </html:link>|<html:linkaction="/objetos">Objetos</html:link>|<html:linkaction="/personajes">
4 Personajes</html:link>
5 </p>
6
<pid="pderecha">@CopyRightrailsymas.com</p>

Creamosdosnuevaspginasjspparalasvistaspersonajesyobjetos
Cdigodepersonajes.jsp
1 <%@tagliburi="http://struts.apache.org/tagshtml" prefix="html" %>
2 <divid="imagenes">
3 <p>Personajes</p>
4 <html:imgsrcKey="imagen.personaje1"altKey="imagen.personaje1.alt"/>
5 <html:imgsrcKey="imagen.personaje2"altKey="imagen.personaje2.alt"/>
6 </div>

Cdigodelapginaobjetos.jsp
1 <%@tagliburi="http://struts.apache.org/tagshtml" prefix="html" %>
2 <divid="imagenes">
3 <p>Objetos</p>
4 <html:imgsrcKey="imagen.objeto1"altKey="imagen.objeto1.alt"/>
5 <html:imgsrcKey="imagen.objeto2"altKey="imagen.objeto2.alt"/>
6 </div>

ficherodepropiedades
1 #tiles
2 imagen.cabecera=../imagenes/cabecera2.png
3 imagen.cabecera.alt=imagencabecera

http://www.railsymas.com

69

TUTORIALFRAMEWORKSTRUTS

4 imagen.lapices=../imagenes/lapices.png
5 imagen.lapices.alt=l&aacute;pices
6 imagen.libros=../imagenes/libros.png
7 imagen.libros.alt=libros
8 imagen.objeto1=../imagenes/candado.png
9 imagen.objeto1.alt=candado.png
10 imagen.objeto2=../imagenes/impresora.png
11 imagen.objeto2.alt=impresora.png
12 imagen.personaje1=../imagenes/personachat.png
13 imagen.personaje1.alt=personachat.png
14 imagen.personaje2=../imagenes/personajes.png
15 imagen.personaje2.atl=personajes.png

ficherodeconfiguracindelasaccionesstrutsconfig.xmenlaseccinactionmapping
1
2 <action
3 path="/plantillas"
4 forward="plantillatiles"/>
5
6 <action
7
8 path="/objetos"
9 forward="plantillaobjetos"/>
10
11 <action
12 path="/personajes"
13 forward="plantillapersonajes"/>

Tenemosdosposibilidadesestablecerlasdefinicionesmediantejspobienmediante
unficherodeconfiguracinxmldenominadotilesdef.xmldentrodelacarpetanweb
infdelproyectostruts
Enelsiguientepostparalasegundapartedeesteejercicioseverelficherode
configuracinantescitadoylaexplicacinmsdetalladaascomolasdiferentes
capturasdelasvistasobjetosypersonajes.

http://www.railsymas.com

70

TUTORIALFRAMEWORKSTRUTS

STRUTSTILESPROYECTOWEBECLIPSE2PARTE

Comosepuedeobservarlasdosimgenessiguenteniendounaspectosimilaraldela
plantillainicial.Lonicoquecambiaeslapginajspqueestaasignadaaldivdecuerpo
delesquelodelapantilla.jsp,eseeselobjetivodelostilesproporcionarunesquema
visualcomnaunconjuntodepginas.
Dentrodelstrutsconfig.xmltenemosunaseccinyapreestablecida,solamentehay
quedescomentarla
1 <pluginclassName="org.apache.struts.tiles.TilesPlugin">
2 <setpropertyproperty="definitionsconfig"value="/WEBINF/tilesdefs.xml"/>
3 <setpropertyproperty="definitionsdebug"value="2"/>
4 <setpropertyproperty="moduleAware"value="true"/>
5
6 </plugin>

comosepuedeobservarenestaseccinsehacereferenciaalarchivoxmlubicadoen
webinf/tilesdefs.xml,setratadelficheroxmlquetieneladecleracindelas
definicionesdelasvistas.
1 <?xmlversion="1.0" encoding="UTF8"?>
2
3 <!DOCTYPEtilesdefinitionsPUBLIC
4 "//ApacheSoftwareFoundation//DTDTilesConfiguration1.1//EN"
5 "http://jakarta.apache.org/struts/dtds/tilesconfig_1_1.dtd">
6
7
8 <tilesdefinitions>
9
10 <definitionname="${YOUR_DEFINITION_HERE}">
11 </definition>
12
13 <definitionname="plantillatiles"path="/tiles/plantilla.jsp">
14 <putname="titulo"value="plantillastruts"type="string"/>
15 <putname="cabecera"value="cabecera.jsp"type="page"/>
16 <putname="menu"value="menu.jsp"type="page"/>
17 <putname="cuerpo"value="cuerpo.jsp"type="page"/>
18 <putname="pie"value="pie.jsp"/>
19 </definition>
20 <definitionname="plantillaobjetos"extends="plantillatiles">
21 <putname="titulo"value="plantillaparaobjetos"type="string"/>
22 <putname="cuerpo"value="objetos.jsp"type="page"/>
23 </definition>
24 <definitionname="plantillapersonajes"extends="plantillatiles">
25 <putname="titulo"value="plantillaparapersonajes"type="string"/>
26 <putname="cuerpo"value="personajes.jsp"type="page"/>
27 </definition>
28 </tilesdefinitions>

http://www.railsymas.com

71

TUTORIALFRAMEWORKSTRUTS

Laplantillatilesplantilla.jsperalapginajspquecontieneelesqueletodelaplantilla,
secorrespondeconladefinicindelname=plantillatiles,estenombreesaprovechado
porstrutsparahacerreferenciaalaplantilladesdeelstrutsconfig.xml.
Comoarrancalaplantillaencuantoalprocesodeejecucin.Partimoscomosiempre
delapginadeejerciciosendichapginahayunenlaceaunactionqueesrecogido
porstrutsconfig.xmleseactionlovuelvoaponer
1 <action
2 path="/plantillas"
3 forward="plantillatiles"/>

Eseactioneraplantillas.doydondesehaceelreenvoalforwardplantillatilesquees
justamenteelvalordelatributonamedelasdefinicionesdetilesdef.xmlconelpath
tiles/plantillas.jspelrestodelasjspdeladefinicinestanyadentrodelacarpeta
tilesalmismonivel.
Unerrortpicoquepuedeocurrir,esdeclararlapginajspplantillas.jspyllamarla
directamenteenesecasonosdamltipleserrores,varioserroresactionservletyun
errordecontextoindicandoqueestvaco.
Ladefinicindelficherotilesdef.xmleslaquealimentalaplantilla.jsp,indicandoenel
namelacabecera,men,cuerpoypielapginajspquelecorrespondeacadacual
medianteelatributovalue.Tambinhayunatributoopcionaltypequeindicaeltipo
devalor,hemosutilizadodospagesystring,esteultimoparaindicarelttulodela
pgina.
Comosepuedeapreciarenelejemplotantodesdelaprimerapartecomolasegunda
existentresvistas,laprimeraqueestaenelanteriorpostycorrespondeconla
plantillainicialylavistadeobjetosypersonajes.
Siqueremosutilizarpartedellayoutdelasplantillasperohaciendouncambiopara
tenerunavistanuevaejemploobjetosnotenemosmsquehacerunaherenciapor
esoenladefinicindelarchivotilesdef.xmlnosvieneunname=plantillaobjetoque
heredaextendsdeplantillatiles,todomenoselcuerpoyelttulo.
Medianteelficheroxmltilesdef.xmlhacemosherenciayademsestamos
sobreescribiendocomoenPOOunapartedelaplantilla,enestecasoelcuerpo.
Enelstrutsconfig.xmlseincluyelosiguiente,elcontroladorproporcionadoporel
frameworkTilesenlugardelcontroladordeStruts.Estecontroladoresunaversin
extendidadelcontroladordeStruts.
Siloquitamosodescomentamosnossaleunerrordeservletexception
1 <!=============================================ControllerConfiguration>
2
3 <controllerprocessorClass="org.apache.struts.tiles.TilesRequestProcessor"/>

http://www.railsymas.com

72

TUTORIALFRAMEWORKSTRUTS

Imagenlavistadeobjetos

Imagendelavistadepersonajes

http://www.railsymas.com

73

TUTORIALFRAMEWORKSTRUTS

TUTORIALHTMLSTRUTSTAGS

Enejemplosanteriores,sehabautilizadounasetiquetasquepodanresultar
diferentessivenimosdeotroslenguajesdeprogramacinweb.
Strutsutilizaunasetiquetashtmlmuysimilaresalasdehtmlperoconalgunas
variantes.Siempreseanteponelaetiquetahtml,detalformaqueparaindicarelinicio
yelfindeldocumentoseponey
Parasuutilizacinenunapginajspdebemosincluirlasiguientesintaxisparaelcaso
de1.3.10
<%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>

elvalordelatributoprefixseponehtmlparanoequivocarseperopodrasecualquier
otronombre
html

equivaleahtml

button

equivalenteainputtype=button

cancel

equivaleainputtype=subtmit

checkbox equivaleainputtype=checkbox
hidden

equivaleainputtype=hidden

img

equivaleaimg

javascript equivaleajavascript
link

equivaleaa

base

basedelapgina

messages muestralosmensajesdelidioma
multibox typecheckboxperopermiteunarraydestringdelospropertyiguales
option

equivaleaoption

password equivaleapassword
radio

equivalearadio

reset

equivaleareset

select

equivaleaselect

submit

equivaleatypesubmit

text

equivaleatypetext

textarea equivaleatextarea
frame

equivaleaframe

form

equivaleahtml

file

equivaletypefile

Enladescargadelproyectostrutsexisteunacarptetadocsconhtmlcontodala
informacionreferentealostagshtmlcomobeanlogictilesetc..

http://www.railsymas.com

74

TUTORIALFRAMEWORKSTRUTS

TUTORIALDELOOKUPDISPATCHACTIONSTRUTS

LookupDispatchactionesotraclasedestrutsquecomplementalosejercicios
anterioressobreformulariosstruts.
HabamosvistolaclaseDispatchactionenstruts,queaportabalaposibilidadde
realizardistintasaccionesenunasolaclase,aadiendounanuevapotencialidadalas
clasesaction,lascualessolamentetenanelmtodoservicegenricopararespondera
laspeticionesdelosusuarios.
LookupDispatchactiontienetambinensuconfiguracinunparmetroparameter,
queindicaelnombredelmtodo.Lookupdispatchactiontienelaventajaquepermite
desdeunmismoformulariopoderllamaradistintosmtodos.

CDIGODEPGINAEJERCICIOS.JSPCOMOLOSANTERIORESEJEMPLOS
1 <divclass="enlace">
2 <html:linkaction="/dinamicoLookup">6)lookupdispatchAction</html:link>
3 </div>

http://www.railsymas.com

75

TUTORIALFRAMEWORKSTRUTS

CONFIGURACIONDELBEANDYNAVALIDATORFORM
1
2 !================================================FormBeanDefinitions>
3
4 <formbeanname="dinamicolibro"type="org.apache.struts.validator.DynaValidatorForm">
5 <formpropertyname="titulo"type="java.lang.String"/>
6 <formpropertyname="autor"type="java.lang.String"/>
7 <formpropertyname="cambio"type="java.lang.String"/>
8 </formbean>

CONFIGURACINDELARCHIVOSTRUTSCONFIG.XMLPARAACTIONMAPPING
1 <!===========================================ActionMappingDefinitions>
2
3 <action
4 path="/dinamicoLookup"
5 forward="/pages/formularioLookup.jsp"/>
6
7 <action
8 path="/lookupDispatchAction"
9 type="acciones.AccionLookupDispatchAction"
10 scope="request"
11 validate="true"
12 name="dinamicolibro"
13 input="/pages/formularioLookup.jsp"
14 parameter="method">
15 <setpropertyproperty="cancellable"value="true"/>
16
17 <forwardname="cancelada"path="/pages/cancelada2.jsp"/>
18 <forwardname="editarlibros"path="/pages/edicion2.jsp"/>
19 </action>
20
21 <action
22 path="/LookupDispatchAction2"
23 type="acciones.AccionLookupDispatchAction"
24 scope="request"
25 validate="false"
26 name="dinamicolibro"
27 parameter="method">
28
29 <setpropertyproperty="cancellable"value="true"/>
30
31 <forwardname="cancelada"path="/pages/cancelada2.jsp"/>
32 <forwardname="datoslibro"path="/pages/datoslibros.jsp"/>
33 </action>

Configuracindelavalidacindeloscamposdelbeanenelficherovalidation.xml
dentrodeltag
<formvalidation>

ComorepasodesdeDynaValidatorForm,secreabanunosformulariosbeandinmicos,
quepermitanvalidarloscamposdeunformulariosinteneerquecrearlaclase

http://www.railsymas.com

76

TUTORIALFRAMEWORKSTRUTS

actionForm.Enelficheroxmlvalidation.xmlsecreanlasreglasparaqueloscampos
seanobligatorios.
1 <formset>
2 <formname="dinamicolibro">
3 <field
4 property="titulo"
5 depends="required">
6 <argkey="libro.titulo"/>
7 </field>
8
9 <field
10 property="autor"
11 depends="required">
12 <argkey="libro.autor"/>
13 </field>
14 </form>
15
16 </formset>

CONFIGURACINDELFICHERODEPROPIEDADESPROPERTIES
1 #lookupdispathAction
2 formularioLookup.cancelar=cancelar
3 formularioLookup.crear=crear
4 formularioLookup.editartitulo=EditarTitulo
5 formularioLookup.editarautor=EditarAutor
6 tituloLookup.libro=LookupDispatchAction
7 Lookup.titulo=titulo
8 Lookup.autor=autor

CDIGODELAPGINAJSPFORMULARIOLOOKUP.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
3 "http://www.w3.org/TR/html4/loose.dtd">
4 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
5 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
6 <html:html>
7 <head>
8 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
9 <title><bean:messagekey="tituloLookup.libro"/></title>
10 <html:base/>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14 <divid="contenedor">
15 <h2><bean:messagekey="tituloLookup.libro"/></h2>
16
17 <divid="errores">
18 <html:errors/>
19 </div>
20 <divid="imagen">
21 <html:imgsrcKey="libro.imagen"titleKey="libro.imagen.alt"/>
22 </div>
23

http://www.railsymas.com

77

TUTORIALFRAMEWORKSTRUTS

24 <divid="contenido">
25 <html:formaction="lookupDispatchAction"focus="nombre"styleId="formulario"method="post">
26 <divclass="campo">
27 <bean:messagekey="Lookup.titulo"/>
28 <html:textproperty="titulo"/>
29 </div>
30
31 <divclass="campo">
32 <bean:messagekey="Lookup.autor"/>
33 <html:textproperty="autor"/>
34 </div>
35
36
37 <html:submitstyleClass="boton"property="method"><bean:message
38 key="formularioLookup.crear"/></html:submit>
39 <html:cancelstyleClass="boton"><bean:messagekey="formularioLookup.cancelar"/>
40 </html:cancel>
41 <html:resetstyleClass="boton"value="borrar"/>
42 </html:form>
43 </div>
44 <divid="pie">
45 <p>www.railsymas.com</p>
46 </div>
47 </div>

</body>
</html:html>

CLASELOOKUPDISPATCHACTIONACCIONLOOKUPDISPATCHACTION.JAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

packageacciones;

importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionMapping;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.actions.LookupDispatchAction;
importorg.apache.struts.validator.DynaValidatorForm;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjava.util.Map;
importjava.util.HashMap;

publicclassAccionLookupDispatchActionextendsLookupDispatchAction{

privateActionForwardenvio;

privateDynaValidatorFormformulario;

privateStringtitulo;

privateStringautor;

protectedMapgetKeyMethodMap()

Mapmap=newHashMap();

map.put("formularioLookup.editartitulo","EditarTitulo");

map.put("formularioLookup.editarautor","EditarAutor");

map.put("formularioLookup.crear","crear");

http://www.railsymas.com

78

TUTORIALFRAMEWORKSTRUTS

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

returnmap;

protectedActionForwardcancelled(ActionMappingmapping,ActionForm
form,HttpServletRequestrequest,HttpServletResponseresponse)throwsException

if(isCancelled(request)){

envio=mapping.findForward("cancelada");

returnenvio;

//creamoslosmtodosquerespondenalasacciones

publicActionForwardcrear(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)throwsException

//recuperamoslosdatosdelformulariobeandinmicoValidator

formulario=(DynaValidatorForm)form;

titulo=formulario.getString("titulo");

autor=formulario.getString("autor");

System.out.println(titulo);

envio=mapping.findForward("editarlibros");

returnenvio;

publicActionForwardEditarTitulo(ActionMappingmapping,ActionFormform,
HttpServletRequestresquest,HttpServletResponseresponse)throwsException

//recuperamoslosdatosdelformulariobeandinmicoValidator

formulario=(DynaValidatorForm)form;

Stringcadena="Sehacambiado"+this.titulo+"por"+formulario.getString("titulo");

formulario.set("cambio",cadena);

//recargamoselformularioconelvalorguardado

formulario.set("autor",this.autor);

envio=mapping.findForward("datoslibro");

returnenvio;

publicActionForwardEditarAutor(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)throwsException

http://www.railsymas.com

79

TUTORIALFRAMEWORKSTRUTS

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

//recuperamoslosdatosdelformulariobeandinmicoValidator

//recuperamoslosdatosdelformulariobeandinmicoValidator
formulario=(DynaValidatorForm)form;
Stringcadena="Sehacambiado"+this.autor+"por"+formulario.getString("autor");

formulario.set("cambio",cadena);
//recargamoselformularioconel
formulario.set("titulo",this.titulo);

envio=mapping.findForward("datoslibro");

returnenvio;
}

LookupDispatchAction,permitealigualquecondispatchactiontenervariasacciones
(mtodos)enlamismaclasedetalformaquetenemosdosformulariosquellamanala
mismaclase.Atravsdelosdiferentesmtodosserealizandistintasacciones.
SeutilizaunHashMapparaestablecerunconjuntodecontraseasparalosdistintos
mtodosausar,esascontraseassonlasulilizadasenlosbotonesdelaspginasjsp.
EsnecesariocrearelmtodoprotectedMapgetKeyMethodMapparalacreacindel
conjuntodeclavesmtodo.
Sisequiereincluirelbotndecancelacinconelusodeestaclase,laconfiguracinen
elficherostrutsconfig.xmlparaellonoresponde,porloquehayquehacercambiosen
laclasejavaeincluirelmtodocancelledparasobreescribirloyresponderalbotnde
cancelacin.
Imagenresultadodelenvodelosdatos

http://www.railsymas.com

80

TUTORIALFRAMEWORKSTRUTS

Introducimostitulo2enelcampodetitulo

resultadofinal

http://www.railsymas.com

81

TUTORIALFRAMEWORKSTRUTS

http://www.railsymas.com

82

TUTORIALFRAMEWORKSTRUTS

DATASOURCESTRUTS1.2.XPROYECTOWEBECLIPSE

EnlacealproyectostrutsDatasource
Eldatasource,seutilizaparaestablecerunpooldeconexionesqueimplementanla
interfacejavax.sql.DataSource.Permitiendoestablecerunaconfiguracinparalas
basesdedatosutilizadasenlasaplicacionesdestruts,ysolamentedesdelasclasesde
negociollamaraestaconfiguracinparapoderutilizarlas.
Estetipodeconfiguracinesvlidoparalasversionesdestruts1.1hastalaversin
1.2.9.Esteejemploadiferenciadelosanterioresdestrutsenelqueseutilizabala
versin1.3.10,estrealizadoconla1.2.9.
DATASOURCESTRUTS

Ladeclaracindeldatasourcevadalantedelosbeansparaladtdstrutsconfig_1_2.dtd
1 <!DOCTYPEstrutsconfigPUBLIC
2 "//ApacheSoftwareFoundation//DTDStrutsConfiguration1.2//EN"
3 "http://jakarta.apache.org/struts/dtds/strutsconfig_1_2.dtd">
4
5 <strutsconfig>
6
7 <!============================================DataSourceConfiguration>
8 <datasources>

CONFIGURACINDELARCHIVOSTRUTSCONFIG.XMLPARAELDATASOURCE
1 <datasources>
2
3 <datasourcetype="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
4
5 <setpropertyproperty="driverClassName"value="com.mysql.jdbc.Driver"/>
6
7
8 <setpropertyproperty="url"value="jdbc:mysql://localhost:3306/libros_jdbc"/>
9
10 <setpropertyproperty="username"value="root"/>

http://www.railsymas.com

83

TUTORIALFRAMEWORKSTRUTS

11
12 <setpropertyproperty="password"value="root"/>
13
14 <setpropertyproperty="maxActive"value="10"/>
15
16 <setpropertyproperty="defaultReadOnly"value="false"/>
17
18 <setpropertyproperty="defaultAutoCommit"value="true"/>
19
20 <setpropertyproperty="validationQuery"value="SELECTCOUNT(*)FROMlibros"/>
21
22 </datasource>
23
24 </datasources>

CONFIGURACINDELOSACTIONSPARAELSTRUTSCONFIG.XML

Creamoslosactionsparaelejemplo,simplementeredireccionamoslaaccin
Welcome.doalaaccinconexin.Siseestablecelaconexincorrectamentese
redireccionaalapgina
1 <!===========================================ActionMappingDefinitions>
2
3 <actionmappings>
4 <!Default"Welcome"action>
5 <!ForwardstoWelcome.jsp>
6 <action
7 path="/Welcome"
8 forward="/conexion.do"/>
9
10 <action
11
12 path="/conexion"

http://www.railsymas.com

84

TUTORIALFRAMEWORKSTRUTS

13 type="accion.accionBaseDatos"
14 scope="request">
15 <forwardname="satisfactoria"path="/pages/registroSatisfactorio.jsp"/>
16 <forwardname="fallida"path="/pages/fallida.jsp"/>
17
18 </action>

CDIGODELAPGINAFALLIDA.JSP
<%@pagelanguage="java"contentType="text/html;charset=ISO88591"pageEncoding="ISO8859
1 1"%>
2 <%@tagliburi="/tags/strutshtml"prefix="html"%>
3 <%@tagliburi="/tags/strutsbean"prefix="bean"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
5
<html>
6
<head>
7
<metahttpequiv="ContentType"content="text/html;charset=ISO88591">
8
<title>ConexionFallida</title>
9
<html:base/>
10
<linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
11
</head>
12
<body>
13
<divid="contenedor">
14
<divid="contenido">
15
<p>conexionfallida</p>
16
</div>
17
<divid="pie">
18
<p>www.railsymas.com</p>
19
</div>
20
</div>
21
</body>
22
</html>

http://www.railsymas.com

85

TUTORIALFRAMEWORKSTRUTS

CDIGODELAPGINAREGISTROSATISFACTORIO
<%@pagelanguage="java"contentType="text/html;charset=ISO88591"pageEncoding="ISO8859
1 1"%>
2 <%@tagliburi="/tags/strutshtml"prefix="html"%>
3 <%@tagliburi="/tags/strutsbean"prefix="bean"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
5
<html:html>
6
<head>
7
<metahttpequiv="ContentType"content="text/html;charset=ISO88591">
8
<title>Consultaalabasededatos</title>
9
<html:base/>
10
<linkrel="stylesheet"href="../css/estilo.css"type="text/css"/>
11
</head>
12
<body>
13
<divid="contenedor">
14
<divid="contenido">
15
<p>Establecemosconexion</p>
16
</div>
17
<divid="pie">
18
<p>www.railsymas.com</p>
19
</div>
20
</div>
21
</body>
22
</html:html>

resultadodelaejecucinporpantalla

http://www.railsymas.com

86

TUTORIALFRAMEWORKSTRUTS

CDIGODELACLASEJAVAACCIONBASEDATOSDENTRODELPACKAGEDE
ACCIONES
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

packageaccion;

importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionMapping;

importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.sql.DataSource;
importjava.sql.Connection;
importjava.sql.Statement;
importjava.sql.ResultSet;
importjava.sql.SQLException;

publicclassaccionBaseDatosextendsAction{

privateDataSourcedatasource;

privateConnectionconexion;

privateStringdevolucion;

privateStatementsentenciaSql;

privateResultSetresultado;

publicActionForwardexecute(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)

try

http://www.railsymas.com

datasource=getDataSource(request);

87

TUTORIALFRAMEWORKSTRUTS

30

conexion=datasource.getConnection();

sentenciaSql=conexion.createStatement();

resultado=sentenciaSql.executeQuery("Select*Fromlibros");

36

while(resultado.next())

37

38

39

41

if(conexion!=null)

42

43

48

conexion.close();

49

51

catch(SQLExceptione)

52

54

devolucion="fallida";

55

returnmapping.findForward(devolucion);

31
32
33
34
35

System.out.println(resultado.getString("autor"));

40

devolucion="satisfactoria";

44
45
46
47

50

53

56
57
58
59
60

http://www.railsymas.com

88

TUTORIALFRAMEWORKSTRUTS

61

62
63 }

resultadoenconsoladelaejecucion,losautoresdelabasededatosdelibros_jdbc
paralatablalibros
1 INFO:Tilesdefinitionfactoryfoundforrequestprocessor''.
2 autor1
3 autor2
4 autor3
5 autor4
6 autor5
7 autor6
8 autor7
9 autor7
10 autor8
11 autor9
12 autor10

http://www.railsymas.com

89

TUTORIALFRAMEWORKSTRUTS

DATASOURCESTRUTS1.3.XPROYECTOWEBECLIPSE

integracindelenlaceenlapginawebdeejercicios
1 <divclass="enlace">
2 <html:linkaction="/datasource">7)datasource</html:link>
3 </div>

CONFIGURACINDELAACCINDATASOURCE.DOENELSTRUTSCONFIG.XML
1 <action
2 path="/datasource"
3 forward="/pages/formulariodatasource.jsp"
4 />

Configuracindelbeanenelficherostrutsconfig.xml,eslaconfiguracindelbean
dinmicoconlaspropiedadesdelatabladelabasededatoslibroscampotitulo,
temticayautorvistosenjdbcj2ee
1 <formbeanname="beandatasource"type="org.apache.struts.validator.DynaValidatorForm">
2 <formpropertyname="titulo"type="java.lang.String"/>
3 <formpropertyname="tematica"type="java.lang.String"/>
4 <formpropertyname="autor"type="java.lang.String"/>
5 </formbean>

CONFIGURACINDELFICHERODEPROPIEDADES
1 #datasource
2 formulariodatasource.crear=enviar
3 formulariodatasource.cancelar=cancelar
4 formulariodatasource.titulo=formulariodatasource
5 formulariodatasource.titulolibro=titulo
6 formulariodatasource.tematica=tematica
7 formulariodatasource.autor=autor
8 formulariodatasource.resultado=listadodelibros
9 datasourceresultado.titulo=listadodedatos

Siintentamoscreareldatasourcealigualquehacamosconlaversin1.2nosdaerror,
enelarchivodeconfiguracindestruts

http://www.railsymas.com

90

TUTORIALFRAMEWORKSTRUTS

Ladtddestruts1.3soportaunconjuntodeetiquetasenelordenqueseindicaenla
siguienteimagen.

Eltagnovienesoportadoparaestadtd
Explicacionesdelproyectostrutsenelwikidatasource
Removedtheandelements
creamosunpackagenuevoparaalbergaralbeanlibro,packagevo,sellamaasporel
patrnvalueobject
1 packagevo;
2
3 publicclassLibro{
4
5
privateStringtitulo;
6
privateStringautor;
7
privateStringtematica;
8
9
publicStringgetTitulo(){

returntitulo;
10
}
11
publicvoidsetTitulo(Stringtitulo){
12

this.titulo=titulo;
13
}
14
publicStringgetAutor(){
15

returnautor;
16
}
17
publicvoidsetAutor(Stringautor){
18

this.autor=autor;
19
}
20
publicStringgetTematica(){
21

returntematica;
22
}
23
publicvoidsetTematica(Stringtematica){
24

this.tematica=tematica;
25
}
26
27
28 }

http://www.railsymas.com

91

TUTORIALFRAMEWORKSTRUTS

CLASECONEXIONDENTRODELPACKAGECONEXIONES
packageconexiones;
1

2
importjava.sql.Connection;
3
importjava.sql.SQLException;
4

5
importjavax.sql.DataSource;
6
importjavax.naming.InitialContext;
7
importjavax.naming.NamingException;
8

10
publicclassConexion{
11

12

privateConnectionconexion=null;
13

14

publicConexion()
15

{
16

17

18

}
19

20

publicConnectionestablecerConexion()
21

{
22

23

try
24

{
25

26

InitialContextcontexto=newInitialContext();
27

DataSourceds=(DataSource)
28
contexto.lookup("java:comp/env/jdbc/datasource");
29

this.conexion=ds.getConnection();

30

31

32

}
33

catch(NamingExceptione)
34

{
35

System.out.println(e.getMessage());
36

}
37

38

catch(SQLExceptione)
39

{
40

System.out.println(e.getMessage());
41

}
42

43

returnthis.conexion;
44

45

}
46

47
}

http://www.railsymas.com

92

TUTORIALFRAMEWORKSTRUTS

CONFIGURACINDELFICHEROWEB.XML
1 <resourceref>
2 <description>DBConnection</description>
3 <resrefname>jdbc/datasource</resrefname>
4 <restype>javax.sql.DataSource</restype>
5 <resauth>Container</resauth>
6 <ressharingscope>shareable</ressharingscope>
7 </resourceref>

FICHEROCONTEXT.XML
1 <?xmlversion="1.0" encoding="UTF8"?>
2 <Contextpath="/DBTest"docBase="DBTest"
3 debug="5"reloadable="true"crossContext="true">
4
5 <!maxActive:MaximumnumberofdBconnectionsinpool.Makesureyou
6 configureyourmysqldmax_connectionslargeenoughtohandle
7 allofyourdbconnections.Setto1fornolimit.
8 >
9
10 <!maxIdle:MaximumnumberofidledBconnectionstoretaininpool.
11 Setto1fornolimit.SeealsotheDBCPdocumentationonthis
12 andtheminEvictableIdleTimeMillisconfigurationparameter.
13 >
14
15 <!maxWait:MaximumtimetowaitforadBconnectiontobecomeavailable
16 inms,inthisexample10seconds.AnExceptionisthrownif
17 thistimeoutisexceeded.Setto1towaitindefinitely.
18 >
19
20 <!usernameandpassword:MySQLdBusernameandpasswordfordBconnections>
21
22 <!driverClassName:Classnamefortheoldmm.mysqlJDBCdriveris
23 org.gjt.mm.mysql.DriverwerecommendusingConnector/Jthough.
24 ClassnamefortheofficialMySQLConnector/Jdriveriscom.mysql.jdbc.Driver.
25 >
26
27 <!url:TheJDBCconnectionurlforconnectingtoyourMySQLdB.
28 >
29
30 <Resourcename="jdbc/datasource"auth="Container"type="javax.sql.DataSource"
31 maxActive="100"maxIdle="30"maxWait="10000"
32 username="root"password="root"driverClassName="com.mysql.jdbc.Driver"
33 url="jdbc:mysql://localhost:3306/libros_jdbc"/>
34
35 </Context>

http://www.railsymas.com

93

TUTORIALFRAMEWORKSTRUTS

CONFIGURACINDELAACCINFORMULARIODATASOURCE.DO
1
2
3
4
5
6
7
8
9
10
11
12
13

<action
path="/formulariodatasource"
type="acciones.ConexionDatasource"
scope="request"
validate="true"
name="beandatasource"
input="/pages/formulariodatasource.jsp">

<setpropertyproperty="cancellable"value="true"/>

<forwardname="cancelada"path="/pages/cancelada2.jsp"></forward>
<forwardname="mostrardatos"path="/pages/mostrarlistado.jsp"></forward>
</action>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

packageacciones;

importconexiones.Conexion;
importvo.Libro;

importjava.io.PrintWriter;
importjava.sql.SQLException;
importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.validator.DynaValidatorForm;
importjava.sql.Statement;
importjava.sql.Connection;
importjava.sql.ResultSet;
importjava.util.ArrayList;
importjavax.servlet.http.HttpSession;

publicclassConexionDatasourceextendsAction{

privateConnectionconexionr=null;
privateActionForwardenvio=null;

privateConexionconexion=null;

privateStatementsentenciaSql;

privateResultSetresultado=null;

privateLibrolibro;

privateArrayList<Libro>listalibros;

privateHttpSessionsession=null;

publicActionForwardexecute(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)throwsException

DynaValidatorFormformulario=(DynaValidatorForm)form;

conexion=newConexion();

response.setContentType("Text/html");

http://www.railsymas.com

94

TUTORIALFRAMEWORKSTRUTS

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

PrintWritersalida=response.getWriter();

if(this.isCancelled(request))

envio=mapping.findForward("cancelada");

else

try

conexionr=conexion.establecerConexion();

sentenciaSql=conexionr.createStatement();

//ejecutamoslasentenciadeseleccindeloscamposmenoselid

System.out.print(formulario.get("titulo"));

System.out.print(formulario.get("autor"));

System.out.print(formulario.get("tematica"));

sentenciaSql.executeUpdate("INSERTINTOlibrosVALUES
("+0+",'"+formulario.get("titulo")+"','"+formulario.get("autor")+"','"+formulario.get("tematica")+"')
;");

//recuperamoslosdatosdelabasededatos

resultado=sentenciaSql.executeQuery("SELECT*fromlibros;");

if(resultado!=null)

//creamoselarraydelibros

listalibros=newArrayList<Libro>();

while(resultado.next())

libro=newLibro();

libro.setTitulo(resultado.getString("titulo"));

libro.setAutor(resultado.getString("autor"));

libro.setTematica(resultado.getString("tematica"));

listalibros.add(libro);

//cerramoslaconexion

conexionr.close();

//establecemoselparmetroporpeticion

session=request.getSession(true);

session.setAttribute("listadolibros",listalibros);

envio=mapping.findForward("mostrardatos");

http://www.railsymas.com

95

TUTORIALFRAMEWORKSTRUTS

99
100
101
102
103
104
105
106
107
108
109
110
111
112

catch(
{

returnenvio;

SQLExceptione)
salida.println("ExcepcionSql:"+e.getMessage());

FORMULARIODATASOURCE.JSP
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <html:base/>
9 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
10 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
11 <title><bean:messagekey="formulariodatasource.titulo"/></title>
12 </head>
13 <body>
14 <divid="contenedor">
15 <h2><bean:messagekey="formulariodatasource.titulo"/></h2>
16
17 <divid="errores">
18 <html:errors/>
19 </div>
20 <divid="imagen">
21 <html:imgsrcKey="dinamico.registro.imagen"titleKey="dinamico.registro.imagen.alt"/>
22 </div>
23
24 <divid="contenido">
25 <html:formaction="formulariodatasource"focus="nombre"styleId="formulario"method="post">
26 <divclass="campo">
27 <bean:messagekey="formulariodatasource.titulolibro"/>
28 <html:textproperty="titulo"/>
29 </div>
30 <divclass="campo">
31 <bean:messagekey="formulariodatasource.autor"/>
32 <html:textproperty="autor"/>
33 </div>
34
35 <divclass="campo">
36 <bean:messagekey="formulariodatasource.tematica"/>
37 <html:textproperty="tematica"/>

http://www.railsymas.com

96

TUTORIALFRAMEWORKSTRUTS

38 </div>
39
40 <html:submitstyleClass="boton"><bean:messagekey="formulariodatasource.crear"/>
41 </html:submit>
42 <html:cancelstyleClass="boton"><bean:messagekey="formulariodatasource.cancelar"/>
43 </html:cancel>
44 <html:resetstyleClass="boton">borrar</html:reset>
45 </html:form>
46 </div>
47 <divid="pie">
48 <p>www.railsymas.com</p>
49 </div>
</div>
</body>
</html:html>

Imagencorrespondiente

MOSTRARLISTADO.JSP

Lasetiquetaslogicnospermiteniterarsobrelosresultadosobtenidos,logic:emptynos
permitesabersielvalordelavariablereferenciadapornameestvaco,enstecaso
seutilizaparamostrarelmensajecorrespondiente.Paracomprobarquenoestvaco
seutilizalogic:notEmpty,paraluegoiterarporlosresultadoconlogic:iterate
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
3 <%@tagliburi="http://struts.apache.org/tagslogic"prefix="logic"%>
4 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
5
6 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
7 "http://www.w3.org/TR/html4/loose.dtd">
8 <html>
9 <head>
10 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
11 <html:base/>
12 <title><bean:messagekey="datasourceresultado.titulo"/></title>

http://www.railsymas.com

97

TUTORIALFRAMEWORKSTRUTS

13 <linkrel="stylesheet"href="../css/estilo.css" type="text/css"/>
14
15 </head>
16 <body>
17 <divid="contenedor">
18 <divid="tabla">
19 <logic:emptyname="listadolibros">
20 <p>Labasededatosdelibrosestavac&iacute;a</p>
21 </logic:empty>
22
23 <logic:notEmptyname="listadolibros">
24 <h2><bean:messagekey="formulariodatasource.resultado"/></h2>
25 <tabletitle="tabladedatoslibros">
26 <tr><th>titulo</th><th>autor</th><th>tematica</th></tr>
27
28 <logic:iteratename="listadolibros"id="libro">
29 <tr>
30 <tdclass="par">
31 <bean:writename="libro"property="titulo"/>
32 </td>
33 <tdclass="impar">
34 <bean:writename="libro"property="autor"/>
35 </td>
36 <tdclass="par">
37 <bean:writename="libro"property="tematica"/>
38 </td>
39 </tr>
40 </logic:iterate>
41 </table>
42 </logic:notEmpty>
43 </div>
44
45 <divid="pie">
46 <p>www.railsymas.com</p>
47 </div>
48 </div>
49 </body>
</html>

Imagencorrespondiente

http://www.railsymas.com

98

TUTORIALFRAMEWORKSTRUTS

http://www.railsymas.com

99

TUTORIALFRAMEWORKSTRUTS

MOSTRANDOLISTADODEDATOS

Cuandomostramoslosdatos,recogidosdeunabasesdedatos,puedequeelnmero
deitemsrecogidosseabastanteamplioporloqueresultarabastanteengorrosopara
elusuarioverunlistadomuylargo.
Sehacenecesariodarunarespuestaaesteproblema.paraelloutlizamoslapaginacin
Podemoscreardedosformasdistintas,bienamanoobienutilizandounalibrerade
strutsadecuada.Displaytagesunjarquepermitelapaginacinylaexprotacinde
datosadiferentesformatos.
Parasuutilizacin,necesitamosimportarlalibreradisplaytag(
http://displaytag.sf.net)
<%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
1 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
2 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3 <%@tagliburi="http://displaytag.sf.net"prefix="display"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <html:base/>
9 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
10 <title><bean:messagekey="displaytag.titulo"/></title>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14
15 <divid="contenedor">
16
17 <divid="tabla">
18
19 <display:tableid="libro"name="sessionScope.listadolibros"pagesize="5"
20 requestURI="/mostrarlistadodisplaytag.do">
21
22 <display:columnproperty="titulo"title="t&iacute;tulo"sortable="true"/>
23 <display:columnproperty="autor"title="autor"sortable="true"/>
24 <display:columnproperty="tematica"title="tem&aacute;tica"sortable="true"/>
25
26 </display:table>
27
28 </div>
29
30 <divid="pie">
31 <p>www.railsymas.com</p>
32 </div>
33
34 </div>
35
36 </body>
</html:html>

http://www.railsymas.com

100

TUTORIALFRAMEWORKSTRUTS

necesitamosincorporarelarchivodepropiedades,paradisplaytag,

Losdatosquesemuestranpuedencambiar,dejarmenosesposible
alpasarlapgina

enlacarpetasrcsecopiaelficherodepropiedadesen
castellano

_es_zonageogrficaejemploes_AR,es_MXetc.
elactionalquellamalatablaensuatributouri,configuradoenelstrutsconfig.xml
1 <action
2 path="/mostrarlistadodisplaytag"
3 forward="/pages/mostrarlistadodisplaytag.jsp"/>

http://www.railsymas.com

101

TUTORIALFRAMEWORKSTRUTS

DESARROLLOWEBUPLOADFILESTRUTS

Ejemploparasubirunarchivozipmediantestruts

formbean,sedeclaraelnombredelformulariobeancomouploadFormenatributo
typesedeclaralarutadelaclasebean
1 <!elformbeansolamentenecesitaelnameyeltype>
2 <formbeanname="uploadForm"
3 type="formularios.Formularioupload"/>

Enelarchivodeconfiguracindelstrutsconfig.xmlenlasecciondeactionsmediante
elatributopathindicamosquestrutsrespondaanteunaaccinuploadfileconla
pginaubicadaen/pages/formularioloadfile.jspencargadademostrarunformulario
parasubirelarchivo
1
2 <actionpath="/uploadfile"
3 forward="/pages/formulariouploadfile.jsp">
4 </action>
5
6 <action
7 path="/subirarchivo"
8 type="acciones.SubirArchivo"
9 scope="request"
10 name="uploadForm"
11 validate="true"
12 input="/pages/formulariouploadfile.jsp">
13
14 <forwardname="subido"path="/pages/mostrarInformacion.jsp"/>
15 </action>

Sisesubielarchivowebcorrectamenteserealizaunreenvioalapgina
mostrarinformacinparaindicarunmensajedeconfirmacinalusuario,encaso
http://www.railsymas.com

102

TUTORIALFRAMEWORKSTRUTS

contrariomedianteelatributoinputseindicaquelapropiapginajspdesubidadel
archivomuestreporpantallaelmensajecorrespondientesegnelerrorcometido
CDIGODELACLASESUBIRARCHIVO
packageacciones;
1
2 importorg.apache.struts.action.Action;
3 importjavax.servlet.http.HttpServletRequest;
4 importjavax.servlet.http.HttpServletResponse;
5 importorg.apache.struts.action.ActionForm;
6 importorg.apache.struts.action.ActionForward;
7 importorg.apache.struts.action.ActionMapping;
8 importorg.apache.struts.upload.FormFile;
9 importformularios.Formularioupload;
10 importjava.io.FileOutputStream;
11 importjava.io.File;
12
13
14
15 publicclassSubirArchivoextendsAction{
16
privateActionForwardenvio;
17
18
19
publicActionForwardexecute(ActionMappingmapping,ActionFormform,
20
21 HttpServletRequestrequest,HttpServletResponseresponse)throwsException
{

22

FormulariouploadformularioSubido=(Formularioupload)form;
23

FileOutputStreamfileoutputstream=null;
24
25

try
26

{
27

FormFilefichero=formularioSubido.getFichero();
28

Stringruta=
29
30 this.getServlet().getServletContext().getRealPath("/upload/")+fichero.getFileName();

fileoutputstream=newFileOutputStream(newFile(ruta));
31

fileoutputstream.write(fichero.getFileData());
32
33

}
34
finally

35

{
36

if(fileoutputstream!=null)
37

{
38

fileoutputstream.close();
39

}
40

}
41

returnmapping.findForward("subido");
42
}
43
44
45
}

http://www.railsymas.com

103

TUTORIALFRAMEWORKSTRUTS

CDIGODELAPGINAJSPENCARGADADEMOSTRARELFORMULARIODESUBIDA
DEARCHIVO
<%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
1
<%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
2
<%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3
<!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
4
"http://www.w3.org/TR/html4/loose.dtd">
5
<html:html>
6
<head>
7
<html:base/>
8
<metahttpequiv="ContentType"content="text/html;charset=UTF8">
9
<title><bean:messagekey="uploadfile.titulo"/></title>
10
<linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
11
</head>
12
<body>
13
<divid="contenedor">
14

15
<h2><bean:messagekey="uploadfile.titulo"/></h2>
16

17
<divid="errores">
18
<html:errors/>
19
</div>
20

21
<divid="contenido">
22

23
<divid="imagen">
24
<html:imgsrcKey="uploadfile.imagen"altKey="uploadfile.imagen.alt"/>
25
</div>
26

27
<html:formmethod="post"action="/subirarchivo"enctype="multipart/formdata">
28

29
<divid="campo">
30

31
<bean:messagekey="uploadfile.fichero"/>
32

33

34
<html:fileproperty="fichero"/>
35

36
<br/>
37

38
<html:submitstyleClass="boton"value="enviar"/>
39

40
</div>
41

42
</html:form>
43
</div>
44
<divid="pie">
45
<p>www.railsymas.com</p>
46
</div>
47

48
</div>
49
</body>
50
</html:html>

http://www.railsymas.com

104

TUTORIALFRAMEWORKSTRUTS

ENELFICHERODEPROPIEDADES
1 #uploadfile
2 uploadfile.titulo=formulariouploadfile
3 uploadfile.fichero=introduceelficheroasubir
4 uploadfile.imagen=../imagenes/subirarchivo.png
5 uploadfile.imagen.alt=imagenarchivo
6 error.fichero.vacio=elficheroestavac&iacute;o
7 error.fichero.tipo=elarchivonoesdetipozip
8 error.fichero.tamanio=erroreltamaoexcedelopermitido
9 uploadfile.resultado=formulariosubido

CLASEBEANPARAELFORMULARIO
1 packageformularios;
2
3 importorg.apache.struts.action.ActionForm;
4 importorg.apache.struts.upload.FormFile;
5 importorg.apache.struts.action.ActionErrors;
6 importjavax.servlet.http.HttpServletRequest;
7 importorg.apache.struts.action.ActionMapping;
8 importorg.apache.struts.action.ActionMessage;
9
10 publicclassFormulariouploadextendsActionForm{
11
staticfinallongserialVersionUID=1L;
12
13
privateFormFilefichero;
14
privateStringinformacion;
15
16
publicStringgetInformacion(){
17

returninformacion;
18
}
19
20
publicvoidsetInformacion(Stringinformacion){
21
this.informacion=informacion;

22
}
23
24
publicFormFilegetFichero(){
25

returnfichero;
26
}
27
28
publicvoidsetFichero(FormFilefichero){
29

this.fichero=fichero;
30
}
31
32
33
publicActionErrorsvalidate(ActionMappingmapping,HttpServletRequestrequest)
34
{
35
36

ActionErrorserrores=newActionErrors();
37
38

//yaestasubidomiramossiesdeltipoindicado
39

if(fichero.getFileSize()==0)
40

{
41

//estavaco
42

errores.add("fichero",newActionMessage("error.fichero.vacio"));
43

http://www.railsymas.com

105

TUTORIALFRAMEWORKSTRUTS

44

45

else
46

{
47
48

if(!fichero.getContentType().equals("application/xzipcompressed"))
49

{
50

errores.add("fichero",newActionMessage("error.fichero.tipo"));
51

System.out.print(fichero.getContentType());
52

}
53
54

else
55

{
56

if(fichero.getFileSize()>2000000)
57

{
58

errores.add("fichero",new
59
60 ActionMessage("error.fichero.tamanio"));

}
61
62

}
63
64

}
65
66

returnerrores;
67
}
68
69
70
}

Situacinenlaquehemosdadoalbotndeenviarsinhaberseleccionadounarchivo

Errordeformatodearchivo

http://www.railsymas.com

106

TUTORIALFRAMEWORKSTRUTS

Situacinelarchivo,stieneelformatozipperonoshemosexcedidodetamao
soportadoporlaaplicacin

Situacinenlaquehemosenviadocorrectamenteelarchivo

Paracomprobarelficherosubidoalproyectodesplegamoslaaplicacinenelservidor
tomcatmedianteunwardelproyecto

http://www.railsymas.com

107

TUTORIALFRAMEWORKSTRUTS

DESARROLLOWEBMLTIPLESARCHIVOSDECONFIGURACINSTRUTS

Enestepostveremoscomocreardiferentesarchivosdeconfiguracinparael
frameworkstruts.
Estamosconlaversin1.3.10destrutsysellevanmostradosdiferentesejemplos
sobreesteframework.siemprealahoradeactivaruncomponentedestrutstenamos
queiralarchivodeconfiguracin,llegaelmomentoenqueestearchivode
configuracinestasobrecargadodelneasdecdigo.

Enesteejemplointervienenlosdosarchivosdeconfiguracin,declaracindeuna
accinenelarchivodeconfiguracindestrutsconfig.xmldenominada
multiconfiguracinyseproduceelreenvioalapginaenlaceprivado.jsp
1 <action
2 path="/multiconfiguracion"
3 forward="/pages/enlaceprivado.jsp"/>

CDIGODELAPGINAENLACEPRIVADO
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
3 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <html:base/>
9 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
10 <title><bean:messagekey="enlaceprivado.titulo"/></title>
11 <linkrel="stylesheet"type="text/css"href="../css/estilo.css"/>
12 </head>
13 <body>
14 <divid="contenedor">
15 <divid="contenido">
16
17 <divid="campo">
18 <html:linkaction="/config2">Zonaprivada</html:link>
19 </div>
20
21 </div>
22 <divid="pie">
23 <p>www.railsymas.com</p>
24 </div>
25 </div>

http://www.railsymas.com

108

TUTORIALFRAMEWORKSTRUTS

26</body>
</html:html>

Enesapginajspexisteunenlacequeactivalaaccinconfig2queapareceenel
ficherodeconfiguracinstrutsconfig2.xml
Enlaceimagen

Sedeclaraenstrutsconfig2.xmlunbeandinmicollamadoformularioprivadocondos
camposdetipostring,yunaaccinprivado,quevasertratadadesdestruts
config2.xml
1 <formbeans>
2
3 <formbeanname="formularioprivado"type="org.apache.struts.validator.DynaValidatorForm">
4 <formpropertyname="usuario"type="java.lang.String"/>
5 <formpropertyname="clave"type="java.lang.String"/>
6
7 </formbean>
8
9 </formbeans>
10
11 <actionmappings>
12
13 <action
14 path="/config2"
15 forward="/pages/privado.jsp"/>
16
17
18 <action
19 path="/privado"
20 type="acciones.Privado"
21 name="formularioprivado"
22 input="/pages/privado.jsp"
23 validate="true"
24 >
25 <forwardname="satisfactorio"path="/pages/satisfactorio.jsp"/>
26 <forwardname="error"path="/pages/cancelada2.jsp"/>
27 </action>

visualizacindelapginaprivadodondesemuestraunformulariodeusuario,

http://www.railsymas.com

109

TUTORIALFRAMEWORKSTRUTS

ENELFICHEROWEB.XMLDELPROYECTO
1 <!StandardActionServletConfiguration>
2 <servlet>
3 <servletname>action</servletname>
4 <servletclass>org.apache.struts.action.ActionServlet</servletclass>
5 <initparam>
6 <paramname>config</paramname>
7 <paramvalue>/WEBINF/strutsconfig.xml,/WEBINF/strutsconfig2.xml</paramvalue>
8 </initparam>
9 <loadonstartup>2</loadonstartup>
10 </servlet>

http://www.railsymas.com

110

TUTORIALFRAMEWORKSTRUTS

DESARROLLOWEBCOMODINESSTRUTS

Seguimosconeltutorialdestruts
Pginajspconvariosejemplosdeutilizacindecomodines(wildcard)

Creamosunficherodeconfiguracinstrutsespecficoparaelejemploylointegramos
enelficherodescriptordedespliegueenstrutsconfigWildcard.xml
<!StandardAction ServletConfiguration>
1
<servlet>
2
<servletname>action</servletname>
3
<servletclass>org.apache.struts.action.ActionServlet</servletclass>
4
<initparam>
5
<paramname>config</paramname>
6
<paramvalue>/WEBINF/strutsconfig.xml,/WEBINF/strutsconfig2.xml,/WEBINF/struts
7
configWildcard.xml</paramvalue>
8
</initparam>
9
<loadonstartup>2</loadonstartup>
10
</servlet>

CONFIGURACINDELARCHIVOSTRUTSCONFIGWILDCARD.XML
1 strutsconfig>
2
3 <!sepuedeaplicaralos>
4 <actionmappings>
5 <actionpath="/enlaces"forward="/pages/enlaces.jsp"/>
6 <actionpath="/Primero*"forward="/pages/Wildcard/Paginap1.jsp"/>
7 <actionpath="/*segundo"forward="/pages/Wildcard/{1}.jsp"/>
8 </actionmappings>
9
10
11 </strutsconfig>

http://www.railsymas.com

111

TUTORIALFRAMEWORKSTRUTS

CDIGODEENLACES.JSP
<%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
1
<%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
2
<%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
3
<!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
4
"http://www.w3.org/TR/html4/loose.dtd">
5
<html>
6
<head>
7
<metahttpequiv="ContentType"content="text/html;charset=UTF8">
8
<title><bean:messagekey="wildcard.enlace.titulo"/></title>
9
<html:base/>
10
<linkrel="stylesheet"href="../css/estilo.css"type="text/css"/>
11
</head>
12
<body>
13
<divid="contenedor">
14

15

<h2>Enlaces</h2>
16
<divid="contenido">
17

18
<divid="campo">
19
<html:linkaction="PrimeroPaginap1">primerop&aacute;ginap1</html:link>
20
</div>
21

22
<divid="campo">
23
<html:linkaction="Paginap1segundo">p&aacute;ginap1segundo</html:link>
24
</div>
25

26
<divid="campo">
27
<html:linkaction="Paginap2segundo">primerap&aacute;ginap2</html:link>
28
</div>
29

30
</div>
31
<divid="pie">
32
<p>www.railsymas.com</p>
33
</div>
34
</div>
35
</body>
36
</html>

Laspginasjspsonsimples,notienenninguncdigoespecial
PGINA1JSP

http://www.railsymas.com

112

TUTORIALFRAMEWORKSTRUTS

PGINA2JSP

http://www.railsymas.com

113

TUTORIALFRAMEWORKSTRUTS

CREACINDEUNPLUGINCONSTRUTSXMLDOM

Tutorialdestrutsparalacreacindeunpluginenstruts
Strutsnospermitelacreacindepluginspropios,enlosdiferentespostutilizabamos
pluginsstandardcomostrutsvalidatorystrutstiles.Perotambinsepuedencrear
pluginsamedidadenuestrasnecesidades
Tenemosunficheroxml,dondetenemosunaestructuraunelementonodoraiz
llamadoplantillayunaseriedenodoshijosllamadosobrero,cadaelementohijo
constadeunatributonombreydoselementossubhijoscargoyedad
1 <?xmlversion="1.0" encoding="UTF8"?>
2 <plantilla>
3 <obreronombre="pepe">
4 <cargo>pen</cargo>
5 <edad>25</edad>
6 </obrero>
7 <obreronombre="juan">
8 <cargo>capataz</cargo>
9 <edad>46</edad>
10 </obrero>
11 <obreronombre="maria">
12 <cargo>pintor</cargo>
13 <edad>38</edad>
14 </obrero>
15 </plantilla>

Esteficheroxmllodenominamosplantillas.xmlyserelficheroqueleaelpluginde
struts.
Paralacreacindelplugindebemosdedeclararloenelficherostrutsconfig.xml
1 <!===============================================PlugInsConfiguration>
2 <pluginclassName="acciones.PluginEjemplo">
3
4 <setpropertyproperty="direccion"value="/WEBINF/plantilla.xml"/>
5
6
7 </plugin>

Porunladotenemoselnombreeldelaclasedelplugin,enelvalordelatributo
classNameyporotroelvalordelapropiedaddireccinenelqueindicamoslarutaala
direccindelficheroxml
LaclasequeimplementalainterfacePlugin,debeimplementarlosmtodosinity
destroy,sisepasanparmetrosenladeclaracindelpluginenestecasodireccincon
elvalordelarutaalficheroparapoderasignarvaloryrecuperardesdelaclasedel
pluginesnecesariocrearmtodosgetterysetter

http://www.railsymas.com

114

TUTORIALFRAMEWORKSTRUTS

Elrestodelosmtodossonlosencargadosdeleerelficheroxml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

packageacciones;

importjava.io.File;
importjava.io.IOException;

importjavax.servlet.ServletContext;

importjavax.servlet.ServletException;
importorg.apache.struts.action.PlugIn;
importorg.apache.struts.action.ActionServlet;
importorg.apache.struts.config.ModuleConfig;
importjavax.xml.parsers.DocumentBuilderFactory;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
importorg.w3c.dom.Node;
importorg.w3c.dom.NodeList;
importorg.xml.sax.SAXException;

importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.ParserConfigurationException;
importvo.Obrero;
importjava.util.ArrayList;

publicclassPluginEjemploimplementsPlugIn
{

privatestaticfinalStringnombreclase=PluginEjemplo.class.getName();

privateStringdireccion;

privateDocumentdocumento;

privatestaticArrayList<Obrero>listadoObreros=newArrayList<Obrero>();

publicStringgetDireccion(){

returndireccion;

publicvoidsetDireccion(Stringdireccion){

this.direccion=direccion;

publicvoidinit(ActionServletservlet,ModuleConfigconfig)throwsServletException

ServletContextcontexto=servlet.getServletContext();

System.out.println(nombreclase+"direccion:"+getDireccion());

http://www.railsymas.com

115

TUTORIALFRAMEWORKSTRUTS

55

PluginEjemplopluginejemplo= new PluginEjemplo();


56
57

leerXml(getDireccion(),servlet);
58
59

contexto.setAttribute(nombreclase,pluginejemplo);
60
61
62
}
63
64
65
publicvoidleerXml(Stringdireccion,ActionServletservlet)
66
{
67

DocumentBuilderFactoryfactoria=DocumentBuilderFactory.newInstance();
68
69

try
70

{
71 DocumentBuilderconstructor=factoria.newDocumentBuilder();
72 ServletContextcontexto=servlet.getServletContext();
73 Stringlugar=contexto.getRealPath(direccion);
74
75
76 documento=constructor.parse(newFile(lugar));
77 documento.getDocumentElement().normalize();
78
79 Nodenodoraiz=documento.getDocumentElement();
80 newArrayList<Obrero>();
81
82 System.out.println(nodoraiz.getNodeName());
83
84 nodos(documento);
85
86

}
87

catch(ParserConfigurationExceptionex)
88

{
89

System.out.println("nosepuedecrearelDomparser:"+ex);
90

}
91
92

catch(SAXExceptionex)
93

{
94

System.out.print("GenerarSaxexcepcin:"+ex);
95

}
96

catch(IOExceptionex)
97

{
98

System.out.print("Ioexcepcin:"+ex);
99

}
100
101
102
}
103
104
105
privatevoidnodos(Documentdocumento)
106
{
107
108 NodeListlistadenodos=documento.getElementsByTagName("obrero");
109
110

http://www.railsymas.com

116

TUTORIALFRAMEWORKSTRUTS

111 for(inti=0;i< listadenodos.getLength() ; i++)


112 {
113
Nodenodo=listadenodos.item(i);
114
115
Obreroobrero=newObrero();
116
117
if(nodo.getNodeType()==Node.ELEMENT_NODE)
118
{
119

Elementelemento=(Element)nodo;
120
121

obrero.setNombre(elemento.getAttribute("nombre"));
122
123

obrero.setCargo(getValor("cargo",elemento));
124

obrero.setEdad(Integer.parseInt(getValor("edad",elemento)));
125
126
}
127
128
listadoObreros.add(obrero);
129
130
131 }
132 }
133
134 privateStringgetValor(Stringcadenatag,Elementelemento)
135 {
NodeListlistado=
136
137 elemento.getElementsByTagName(cadenatag).item(0).getChildNodes();
Nodenodo=listado.item(0);
138
139
returnnodo.getNodeValue();
140
141 }
142
143
144 publicstaticArrayList<Obrero>getListado()
145 {
returnlistadoObreros;
146
147 }
148
149
publicvoiddestroy()
150
{
151

System.out.println("Findelplugin");
152
}
153
154
}

CLASEOBRERO
1
2
3
4
5
6
7
8
9

packagevo;

publicclassObrero{

privateStringnombre;

privateintedad;

privateStringcargo;

publicStringgetNombre(){

http://www.railsymas.com

117

TUTORIALFRAMEWORKSTRUTS

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 }

returnnombre;
}
publicvoidsetNombre(Stringnombre){

this.nombre=nombre;
}
publicintgetEdad(){

returnedad;
}
publicvoidsetEdad(intedad){

this.edad=edad;
}
publicStringgetCargo(){

returncargo;
}
publicvoidsetCargo(Stringcargo){

this.cargo=cargo;
}

CONFIGURACINDELACTIONENSTRUTSCONFIG.XML
1 <action
2
3 path="/crearplugin"
4 type="acciones.AccionRecogerObreros">
5
6 <forwardname="satisfactorio"path="/pages/listadoobreros.jsp"/>
7
8
9
10 </action>

Resultadofinal

http://www.railsymas.com

118

TUTORIALFRAMEWORKSTRUTS

INTEGRACINSTRUTSHIBERNATE

Enesteejemploseinsertauntuplaenlabasededatoscreada,conlosdatos
introducidosmedianteunformulariorellenadoporelusuario
Tenemoslatablalibrosdelabasededatoslibros_jdbc,talcomovieneenesteejemplo
basededatos.Tenemosunatablalibrospertenecientesalabasedatoscontres
camposeltitulo,autorylatemticadellibro.
Paraesteejemplonecesitamosparaunmejorentendimientonecesitamosconocer
comosecreaunpluginyaqutenemosunohechocreacindeplugin
Formularioderecogidadedatos

esteformumarioestaasociadoaunaaccinrecogidaenelficherodeconfiguracinde
strutselstrutsconfig.xml
1 <action
2
3 path="/formularioHibernate"
4 type="acciones.AccionHibernateLibro"
5 scope="request"
6 name="hibernatelibro"
7 validate="true"
8 input="/pages/formulariohibernate.jsp"
9 >
10 <setpropertyproperty="cancellable"value="true"/>
11 <forwardname="listado"path="/pages/listadohibernate.jsp"/>
12 <forwardname="cancelada"path="/pages/cancelada2.jsp"/>
13 </action>

Sehaexplicadoenotrospostanteriorescadaunodeloselementosqueaparecenen
estaconfiguracin,peroamododerecordatorio,seenumeranlosvaloresdelos
diferentescampos.Paraelpathtenemoselnombredelaaccinqueseejecutaeneste
http://www.railsymas.com

119

TUTORIALFRAMEWORKSTRUTS

caso(formulariohibernate),estaaccinestarecogidaenunaclase
(AccionHibernateLibro)queeslaencargadadeevaluaryprocesarlosdatos,elname
hacereferenciaalbeanenestecasodinmicoencargadoderecogerlosdatosdel
formulario(hibernatelibro).
Cdigodelbeandinmicoencargadoderecogerlosdatosdelformulario,parapoder
sertratadosporlaclase(AccinHibernateLibro)
1 <formbeanname="hibernatelibro"type="org.apache.struts.validator.DynaValidatorForm">
2 <formpropertyname="titulo"type="java.lang.String"/>
3 <formpropertyname="tematica"type="java.lang.String"/>
4 <formpropertyname="autor"type="java.lang.String"/>
5 </formbean>

Cdigodelformularioformulariohibernate.jspcorrespondientealaimagenanterior
1 <%@pagelanguage="java"contentType="text/html;charset=UTF8" pageEncoding="UTF8"%>
2 <%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
3 <%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
4 <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN"
5 "http://www.w3.org/TR/html4/loose.dtd">
6 <html:html>
7 <head>
8 <html:base/>
9 <metahttpequiv="ContentType"content="text/html;charset=UTF8">
10 <linkrel="stylesheet"href="../css/estilo.css"type="text/css"/>
11 <title><bean:messagekey="titulo.hibernate"/></title>
12 </head>
13 <body>
14 <divid="contenedor">
15 <h2><bean:messagekey="titulo.hibernate"/></h2>
16 <divid="errores">
17 <html:errors/>
18 </div>
19
20 <divid="imagen">
21 <html:imgsrcKey="libro.imagen"titleKey="libro.imagen.alt"/>
22 </div>
23
24 <divid="contenido">
25
26 <html:formmethod="post"action="formularioHibernate"styleId="formulario"focus="titulo">
27
28 <divclass="campo">
29
30 <bean:messagekey="formulariodatasource.titulolibro"/>
31
32 <html:textproperty="titulo"/>
33
34 </div>
35
36 <divclass="campo">
37
38 <bean:messagekey="formulariodatasource.autor"/>

http://www.railsymas.com

120

TUTORIALFRAMEWORKSTRUTS

39
40 <html:textproperty="autor"/>
41
42 </div>
43
44 <divclass="campo">
45
46 <bean:messagekey="formulariodatasource.tematica"/>
47
48 <html:textproperty="tematica"/>
49
50 </div>
51
52 <html:submitstyleClass="boton"value="enviar"/>
53 <html:cancelstyleClass="boton"value="cancelar"/>
54 <html:resetstyleClass="boton"value="borrar"/>
55
56
57 </html:form>
58
59 </div>
60
61 <divid="pie">
62 <p>www.railsymas.com</p>
63 </div>
64
65 </div>
66 </body>
</html:html>

configuracindelpluginenelficherostrutsconfig.xml,creamosunpluginindicandola
claseHibernatePluginylapropiedaddireccinconelvalordelarutadelficherode
configuracindehibernate
1 <!==========Hibernate=======>
2
3
4 <pluginclassName="configuracion.plugin.HibernatePlugin">
5
6 <setpropertyproperty="direccion"value="/hibernate.cfg.xml"/>
7
8 </plugin>

paracargarelficherodeconfiguracindehibernatecreamosunplugin,comorepaso
tenemosqueextenderdelaclasePluginysobreescribimoslosmtodosdestroyeinit.
Secreaporcomodidadunavariableestticadelaclasellamadaclave_hibernateque
nospermitirrecogerlafactoriadehibernateparapoderinsertar,borrar,editaretc..
1
2
3
4
5
6

packageconfiguracion.plugin;

importjavax.servlet.ServletContext;
importjavax.servlet.ServletException;
importorg.hibernate.SessionFactory;
importorg.hibernate.cfg.Configuration;

http://www.railsymas.com

121

TUTORIALFRAMEWORKSTRUTS

7 importorg.apache.struts.action.ActionServlet;
8 importorg.apache.struts.action.PlugIn;
9 importorg.apache.struts.config.ModuleConfig;
10 importorg.hibernate.HibernateException;
11
12
13 publicclassHibernatePluginimplementsPlugIn
14 {
15
privateStringdireccion;
16
17
18
19 publicstaticfinalStringclave_hibernate="Hibernate";
20
21 privateSessionFactoryfactoria=null;
22
23
24 publicStringgetDireccion(){

returndireccion;
25
}
26
27
28 publicvoidsetDireccion(Stringdireccion){

this.direccion=direccion;
29
}
30
31
32 publicvoiddestroy(){
33 try
34 {
35 factoria.close();
36 }
37 catch(HibernateExceptione)
38 {
39 System.out.println("Nosepuedecerrarlasesin:"+e.getMessage());
40 }
41
42 }
43
44
45
46 publicvoidinit(ActionServletservlet,ModuleConfigconfig)throwsServletException
47 {
48 Configurationconfiguration=null;
49
50 ServletContextcontexto=null;
51
52 try{
53
54 contexto=servlet.getServletContext();
55 configuration=(newConfiguration()).configure(direccion);
56 factoria=configuration.buildSessionFactory();
57
58 contexto.setAttribute(clave_hibernate,factoria);
59
60 }catch(HibernateExceptione){
61 System.out.println("Errordeinicializacindehibernate:"+e.getMessage());
62 }

http://www.railsymas.com

122

TUTORIALFRAMEWORKSTRUTS

63
64
65 }
66
67
68 }

cdigodelaclaseencargadaderecogerlaaccin,estaclasecomosolamenterealiza
unaaccinextendemosdeactionyeditamoselmtodoejecute.Estaclaseesla
encargadaderecogerlosdatosdelformularioascomodelautilizacinderecuperar
elmanejadordelafactoria.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

packageacciones;

importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionMapping;

importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.ServletContext;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.validator.DynaValidatorForm;
importorg.apache.struts.action.ActionForward;

importconfiguracion.plugin.HibernatePlugin;

importorg.hibernate.SessionFactory;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
importorg.hibernate.TransactionException;
importmodelos.*;
importjava.util.List;
importjava.util.Iterator;

publicclassAccionHibernateLibroextendsAction{

privateActionForwardreenvio=null;

privateDynaValidatorFormformulario=null;

privateSessionsesion=null;

privateSessionFactoryfactory=null;

privateTransactiontransaction=null;

publicActionForwardexecute(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)throwsException

formulario=(DynaValidatorForm)form;

if(isCancelled(request))

http://www.railsymas.com

123

TUTORIALFRAMEWORKSTRUTS

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

reenvio=mapping.findForward("cancelada");

else

ServletContextcontext=request.getSession().getServletContext();

factory=(SessionFactory)
context.getAttribute(HibernatePlugin.clave_hibernate);

sesion=factory.openSession();

try

transaction=sesion.beginTransaction();

Libroslibro=newLibros();

//introducimoslosvaloresparaellibronuevo

libro.setTitulo(formulario.getString("titulo"));

libro.setAutor(formulario.getString("autor"));

libro.setTematica(formulario.getString("tematica"));

sesion.save(libro);

transaction.commit();

transaction=sesion.beginTransaction();

List<Libros>libros=sesion.createQuery("from
Libros").list();

for(Iterator<Libros>iterador=libros.iterator();
iterador.hasNext();)

libro=(Libros)iterador.next();

System.out.println("titulo:"+libro.getTitulo());

System.out.println("autor:"+libro.getAutor());

System.out.println("tematica:"+libro.getTematica());

transaction.commit();

request.setAttribute("libros",libros);

reenvio=mapping.findForward("listado");

catch(TransactionExceptione)

http://www.railsymas.com

124

TUTORIALFRAMEWORKSTRUTS

100
101

102 anteriores
103

104

105
106

107

108

109

110

111
112

113
114

//abortamoslatransaccinyrestauramoslosvalores

transaction.rollback();
e.printStackTrace();

}
finally
{

//cerramoslasesin
sesion.close();

}
returnreenvio;

ARCHIVODECONFIGURACINHIBERNATE.CFG,XML
<?xmlversion="1.0" encoding="UTF8"?>
1
<!DOCTYPEhibernateconfigurationPUBLIC
2

"//Hibernate/HibernateConfigurationDTD3.0//EN"
3

"http://hibernate.sourceforge.net/hibernateconfiguration3.0.dtd">
4
<hibernateconfiguration>
5
<sessionfactory>
6
<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
7
<propertyname="hibernate.connection.username">root</property>
8
<propertyname="hibernate.connection.password">root</property>
9
<propertyname="hibernate.connection.url">
10
jdbc:mysql://localhost:3306/libros_jdbc</property>
11
<propertyname="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
12
<propertyname="hibernate.hbm2ddl.auto">update</property>
13

14
<propertyname="show_sql">true</property>
15
<propertyname="format_sql">true</property>
16

17
<mappingresource="modelos/Libros.hbm.xml"/>
18

19
</sessionfactory>
20
</hibernateconfiguration>

sobrelosparmetrosrecogidosenelficherohibernate.cfg.xmlsecomentaronenel
posthibernatetools
Paraelmapeodelastablastenemosquecrearunarchivoxmlconextensionhbm.xml.
estosarchivoslospodemosponerenunpackagepropioporenesteejemplomodelo
haciendoreferenciaalaslasclasesyficherosdeconfiguracinasociadosalastablasde
labasededatos.

http://www.railsymas.com

125

TUTORIALFRAMEWORKSTRUTS

Alejecutarlaaplicacinsenoscreaautomticamenteunaclasebeanconlos
propiedadesindicadasenlosficheroshbm.xml,enestecasounaclaseLibro
Paracrearunficherohbmvamosconlavistahibernatedeeclipseactivadaanew,
hibernatexmlmappingcreamosunficherolibros.hbm.xml
1 <?xmlversion="1.0"?>
2 <!DOCTYPEhibernatemappingPUBLIC"//Hibernate/HibernateMappingDTD3.0//EN"
3 "http://hibernate.sourceforge.net/hibernatemapping3.0.dtd">
4 <!Generated26ene20101:33:06byHibernateTools3.2.4.GA>
5 <hibernatemapping>
6 <classname="modelos.Libros"table="libros"catalog="libros_jdbc">
7 <idname="id"type="java.lang.Integer">
8 <columnname="id"/>
9 <generatorclass="identity"/>
10 </id>
11 <propertyname="titulo"type="string">
12 <columnname="titulo"length="50"notnull="true"/>
13 </property>
14 <propertyname="autor"type="string">
15 <columnname="autor"length="50"notnull="true"/>
16 </property>
17 <propertyname="tematica"type="string">
18 <columnname="tematica"length="50"notnull="true"/>
19 </property>
20 </class>
21 </hibernatemapping>

Valoresdelosparmetros,tablehacereferenciaalatabladelabasededatos,catalog
hacereferenciaalabasededatos,elprimerparametroidindicamosqueelcampoes
laclaveprimaria,losatributospropertyindicamoselnombredelapropiedadyaque
campodelatablacorrespondeesdecirpodemostenerelcampotituloenlatablayen
lapropiedadtitu_xpordeciralgo,entocesalahoradeusarporcdigoelobjetode
mapeoharamosobjeto.titu_xperoporcomodidadledamoselmismovalorquela
tablaasesmsfcilacordorsedelaspropiedades.
Imagendellistadodellibrounavezguardadolosdatos

http://www.railsymas.com

126

TUTORIALFRAMEWORKSTRUTS

Salidaporpantallaparaverificarlainsercincomoconsecuenciadeactivarenel
ficherohibernate.cfg.xmlelparmetroshow_sqlyformat_sql
1 INFO:Tilesdefinitionfactoryfoundforrequestprocessor''.
2 Hibernate:
3 insert
4 into
5 libros_jdbc.libros
6 (titulo,autor,tematica)
7 values
8 (?,?,?)
9 Hibernate:
10 select
11 libros0_.idasid0_,
12 libros0_.tituloastitulo0_,
13 libros0_.autorasautor0_,
14 libros0_.tematicaastematica0_
15 from
16 libros_jdbc.libroslibros0_
17 titulo:titulo3
18 autor:autor3
19 tematica:tematica3

http://www.railsymas.com

127

Vous aimerez peut-être aussi