如何通过AJAX调用处理JSP中的servlet响应?

时间:2011-06-08 12:45:26

标签: ajax json jsp servlets gson

我想通过ajax调用在我的JSP页面中显示servlet响应(作为超链接)。谁能告诉我如何在jsp页面中显示内容?如果我以正确的方式做到这一点,我也不太确定。我的servlet类或Ajax.js中可能存在一些错误。我还在学习阶段。这是我的代码片段:

JSP页面

<script type="text/javascript"> var AJAX_SERVLET="<%=renderResponse.encodeURL(renderRequest.getContextPath())%>/ajaxServlet"; </script> <label for="push">Push to start</label> <button dojoType="dijit.form.Button" style="width: 4em" type="button" name="submitButton" value="Submit" onclick="ajaxFunction()"></button>

Ajax.js

function ajaxFunction() {
    if (xmlhttp) {
    xmlhttp.open("GET", AJAX_SERVLET, true); //AJAX_SERVLET has the servlet path
    xmlhttp.onreadystatechange = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type',
            'application/x-www-form-urlencoded');
    xmlhttp.send(null);
}

}

function handleServerResponse() { if (xmlhttp.readyState == 4) { //alert(xmlhttp.status); if (xmlhttp.status == 200) { var resultContent =httpRequest.getResponseHeader("Content-Type");
} else { alert("Error during AJAX call. Please try again"); } }

getter / setter方法

public class SearchResponse {

private String productNumber;
private String productType;
private String funcDesignation;}

Servlet类

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    List result = new ArrayList();
    result.add(new SearchResponse("001", "User Manual", "Operator"));
    response.setContentType("application/json");         
    response.setCharacterEncoding("UTF-8");        
    response.getWriter().write(new Gson().toJson(result));
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    doPost(request, response);
}

0 个答案:

没有答案