Struts 2 / Foundation 5 – Clase ModelDriven y carga de archivos

Soy nuevo en la progtwigción de Java y estoy tratando de crear una página web básica con formulario, etc. para realizar un pedido. Decidí usar Struts 2 después de asistir a un par de sesiones en el trabajo. También usé zurb Foundation 5 para una interfaz de usuario sensible. Pude crear una página web HTML y un formulario con campos de texto, etc. y en el envío del formulario, los correos electrónicos se envían al cliente y al propietario del sitio con los datos del formulario.

Ahora estoy tratando de agregar la funcionalidad de carga de archivos al formulario. El problema al que me enfrento es que la carga del archivo se realizó correctamente, pero los otros datos del formulario no se están completando y se eliminan en el correo electrónico.

Por favor encuentre el código a continuación.

Contenido web / WEB-INF / https://stackoverflow.com/questions/24884568/struts-2-foundation-5-modeldriven-class-and-file-upload/submitAssign.html

             
slide 1 slide 1


Please enter a valid phone number
Only alphabets are allowed
Only alphabets are allowed
Please enter a number value
Please enter a number value
Please enter a valid date



$(document).foundation(); $('#assign-form') .on('invalid.fndtn.abide', function () { var invalid_fields = $(this).find('[data-invalid]'); console.log(invalid_fields); }) .on('valid.fndtn.abide', function () { $('#date'). console.log('valid!'); });

struts.xml

        image/jpeg,image/png,image/gif 4194304   submitSuccess.html submitError.html    

SubmitAssignment.java

 package com.assignupload.actions; import java.io.File; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import com.assignupload.pojo.AssignmentInfo; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class SubmitAssignment extends ActionSupport implements ModelDriven, ServletRequestAware { private File[] assignUpload; private String[] assignUploadFileName; private String[] assignUploadContentType; AssignmentInfo assignInfo = new AssignmentInfo(); @Override public Object getModel() { return assignInfo; } @Override public String execute() throws Exception { System.out.println(assignInfo); ServletContext servletContext = ServletActionContext.getServletContext(); String dataDir = servletContext.getRealPath("/WEB-INF"); for (int i = 0; i < assignUpload.length; i++){ File savedFile = new File(dataDir, assignUploadFileName[i]); assignUpload[i].renameTo(savedFile); } try{ SendOrderEmail sendEmail = new SendOrderEmail(assignInfo); sendEmail.sendEmail();} catch (Exception e){ e.printStackTrace(); return ERROR; } return SUCCESS; } public File[] getAssignUpload() { return assignUpload; } public void setAssignUpload(File[] assignUpload) { this.assignUpload = assignUpload; } public String[] getAssignUploadFileName() { return assignUploadFileName; } public void setAssignUploadFileName(String[] assignUploadFileName) { this.assignUploadFileName = assignUploadFileName; } public String[] getAssignUploadContentType() { return assignUploadContentType; } public void setAssignUploadContentType(String[] assignUploadContentType) { this.assignUploadContentType = assignUploadContentType; } @Override public void setServletRequest(HttpServletRequest arg0) { // TODO Auto-generated method stub } } 

AssignmentInfo.Java

 package com.assignupload.pojo; import java.io.File; public class AssignmentInfo { private String email; private Long phoneNum; private String custName; private String assignSubject; private int noOfPages; private int noOfWords; private String lastDate; private String descAssign; public AssignmentInfo() { // TODO Auto-generated constructor stub } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getPhoneNum() { return phoneNum; } public void setPhoneNum(Long phoneNum) { this.phoneNum = phoneNum; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getAssignSubject() { return assignSubject; } public void setAssignSubject(String assignSubject) { this.assignSubject = assignSubject; } public int getNoOfPages() { return noOfPages; } public void setNoOfPages(int noOfPages) { this.noOfPages = noOfPages; } public int getNoOfWords() { return noOfWords; } public void setNoOfWords(int noOfWords) { this.noOfWords = noOfWords; } public String getLastDate() { return lastDate; } public void setLastDate(String lastDate) { this.lastDate = lastDate; } public String getDescAssign() { return descAssign; } public void setDescAssign(String descAssign) { this.descAssign = descAssign; } @Override public String toString() { return "AssignmentInfo [email=" + email + ", phoneNum=" + phoneNum + ", custName=" + custName + ", assignSubject=" + assignSubject + ", noOfPages=" + noOfPages + ", noOfWords=" + noOfWords + ", lastDate=" + lastDate + ", descAssign=" + descAssign + "]"; } } 

Además del código anterior, tengo un archivo SendOrderEmail.java que está enviando los correos electrónicos con éxito.

Aquí está el registro de errores en eclipse.

 INFO 2014-07-22 14:27:04,351 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.Dispatcher - Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir DEBUG2014-07-22 14:27:04,351 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.Dispatcher - saveDir=C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\AssignmentUpload DEBUG2014-07-22 14:27:04,428 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item email DEBUG2014-07-22 14:27:04,428 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a normal form field DEBUG2014-07-22 14:27:04,429 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item phoneNum DEBUG2014-07-22 14:27:04,429 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a normal form field DEBUG2014-07-22 14:27:04,430 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item custName DEBUG2014-07-22 14:27:04,430 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a normal form field DEBUG2014-07-22 14:27:04,431 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item assignSubject DEBUG2014-07-22 14:27:04,431 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a normal form field DEBUG2014-07-22 14:27:04,432 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item noOfPages DEBUG2014-07-22 14:27:04,432 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a normal form field DEBUG2014-07-22 14:27:04,432 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item noOfWords DEBUG2014-07-22 14:27:04,432 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a normal form field DEBUG2014-07-22 14:27:04,433 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item lastDate DEBUG2014-07-22 14:27:04,433 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a normal form field DEBUG2014-07-22 14:27:04,434 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item descAssign DEBUG2014-07-22 14:27:04,434 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a normal form field DEBUG2014-07-22 14:27:04,434 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Found item assignUpload DEBUG2014-07-22 14:27:04,435 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Item is a file upload DEBUG2014-07-22 14:27:04,448 [http-bio-8080-exec-7] com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler - Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@1ac8b63], property=struts] DEBUG2014-07-22 14:27:04,457 [http-bio-8080-exec-7] com.opensymphony.xwork2.DefaultActionProxy - Creating an DefaultActionProxy for namespace [/] and action name [submitAssign] DEBUG2014-07-22 14:27:04,482 [http-bio-8080-exec-7] com.opensymphony.xwork2.interceptor.ParametersInterceptor - Setting params NONE DEBUG2014-07-22 14:27:04,482 [http-bio-8080-exec-7] com.opensymphony.xwork2.interceptor.ParametersInterceptor - Setting params assignUploadFileName => [ 1235962_10151872148662472_2018380961_n.jpg ] noOfWords => [ 1000 ] phoneNum => [ 919766759029 ] noOfPages => [ 4 ] email => [ xxxxxx@gmail.com ] descAssign => [ Image test 6 ] assignSubject => [ Astronomy ] lastDate => [ 2014-07-31 ] assignUpload => [ C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\AssignmentUpload\upload_1dec45bb_28eb_4942_9d60_566bc01b4d5d_00000008.tmp ] custName => [ XXXXX ] assignUploadContentType => [ image/jpeg ] DEBUG2014-07-22 14:27:04,486 [http-bio-8080-exec-7] com.opensymphony.xwork2.DefaultActionInvocation - Executing action method = null AssignmentInfo [email=null, phoneNum=null, custName=null, assignSubject=null, noOfPages=0, noOfWords=0, lastDate=null, descAssign=null] java.lang.NullPointerException at javax.mail.internet.InternetAddress.parse(InternetAddress.java:678) at javax.mail.internet.InternetAddress.parse(InternetAddress.java:638) at javax.mail.internet.InternetAddress.parse(InternetAddress.java:615) at com.assignupload.actions.SendOrderEmail.custEmail(SendOrderEmail.java:55) at com.assignupload.actions.SendOrderEmail.sendEmail(SendOrderEmail.java:41) at com.assignupload.actions.SubmitAssignment.execute(SubmitAssignment.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252) at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:325) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:434) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Email to customer was not sent! DEBUG2014-07-22 14:27:18,318 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.ServletDispatcherResult - Forwarding to location submitSuccess.html DEBUG2014-07-22 14:27:18,336 [http-bio-8080-exec-7] com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler - Entering nullPropertyValue [target=[com.assignupload.actions.SubmitAssignment@19d85cd, com.opensymphony.xwork2.DefaultTextProvider@1ac8b63], property=struts] DEBUG2014-07-22 14:27:18,356 [http-bio-8080-exec-7] com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler - Entering nullPropertyValue [target=[com.assignupload.actions.SubmitAssignment@19d85cd, com.opensymphony.xwork2.DefaultTextProvider@1ac8b63], property=struts] DEBUG2014-07-22 14:27:18,367 [http-bio-8080-exec-7] org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest - Removing file assignUpload name=1235962_10151872148662472_2018380961_n.jpg, StoreLocation=C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\AssignmentUpload\upload_1dec45bb_28eb_4942_9d60_566bc01b4d5d_00000008.tmp, size=96207 bytes, isFormField=false, FieldName=assignUpload 

¿Podría por favor guiarme en cuanto a por qué se eliminan los datos del formulario?

Su problema es que está definiendo una stack de interceptores incorrecta para su acción.

La predeterminada es la defaultStack predeterminada, mientras que la que usó después del Interceptor FileUpload es la basicStack .

Como puede ver en la documentación oficial , el basicStack no ModelDriven soporte ModelDriven . Cambia tu configuración de acción desde:

  image/jpeg,image/png,image/gif 4194304   

a :

  image/jpeg,image/png,image/gif 4194304   

o incluso mejor (para evitar usar el Interceptor FileUpload dos veces) para:

  image/jpeg,image/png,image/gif 4194304  

También considere usar tags Struts2 para generar el HTML (use simple tema simple para el control máximo del HTML generado, o XHTML , el predeterminado, para la máxima asistencia en la generación de HTML).

En muchas de las tags (las que tienen atributos dynamics permitidos: verdadero en la documentación), como , , etc., puede definir sus propios atributos , como el pattern HTML5, por ejemplo.

El HTML será más limpio y lo codificarás más rápido.