struts2文件使用ajax在同一页面上传成功消息

时间:2014-09-17 06:13:27

标签: java javascript ajax jsp struts2

我正在上传.csv文件并在同一页面上重定向,我想在同一页面上显示文件上传成功消息。我不想使用ajax发送请求。我是struts框架I的新手#39;已经完成了许多文件上传教程,但每个人都重定向到不同的页面并在那里显示消息。

2 个答案:

答案 0 :(得分:1)

上传后(如果有错误),请发送您来自的相同页面:

struts.xml中

    <action name="uploadPage" class="foo.bar.UploadAction">
        <result>/upload.jsp</result>
        <result name="input">/upload.jsp</result>
        <result name="error">/upload.jsp</result>
    </action>
    <action name="doUpload"   class="foo.bar.UploadAction" method="upload">
        <result>/upload.jsp</result>
        <result name="input">/upload.jsp</result>
        <result name="error">/upload.jsp</result>
    </action>

UploadAction

    public class UploadAction extends ActionSupport {       
        File   upload;
        String uploadFileName;
        String uploadContentType;       
        /* Getters and Setters for the above properties */

        public String execute() {
            return SUCCESS;
        }

        public String upload(){             
            try {
                getService().upload(upload,uploadFileName,uploadContentType);
                addActionMessage("Upload successfully completed");
                return SUCCESS;
            } catch (Exception e){
                addActionError("Error while uploading: " + e.getMessage());
                return ERROR;
            }
        }
    }

upload.jsp

<body>
    <s:if test="hasActionErrors()">
        <s:actionerror />
    </s:if>
    <s:if test="hasActionMessages()">
        <s:actionmessage />    
    </s:if>

    <s:form action="doUpload" enctype="multipart/form-data">
        <s:file name="upload" />
        <s:submit />
    <s:form>
</body>

这是基本的,然后您可能想要更改URL或使用Post Redirect Get或Tokens等..以防止用户在刷新时重新提交文件。

答案 1 :(得分:1)

使用

在您的操作中设置ActionError(如果文件不符合您的条件)
     addActionError("file not uploaded something went wrong");

否则设置动作消息

     addActionMessage("Upload successfully completed");

jsp页面。

<body>
    <s:actionerror />
    <s:actionmessage />    

 <s:form action="uploadAction" >
    <s:file name="filename" /> 
    <s:submit />
 <s:form>
</body>