首页 文章

如何使用Servlets和Ajax?

提问于
浏览
302

我是Web应用程序和Servlet的新手,我有以下问题:

每当我在servlet中打印一些东西并通过webbrowser调用它时,它就会返回一个包含该文本的新页面 . 有没有办法使用Ajax在当前页面中打印文本?

7 回答

  • 517

    实际上,关键字是"ajax":异步JavaScript和XML . 然而,去年它不仅仅是Asynchronous JavaScript和JSON . 基本上,您让JS执行异步HTTP请求并根据响应数据更新HTML DOM树 .

    由于它可以在所有浏览器(尤其是Internet Explorer与其他浏览器)之间工作,因此有很多JavaScript库可以简化这一功能,并且可以涵盖尽可能多的浏览器特定的错误/怪癖 . ,例如jQueryPrototypeMootools . 由于jQuery最受欢迎,我将在下面的例子中使用它 .

    Kickoff示例将String作为纯文本返回

    像下面一样创建 /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映射到 /someservlet/someservlet/* 的URL模式,如下所示(显然,URL模式可供您自由选择,但您需要在相应的所有位置更改JS代码示例中的 someservlet URL):

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

    或者,当您还没有使用Servlet 3.0兼容容器(Tomcat 7,Glassfish 3,JBoss AS 6等等或更新版本)时,请以旧式方式将其映射到_1723563中(另请参阅our Servlets wiki page):

    <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 <String>作为JSON返回

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

    这是一个将 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>.
            });
        });
    });
    

    请注意,当您将响应内容类型设置为 application/json 时,jQuery会自动将响应解析为JSON,并直接为您提供JSON对象( responseJson )作为函数参数 . 如果您忘记设置它或依赖于 text/plaintext/html 的默认值,那么之后 responseJson 参数将不需要手动摆弄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>
    

    将列表<Entity>作为JSON返回

    这是一个在 <table> 中显示 List<Product> 的示例,其中 Product 类具有 Long idString nameBigDecimal 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>.
            });
        });
    });
    

    将列表<Entity>作为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很有趣,但毕竟一般只对所谓的"public web services"有用 . 像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 Form plugin与上面的jQuery示例相比更少或更多,但它根据文件上传的要求对 multipart/form-data 表单提供了额外的透明支持 .

    手动向servlet发送请求参数

    如果你不想发布一些数据,那么你可以使用jQuery $.param()轻松地将JSON对象转换为URL编码的查询字符串 .

    var params = {
        foo: "fooValue",
        bar: "barValue",
        baz: "bazValue"
    };
    
    $.post("someservlet", $.param(params), function(response) {
        // ...
    });
    

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

    手动将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) {
            // ...
        }
    });
    

    请注意,很多初学者将 contentTypedataType 混在一起 . contentType 表示 request 正文的类型 . dataType 表示 response 正文的(预期)类型,这通常是不必要的,因为jQuery已根据响应的 Content-Type 标头自动检测它 .

    然后,为了处理servlet中的JSON对象,该对象不作为单独的请求参数发送,而是作为整个JSON字符串以上述方式发送,您只需要使用JSON工具手动解析请求体,而不是使用 getParameter() 通常的方式 . 即,servlet不支持 application/json 格式化的请求,但仅支持 application/x-www-form-urlencodedmultipart/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发送重定向

    要实现和理解的重要一点是,servlet对ajax请求的任何 sendRedirect()forward() 调用只会转发或重定向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;
        }
    
        // ...
    }
    

    另见:

  • 6

    更新当前显示在用户浏览器中的页面(无需重新加载)的正确方法是在浏览器中执行一些代码更新页面的DOM .

    该代码通常是嵌入HTML页面或从HTML页面链接的javascript,因此是AJAX建议 . (事实上,如果我们假设更新的文本是通过HTTP请求来自服务器的,那么这就是经典的AJAX . )

    也可以使用一些浏览器插件或附加组件来实现这种事情,尽管插件可能很难进入浏览器的数据结构来更新DOM . (本机代码插件通常会写入页面中嵌入的某些图形框架 . )

  • 11

    我将向您展示一个servlet的完整示例以及ajax如何调用 .

    在这里,我们将创建一个使用servlet创建登录表单的简单示例 .

    index.html

    <form>  
       Name:<input type="text" name="username"/>

    Password:<input type="password" name="userpass"/>

    <input type="button" value="login"/> </form>

    Here is ajax Sample

    $.ajax
            ({
                type: "POST",           
                data: 'LoginServlet='+name+'&name='+type+'&pass='+password,
                url: url,
            success:function(content)
            {
                    $('#center').html(content);           
                }           
            });
    

    LoginServlet Servlet Code :-

    package abc.servlet;
    
    import java.io.File;
    
    
    public class AuthenticationServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
        {   
            doPost(request, response);
        }
    
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
    
            try{
            HttpSession session = request.getSession();
            String username = request.getParameter("name");
            String password = request.getParameter("pass");
    
                    /// Your Code
    out.println("sucess / failer")
            } catch (Exception ex) {
                // System.err.println("Initial SessionFactory creation failed.");
                ex.printStackTrace();
                System.exit(0);
            } 
        }
    }
    
  • 4
    $.ajax({
    type: "POST",
    url: "url to hit on servelet",
    data:   JSON.stringify(json),
    dataType: "json",
    success: function(response){
        // we have the response
        if(response.status == "SUCCESS"){
            $('#info').html("Info  has been added to the list successfully.<br>"+
            "The  Details are as follws : <br> Name : ");
    
        }else{
            $('#info').html("Sorry, there is some thing wrong with the data provided.");
        }
    },
     error: function(e){
       alert('Error: ' + e);
     }
    });
    
  • 13

    Ajax(也是AJAX)是Asynchronous JavaScript和XML的首字母缩写,是一组在客户端用于创建异步Web应用程序的相互关联的Web开发技术 . 使用Ajax,Web应用程序可以异步向服务器发送数据和从中检索数据 . 下面是示例代码:

    jsp页面java脚本函数用两个提交数据到servlet变量firstName和lastName:

    function onChangeSubmitCallWebServiceAJAX()
        {
          createXmlHttpRequest();
          var firstName=document.getElementById("firstName").value;
          var lastName=document.getElementById("lastName").value;
          xmlHttp.open("GET","/AJAXServletCallSample/AjaxServlet?firstName="
          +firstName+"&lastName="+lastName,true)
          xmlHttp.onreadystatechange=handleStateChange;
          xmlHttp.send(null);
    
        }
    

    用于读取数据的Servlet以xml格式发送回jsp(您也可以使用文本 . 只需要将响应内容更改为文本并在javascript函数上呈现数据 . )

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
    
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write("<details>");
        response.getWriter().write("<firstName>"+firstName+"</firstName>");
        response.getWriter().write("<lastName>"+lastName+"</lastName>");
        response.getWriter().write("</details>");
    }
    
  • 3

    通常,您无法从servlet更新页面 . 客户端(浏览器)必须请求更新 . Eiter客户端加载一个全新的页面,或者它请求更新现有页面的一部分 . 这种技术称为Ajax .

  • 6

    使用bootstrap多选

    Ajax

    function() { $.ajax({
        type : "get",
        url : "OperatorController",
        data : "input=" + $('#province').val(),
        success : function(msg) {
        var arrayOfObjects = eval(msg); 
        $("#operators").multiselect('dataprovider',
        arrayOfObjects);
        // $('#output').append(obj);
        },
        dataType : 'text'
        });}
    }
    

    In Servlet

    request.getParameter("input")
    

相关问题