从java Servlet方法doGet将数据返回给ajax

时间:2014-02-26 13:32:01

标签: java jquery ajax jsp servlets

我有这样的功能ajax:

$.ajax({
        url: "associer_type_flux", // It's  my servlet
        dataType : "xml",
        type : "GET",
        data : { },
        success: function(response){
            alert("fine");
        },
        error:  function(data, status, er){
            alert(data+"_"+status+"_"+er);
        }
    });

我的方法在我的servlet中执行如下操作:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String forward = ""; 
    try {           
        String fluxXML = "";
        ServicesCodeTypeFluxGlobaux servicesCodeTypeFluxGlobaux = new ServicesCodeTypeFluxGlobauxImpl();

            fluxXML = "<lescodetypeflux>";

            fluxXML += "</lescodetypeflux>";
            PrintWriter printWriter  = response.getWriter();
            printWriter.println(fluxXML);

        }
        forward = "/associerCode/accueil_association.jsp";
        getServletContext().getRequestDispatcher(forward).forward(request, response);           
    }
    catch (Exception e) {
        forward = "/erreur.jsp";
        request.setAttribute("msg", e.getMessage());
    }       
}

所以我的问题是,我无法在我的jsp中获取数据..但我不知道如何获取此数据或从doGet方法返回此数据..现在我有一个警告错误..

Thx

1 个答案:

答案 0 :(得分:0)

一些建议让它发挥作用 -

  1. 不要忘记在你的情况下设置mime类型“text / xml”或“application / xml”

  2. 你不能同时使用out.println()和requestdispatcher,因为它会抛出异常。 out.println()将在响应正文中打印该值,但请求调度程序会将您重定向到其他页面,并且您将获得的是您重定向的页面的整个内容。

  3. 所以在你的情况下你应该只使用out.println()

    所以你的最终代码应该是这样的 -

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/xml");
        String forward = ""; 
        try {           
            String fluxXML = "";
            ServicesCodeTypeFluxGlobaux servicesCodeTypeFluxGlobaux = new ServicesCodeTypeFluxGlobauxImpl();
    
                fluxXML = "<lescodetypeflux>";
    
                fluxXML += "</lescodetypeflux>";
                PrintWriter printWriter  = response.getWriter();
                printWriter.println(fluxXML);
                printWriter.close();
            }        
        }
        catch (Exception e) {
            //print xml with error value
        }       
    }