如何使用Servlets和Ajax?


如何使用Servlets和Ajax?


纯文本形式返回

创建/some.jsp如下所示(注意:代码不希望将JSP文件放在子文件夹中,如果这样做,请相应地更改servlet URL):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4112686</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                    $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                });
            });
        </script>
    </head>
    <body>
        <button id="somebutton">press here</button>
        <div id="somediv"></div>
    </body>
</html>

使用如下所示的doGet()方法创建一个servlet :

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}

将此servlet映射到URL模式/someservlet/someservlet/*如下所示(显然,URL模式可供您自由选择,但您需要相应地更改someservletJS代码示例中的URL):

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    // ...
}

或者,当您还没有使用Servlet 3.0兼容容器(Tomcat 7,Glassfish 3,JBoss AS 6等等或更新版本)时,请以web.xml旧式方式映射它(另请参阅我们的Servlets维基页面):

<servlet>
    <servlet-name>someservlet</servlet-name>
    <servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>someservlet</servlet-name>
    <url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>

现在在浏览器中打开http:// localhost:8080 / context / test.jsp并按下按钮。您将看到div的内容使用servlet响应进行更新。

List以JSON身份返回

使用JSON而不是明文作为响应格式,您甚至可以进一步采取措施。它允许更多动态。首先,您希望有一个工具来转换Java对象和JSON字符串。它们也有很多(请参阅本页底部的概述)。我个人最喜欢的是Google Gson。下载并将其JAR文件放在/WEB-INF/libwebapplication的文件夹中。

这是一个显示List<String>为的示例<ul><li>。servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

JS代码:

$(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, item) { // Iterate over the JSON array.
            $("<li>").text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
        });
    });
});

请注意,responseJson当您将响应内容类型设置为时,jQuery会自动将响应解析为JSON,并直接为您提供JSON对象()作为函数参数application/json。如果你忘了设置它或者依赖于默认值text/plainor text/html,那么responseJson参数不会给你一个JSON对象,而是一个简单的香草字符串,然后你需要手动摆弄JSON.parse(),这样你就完全没必要了。首先将内容类型设置为正确。

Map<String, String>以JSON身份返回

这是另一个显示Map<String, String><option>

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> options = new LinkedHashMap<>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    String json = new Gson().toJson(options);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

和JSP:

$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
        $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
        $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
            $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
        });
    });
});

<select id="someselect"></select>

List以JSON身份返回

下面是其中显示的示例List<Product><table>其中Product类具有的属性Long id,String name和BigDecimal price。servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();
    String json = new Gson().toJson(products);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

JS代码:

$(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
            $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
        });
    });
});

List以XML格式返回

这是一个与前一个示例有效相同的示例,但后来使用XML而不是JSON。当使用JSP作为XML输出生成器时,您会发现对表和所有表进行编码并不那么繁琐。JSTL这种方式更有用,因为您可以实际使用它来迭代结果并执行服务器端数据格式化。servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();

    request.setAttribute("products", products);
    request.getRequestDispatcher("/WEB-INF/xml/products.jsp").forward(request, response);
}

JSP代码(注意:如果你把它<table>放在一个<jsp:include>,它可以在非ajax响应的其他地方重用):

<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
    <table>
        <c:forEach items="${products}" var="product">
            <tr>
                <td>${product.id}</td>
                <td><c:out value="${product.name}" /></td>
                <td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
            </tr>
        </c:forEach>
    </table>
</data>

JS代码:

$(document).on("click", "#somebutton", function() {             // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseXml) {                // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response XML...
        $("#somediv").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
    });
});

您现在可能已经意识到为什么XML比使用Ajax更新HTML文档的特定目的更强大。JSON很有趣,但毕竟通常只对所谓的“公共Web服务”有用。像JSF这样的MVC框架使用XML来实现他们的ajax魔术。

对现有表单进行Ajax化

您可以使用jQuery $.serialize()轻松地对现有的POST表单进行ajax,而无需摆弄收集和传递单个表单输入参数。假设一个现有的表单在没有JavaScript / jQuery的情况下工作得很好(因此当最终用户禁用JavaScript时会优雅地降级):

<form id="someform" action="someservlet" method="post">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <input type="text" name="baz" />
    <input type="submit" name="submit" value="Submit" />
</form>

您可以使用ajax逐步增强它,如下所示:

$(document).on("submit", "#someform", function(event) {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(response) {
        // ...
    });

    event.preventDefault(); // Important! Prevents submitting the form.
});

您可以在servlet中区分正常请求和ajax请求,如下所示:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    String baz = request.getParameter("baz");

    boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

    // ...

    if (ajax) {
        // Handle ajax (JSON or XML) response.
    } else {
        // Handle regular (JSP) response.
    }
}

的jQuery的表格插件确实更少或更多的与上述相同的jQuery例子,但它具有用于附加透明支持multipart/form-data所要求的文件上传形式。

手动向servlet发送请求参数

如果您根本没有表单,但只想与“在后台”的servlet进行交互,您希望POST一些数据,那么您可以使用jQuery $.param()轻松地将JSON对象转换为URL编码请求参数。

var params = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.post("someservlet", $.param(params), function(response) {
    // ...
});

doPost()可以重复使用与上面所示相同的方法。请注意,上面的语法也适用$.get()于jQuery和doGet()servlet。

手动将JSON对象发送到servlet

不过,若你打算发送JSON对象作为一个整体,而不是作为单独的请求参数出于某种原因,那么你就需要使用到它序列化到一个字符串JSON.stringify()(不是jQuery的部分),并指示jQuery来请求内容类型设置为application/json代替(默认)application/x-www-form-urlencoded。这不能通过$.post()便利功能来完成,但需要通过$.ajax()以下方式完成。

var data = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.ajax({
    type: "POST",
    url: "someservlet",
    contentType: "application/json", // NOT dataType!
    data: JSON.stringify(data),
    success: function(response) {
        // ...
    }
});

请注意,很多初学者都会混contentType在一起dataType。该contentType表示的类型请求体。的dataType表示(预期)类型的反应体,这通常是不必要的,因为已经jQuery的自动检测它基于响应的Content-Type报头中。

然后,为了处理servlet中的JSON对象,该对象不作为单独的请求参数发送,而是以上述方式作为整个JSON字符串发送,您只需要使用JSON工具手动解析请求体,而不是使用getParameter()通常的办法。也就是说,servlet不支持application/json格式化请求,只支持application/x-www-form-urlencoded或multipart/form-data格式化请求。Gson还支持将JSON字符串解析为JSON对象。

JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
String foo = data.get("foo").getAsString();
String bar = data.get("bar").getAsString();
String baz = data.get("baz").getAsString();
// ...

请注意,这一切都比使用更笨拙$.param()。通常,您只想JSON.stringify()在目标服务是例如JAX-RS(RESTful)服务时使用,该服务由于某种原因仅能够使用JSON字符串而不是常规请求参数。

从servlet发送重定向

重要的是认识和理解的是,任何sendRedirect()和forward()由servlet调用上一个Ajax请求只转发或重定向Ajax请求本身,而不是主文档/窗口,Ajax请求的发源地。在这种情况下,JavaScript / jQuery仅responseText在回调函数中将重定向/转发的响应检索为变量。如果它代表整个HTML页面而不是特定于ajax的XML或JSON响应,那么您所能做的就是用它替换当前文档。

document.open();
document.write(responseText);
document.close();

请注意,这不会更改最终用户在浏览器地址栏中看到的URL。因此,可书籍性存在问题。因此,最好只返回JavaScript / jQuery的“指令”来执行重定向,而不是返回重定向页面的整个内容。例如,通过返回布尔值或URL。

String redirectURL = "http://example.com";

Map<String, String> data = new HashMap<>();
data.put("redirect", redirectURL);
String json = new Gson().toJson(data);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
function(responseJson) {
    if (responseJson.redirect) {
        window.location = responseJson.redirect;
        return;
    }

    // ...
}