سؤال

New to struts2 and ran into a question and need clarification. Hope the experts to help me a bit

I am writing a beginners struts program using tags, i am using tag prefix 's' I have created JSP page where you can upload a file, I have logic to check if the file is present or if its null based on the input I display accordingly. When no file is uploaded, I put the user of a retry.jsp page with ERROR MSG: "You have not selected any file, please select a file and try upload" and I have button with value="Go back to upload page" the following is the logic I have in my retry.jsp:

<s:form action="Goback" method="post">
<s:submit value="Go back to upload page"/>
</s:form>

So would like to know if there is any way to call the "Goback" action with out using form and by just using a button.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top