如何推迟doPost方法?

时间:2015-06-15 21:20:57

标签: java servlets

在我的servlet中,我将文件上传到特定的URL,然后调用另一个类中的方法来在线获取该文件并进行更改。问题是,很多时候,文件中有大量数据,并且在文件完全更改之前,dopost方法完成(并从上传文件提交表单转到下一页)。如何在文件完全更改之前阻止do post方法进入下一页?

我希望Test.preFirstMethod()在页面重新加载并完成下载链接之前完成。 Test.preFirstMethod()接收一个excel文件,并使用来自互联网的动态内容对其进行修改。

public class Uploads extends HttpServlet {
private Object lock1 = new Object();
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
public Thread tt = new Thread(new Runnable() {
    public void run()
    {
        try {Test.preFirstMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

int BUFFER_LENGTH = 4096;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    String fileName="";
    for (Part part : request.getParts()) {
        InputStream is = request.getPart(part.getName()).getInputStream();
        fileName = getFileName(part);
        File f2 = new File(fileName);
        FileOutputStream os = new FileOutputStream(System.getenv("OPENSHIFT_DATA_DIR") + "nn.xlsx");
        byte[] bytes = new byte[BUFFER_LENGTH];
        int read = 0;
        while ((read = is.read(bytes, 0, BUFFER_LENGTH)) != -1) {
            os.write(bytes, 0, read);
        }
        os.flush();
        is.close();
        fileName=fileName.substring(0,fileName.lastIndexOf("."))+"_ZillowAdded.xlsx";
        try {
            tt.start();
            try { tt.join(); } catch (InterruptedException e) {
                e.printStackTrace();
            }           
            InputStream is2 = new FileInputStream(f2);
            FileOutputStream os2 = new FileOutputStream(System.getenv("OPENSHIFT_DATA_DIR") + fileName);
            while ((read = is2.read(bytes, 0, BUFFER_LENGTH)) != -1) {
                os2.write(bytes, 0, read);
            }
            os2.flush();
            is2.close();
            os2.close();

        } catch(Exception e) {e.printStackTrace();}
        os.close();
    }

    if(!ServletFileUpload.isMultipartContent(request)){
        throw new ServletException("Content type is not multipart/form-data");
    }

    response.setContentType("text/html");
    out.write("<html><head></head><body>");
    out.write("File "+fileName.substring(0,fileName.indexOf("_Zillow"))+ " uploaded successfully.");
    out.write("<br>");
    out.write("<a href=\"/uploads/"+fileName+"\">Download "+fileName+"</a>");
    out.write("</body></html>"); }

0 个答案:

没有答案