You can use an anchor (<s:a>
) or a button triggering a javascript function to make a POST or a GET without using a <form>
.
BTW in your case I would step back a bit and rethink the logic:
you can put your requirement (a file must be uploaded) in Struts2 validation, so that when a form will be posted without a file, it will return an INPUT
result from the ValidationInterceptor, instead of reaching the Action (and returning SUCCESS
after executing the method), going back to the same page (or to another, if required, but generally it is not), and notifying the error to user through an automatic populated fieldError
.
You can do it in XML, with Annotations or with pure Java in the validate()
method.
Follow the example (when no result is specified, SUCCESS is used):
Struts.xml
<action name="SourceAction" class="xxx.yyy.SourceAction">
<result>source.jsp</result>
</action>
<action name="TargetAction" class="xxx.yyy.TargetAction">
<result>target.jsp</result>
<result name="input">source.jsp</result>
</action>
Source Action
public class SourceAction extends ActionSupport
public String execute(){
return SUCCESS;
}
}
Source JSP
<s:form action="targetAction" enctype="multipart/form-data" />
<s:file name="file" />
<s:fielderror fieldName="file" />
<s:submit value="Start the upload" />
</s:form>
Target Action
public class TargetAction extends ActionSupport implements Validateable{
private File file;
private String fileContentType;
private String fileFileName;
/* Getters and setters */
public String execute() {
return SUCCESS;
}
public void validate() {
if (file==null){
addFieldError("file","File is mandatory !! Please Retry");
}
}
/* when fieldErrors are added, INPUT result will be returned */
}
Target JSP
File <s:property value="fileFileName"/> successfully loaded.
You need to use the default InterceptorStack or ensure to have at least the Params, Upload, Workflow, Parameters, Validate Interceptors.