未在Servlet上调用POST方法-GWT项目 [英] POST method not called on servlet - GWT project

查看:50
本文介绍了未在Servlet上调用POST方法-GWT项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个servlet来处理上传的文件并将其存储在服务器上.

I have this servlet to handle uploaded file and to store them on server.

public class ImageService extends HttpServlet {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private static final long MAX_FILE_SIZE = 1024 * 1024 * 1024; // 1GB

@Override
protected void doPost(final HttpServletRequest request,
        final HttpServletResponse response) {

    slog("SERVLET STARTED");

    List<String> files = new ArrayList<String>();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        slog("REQUEST IS MULTIPART");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/html");

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        try {
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {

                FileItem item = iterator.next();

                if (!item.isFormField()) {
                    String fileName = item.getName();
                    slog("TROVATO FILE " + item.getName());
                    String root = getServletContext().getRealPath("/");
                    File path = new File(root + "/fileuploads");
                    slog("SALVO FILE IN " + path.getAbsolutePath());
                    if (!path.exists()) {
                        path.mkdirs();
                    }

                    File uploadedFile = creaFileNonAmbiguo(path, fileName);
                    slog("NOME ASSEGNATO AL FILE " + uploadedFile.getName());
                    item.write(uploadedFile);
                    response.getWriter()
                            .write(uploadedFile.getName() + ";");
                    files.add(uploadedFile.getName());
                }
            }

            response.getWriter().flush();
            slog("RISPOSTA INVIATA");

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

        }
    } else {
        slog("LA RICHIESTA NON E' MULTIPART");
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
    slog("SERVLET TERMINATA");
}

@Override
protected void doGet(final HttpServletRequest request,
        final HttpServletResponse response) {

    response.setContentType("image/jpeg");
    String root = getServletContext().getRealPath("/").concat(
            "fileuploads/");
    String path = root.concat(request.getParameter("src"));

    File file = new File(path);
    response.setContentLength((int) file.length());
    FileInputStream in;
    try {
        in = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (IOException e) {

        e.printStackTrace();
    }

}

private File creaFileNonAmbiguo(File path, String fileName) {

    File res = new File(path + "/" + fileName);
    if (!res.exists())
        return res;
    else {
        return creaFileNonAmbiguo(path, "c".concat(fileName));
    }
}

private void slog(String s) {
    System.out.println("UPLOAD SERVLET: " + s);
}

}

您可以看到servlet具有doPost和doGet.在我的代码的这一部分中正确调用了doGet():

As you can see the servlet has doPost and doGet. doGet() is correctly called in this part of my code:

[...]
String path = GWT.getModuleBaseURL() + "imageUpload?src=";

    for (String foto : result) {
        String url = path.concat(foto);
[...]

但是,从我的Chrome调试器和从未记录过SERVLET STARTED的事实中可以看出,从未调用过doPost方法.

But the doPost method is never called, as I can see from the Chrome debugger and from the fact that SERVLET STARTED is never logged.

这是我从客户端调用doPost()方法的方式:

This is the way I call the doPost() method from client:

inserisciSegnalazioneBtn.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {

            if (!catLst.isEnabled()
                    || catLst.getItemText(catLst.getSelectedIndex())
                            .equals("")
                    || catLst.getItemText(catLst.getSelectedIndex())
                            .equals("")
                    || descrizioneBox.getText().equals("")
                    || gsb.getText().equals("")) {
                Window.alert("ATTENZIONE: devi riempire tutti i campi");
                return;
            }

            segnalazione.setCategoria(new Categoria(catLst.getItemText(catLst
                    .getSelectedIndex())));
            segnalazione.setDescrizione(descrizioneBox.getText());
            segnalazione.setIndirizzo(gsb.getText());
            segnalazione.setUtente(LoginPanel.username);

            Segnalazioni_Degrado.dataLayerService.inserisciSegnalazione(
                    segnalazione, new AsyncCallback<Boolean>() {

                        @Override
                        public void onFailure(Throwable caught) {
                            caught.printStackTrace();
                        }

                        @Override
                        public void onSuccess(Boolean result) {
                            if (result) {
                                geocode(segnalazione);
                                uploadFrm.submit();
                                Window.alert("Inserimento avvenuto con successo");
                                MenuPanel.refreshBtn.click();
                            } else
                                Window.alert("L'inserimento ha avuto esito negativo");
                            thisPnl.hide();
                        }

                    });

        }

    });

    uploadFrm.setAction(GWT.getModuleBaseURL() + "imageUpload");
    uploadFrm.setEncoding(FormPanel.ENCODING_MULTIPART);
    uploadFrm.setMethod(FormPanel.METHOD_POST);

    uploadFrm
            .addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

                @Override
                public void onSubmitComplete(SubmitCompleteEvent event) {
                    Window.alert("SUBMIT COMPLETATO");
                    String res = event.getResults();
                    if (res != null && !res.equals("")) {
                        Window.alert("IL SERVER RISPONDE " + res.toString());
                        String[] uploadedFiles = res.split(";");
                        aggiornaFotoDB(uploadedFiles, segnalazione);
                    }
                }
            });

奇怪的是,它可以在DevMode上正常工作,但是当我将Web应用程序部署到Tomcat时却无法工作. 我的代码有什么问题?

The weird thing is that it works properly on DevMode, but it doesn't work when I deploy my webapp to Tomcat. What's wrong with my code?

推荐答案

原来是问题所在

thisPnl.hide();

解决方案是将面板隐藏在SubmitCompleteHandler

The solution was to hide the panel INSIDE the SubmitCompleteHandler

这篇关于未在Servlet上调用POST方法-GWT项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆