如何使用servlet和ajax?

vlurs2pr  于 2021-06-29  发布在  Java
关注(0)|答案(7)|浏览(261)

我对web应用和servlet非常陌生,我有以下问题:
每当我在servlet中打印一些内容并由webbrowser调用它时,它就会返回一个包含该文本的新页面。有没有一种方法可以使用ajax打印当前页面中的文本?

l5tcr1uw

l5tcr1uw1#

$.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);
 }
});
rqcrx0a6

rqcrx0a62#

更新当前显示在用户浏览器中的页面(无需重新加载)的正确方法是让浏览器中执行的一些代码更新页面的dom。
这段代码通常是嵌入在html页面中或从html页面链接的javascript,因此ajax建议(事实上,如果我们假设更新的文本通过http请求来自服务器,这就是经典的ajax。)
也可以使用一些浏览器插件或附加组件来实现这类功能,尽管插件要进入浏览器的数据结构来更新dom可能很棘手(本机代码插件通常会写入嵌入在页面中的某些图形框架。)

kcugc4gi

kcugc4gi3#

我将向您展示一个完整的servlet示例&ajax如何调用。
这里,我们将创建一个简单的示例来使用servlet创建登录表单。
索引.html

<form>  
   Name:<input type="text" name="username"/><br/><br/>  
   Password:<input type="password" name="userpass"/><br/><br/>  
   <input type="button" value="login"/>  
</form>

这里是ajax示例

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

loginservlet servlet代码:-

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);
        } 
    }
}
c6ubokkw

c6ubokkw4#

使用引导多重选择
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'
    });}
}

在servlet中

request.getParameter("input")
vybvopom

vybvopom5#

通常不能从servlet更新页面。客户端(浏览器)必须请求更新。eiter客户端加载一个全新的页面,或者请求对现有页面的一部分进行更新。这种技术称为ajax。

p8ekf7hl

p8ekf7hl6#

实际上,关键字是“ajax”:异步javascript和xml。然而,在过去的几年里,它更多的是异步javascript和json。基本上,让js执行一个异步http请求,并根据响应数据更新htmldom树。
由于让它在所有浏览器上运行是一项相当繁琐的工作(尤其是internet explorer与其他浏览器相比),因此有大量的javascript库可以在单个函数中简化这一点,并尽可能多地掩盖特定于浏览器的错误/怪癖,例如jquery、prototype、mootools。由于jquery现在最流行,我将在下面的示例中使用它。

以纯文本形式返回字符串的启动示例

创建 /some.jsp 如下所示(注意:这个答案中的代码片段并不期望jsp文件被放置在子文件夹中,如果这样做,请相应地从 "someservlet""${pageContext.request.contextPath}/someservlet" ; 为了简洁起见,代码片段中省略了它):

<!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() 方法如下:

@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.
}

将此servletMap到 /someservlet 或者 /someservlet/* 如下所示(显然,url模式可以自由选择,但是您需要更改 someservlet url在js代码示例中的所有位置):

package com.example;

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

或者,当您还没有使用与Servlet3.0兼容的容器(Tomcat7、GlassFish3、JBossAS6等或更新版本)时,请将其Map到 web.xml 老式的方式(另请参见我们的servlets wiki页面):

<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字符串之间进行转换。它们也有很多(请参阅本页底部的概述)。我个人最喜欢的是googlegson。下载并将其jar文件放入 /WEB-INF/lib Web应用程序的文件夹。
下面是一个显示 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>.
        });
    });
});

请注意,jquery会自动将响应解析为json,并直接向您提供一个json对象( responseJson )将响应内容类型设置为 application/json . 如果您忘记设置或依赖默认值 text/plain 或者 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>.
        });
    });
});

将列表返回为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".
    });
});

到现在为止,您可能已经意识到,对于使用ajax更新html文档的特定用途,xml为什么比json强大得多。json很有趣,但毕竟通常只对所谓的“公共web服务”有用。像jsf这样的mvc框架在其ajax魔力的掩护下使用xml。

对现有形式进行轴化

您可以使用jquery $.serialize() 轻松地Ajaxifyingexistingpost表单,而不必费心收集和传递单个表单输入参数。假设一个现有的表单在没有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交互,以便发布一些数据,那么可以使用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) {
        // ...
    }
});

请注意,很多开胃菜混合在一起 contentTypedataType . 这个 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执行重定向的“指令”比返回重定向页面的全部内容要好得多。e、 通过返回布尔值或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;
    }

    // ...
}

另请参见:

调用servlet并从javascript调用java代码以及参数
访问javascript中的java/servlet/jsp/jstl/el变量
如何在基于ajax的网站和基本html网站之间轻松切换?
如何使用jsp/servlet和ajax将文件上传到服务器?

nnt7mjpx

nnt7mjpx7#

ajax(也称ajax)是异步javascript和xml的缩写,是一组相互关联的web开发技术,用于在客户端创建异步web应用程序。使用ajax,web应用程序可以向服务器异步发送数据并从中检索数据,下面是示例代码:
jsp页面java脚本函数,用于将数据提交到具有两个变量firstname和lastname的servlet:

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>");
}

相关问题