Java 如何使用 Servlet 和 Ajax?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4112686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Servlets and Ajax?
提问by Amir Rachum
I'm very new to web apps and Servlets and I have the following question:
我对 Web 应用程序和 Servlet 很陌生,我有以下问题:
Whenever I print something inside the servlet and call it by the webbrowser, it returns a new page containing that text. Is there a way to print the text in the current page using Ajax?
每当我在 servlet 中打印某些内容并由网络浏览器调用它时,它都会返回一个包含该文本的新页面。有没有办法使用 Ajax 打印当前页面中的文本?
采纳答案by BalusC
Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.
事实上,关键字是“ajax”:异步 JavaScript 和 XML。然而,去年它比异步 JavaScript 和 JSON更常见。基本上,您让 JS 执行异步 HTTP 请求并根据响应数据更新 HTML DOM 树。
Since it's pretty a tediouswork to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of JavaScript libraries out which simplifies this in single functions and covers as many as possible browser-specific bugs/quirks under the hoods, such as jQuery, Prototype, Mootools. Since jQuery is most popular these days, I'll use it in the below examples.
由于让它在所有浏览器(尤其是 Internet Explorer 与其他浏览器)上工作是一项相当乏味的工作,因此有大量 JavaScript 库可以在单个函数中简化这一点,并涵盖尽可能多的特定于浏览器的错误/怪癖,例如jQuery、Prototype、Mootools。由于 jQuery 现在最流行,我将在下面的示例中使用它。
Kickoff example returning String
as plain text
String
以纯文本形式返回的启动示例
Create a /some.jsp
like below (note: the code doesn't expect the JSP file being placed in a subfolder, if you do so, alter servlet URL accordingly):
创建/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>
Create a servlet with a doGet()
method which look like this:
使用如下所示的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.
}
Map this servlet on an URL pattern of /someservlet
or /someservlet/*
as below (obviously, the URL pattern is free to your choice, but you'd need to alter the someservlet
URL in JS code examples over all place accordingly):
将此 servlet 映射到/someservlet
或/someservlet/*
如下所示的 URL 模式上(显然,URL 模式由您自由选择,但您需要相应地更改someservlet
JS 代码示例中的URL):
@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
// ...
}
Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in web.xml
the old fashioned way (see also our Servlets wiki page):
或者,如果您还没有使用 Servlet 3.0 兼容容器(Tomcat 7、Glassfish 3、JBoss AS 6 等或更新版本),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>
Now open the http://localhost:8080/context/test.jspin the browser and press the button. You'll see that the content of the div get updated with the servlet response.
现在在浏览器中打开http://localhost:8080/context/test.jsp并按下按钮。您将看到 div 的内容随着 servlet 响应而更新。
Returning List<String>
as JSON
List<String>
以 JSON 形式返回
With JSONinstead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this pagefor an overview). My personal favourite is Google Gson. Download and put its JAR file in /WEB-INF/lib
folder of your webapplication.
使用JSON而不是纯文本作为响应格式,您甚至可以更进一步。它允许更多的动态。首先,您需要一个工具来在 Java 对象和 JSON 字符串之间进行转换。也有很多(有关概述,请参阅本页底部)。我个人最喜欢的是Google Gson。下载并将其 JAR 文件放在/WEB-INF/lib
您的 web 应用程序的文件夹中。
Here's an example which displays List<String>
as <ul><li>
. The servlet:
这是一个显示List<String>
为<ul><li>
. 小服务程序:
@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);
}
The JS code:
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>.
});
});
});
Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (responseJson
) as function argument when you set the response content type to application/json
. If you forget to set it or rely on a default of text/plain
or text/html
, then the responseJson
argument wouldn't give you a JSON object, but a plain vanilla string and you'd need to manually fiddle around with JSON.parse()
afterwards, which is thus totally unnecessary if you set the content type right in first place.
请注意,jQuery 会自动将响应解析为 JSON,并responseJson
在您将响应内容类型设置为application/json
. 如果您忘记设置它或依赖于默认值text/plain
or text/html
,那么该responseJson
参数不会给您一个 JSON 对象,而是一个普通的普通字符串,您需要在JSON.parse()
之后手动摆弄,因此如果您完全没有必要首先设置内容类型。
Returning Map<String, String>
as JSON
Map<String, String>
以 JSON 形式返回
Here's another example which displays Map<String, String>
as <option>
:
这是另一个示例,显示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);
}
And the JSP:
和 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>.
});
});
});
with
和
<select id="someselect"></select>
Returning List<Entity>
as JSON
List<Entity>
以 JSON 形式返回
Here's an example which displays List<Product>
in a <table>
where the Product
class has the properties Long id
, String name
and BigDecimal price
. The servlet:
下面是其中显示了一个例子List<Product>
中<table>
,其中Product
类具有的属性Long id
,String name
和BigDecimal price
。小服务程序:
@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);
}
The JS code:
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>.
});
});
});
Returning List<Entity>
as XML
List<Entity>
以 XML 形式返回
Here's an example which does effectively the same as previous example, but then with XML instead of JSON. When using JSP as XML output generator you'll see that it's less tedious to code the table and all. JSTL is this way much more helpful as you can actually use it to iterate over the results and perform server side data formatting. The servlet:
这是一个与前面的示例有效相同的示例,但使用 XML 而不是 JSON。当使用 JSP 作为 XML 输出生成器时,您会发现对表格和所有内容进行编码变得不那么乏味了。JSTL 这种方式更有帮助,因为您实际上可以使用它来迭代结果并执行服务器端数据格式化。小服务程序:
@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);
}
The JSP code (note: if you put the <table>
in a <jsp:include>
, it may be reusable elsewhere in a non-ajax response):
JSP 代码(注意:如果你把它<table>
放在 a 中<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>
The JS code:
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".
});
});
You'll by now probably realize why XML is so much more powerful than JSON for the particular purpose of updating a HTML document using Ajax. JSON is funny, but after all generally only useful for so-called "public web services". MVC frameworks like JSFuse XML under the covers for their ajax magic.
您现在可能会意识到,对于使用 Ajax 更新 HTML 文档的特定目的,为什么 XML 比 JSON 强大得多。JSON 很有趣,但毕竟通常只对所谓的“公共网络服务”有用。像JSF这样的 MVC 框架在幕后使用 XML 来实现它们的 ajax 魔法。
Ajaxifying an existing form
对现有表单进行 Ajax 化
You can use jQuery $.serialize()
to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery (and thus degrades gracefully when enduser has JavaScript disabled):
您可以使用 jQuery$.serialize()
轻松地对现有的 POST 表单进行 ajaxify,而无需摆弄收集和传递单个表单输入参数。假设一个现有的表单在没有 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>
You can progressively enhance it with ajax as below:
您可以使用 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.
});
You can in the servlet distinguish between normal requests and ajax requests as below:
您可以在 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.
}
}
The jQuery Form plugindoes less or more the same as above jQuery example, but it has additional transparent support for multipart/form-data
forms as required by file uploads.
的jQuery的表格插件确实更少或更多的与上述相同的jQuery例子,但它具有用于附加透明支持multipart/form-data
所要求的文件上传形式。
Manually sending request parameters to servlet
手动向servlet发送请求参数
If you don't have a form at all, but just wanted to interact with the servlet "in the background" whereby you'd like to POST some data, then you can use jQuery $.param()
to easily convert a JSON object to an URL-encoded query string.
如果您根本没有表单,而只是想在“后台”与 servlet 交互以便发布一些数据,那么您可以使用 jQuery$.param()
轻松地将 JSON 对象转换为 URL 编码的对象请求参数。
var params = {
foo: "fooValue",
bar: "barValue",
baz: "bazValue"
};
$.post("someservlet", $.param(params), function(response) {
// ...
});
The same doPost()
method as shown here above can be reused. Do note that above syntax also works with $.get()
in jQuery and doGet()
in servlet.
doPost()
可以重复使用与上面显示的相同的方法。请注意,上述语法也适用$.get()
于 jQuery 和doGet()
servlet。
Manually sending JSON object to servlet
手动将 JSON 对象发送到 servlet
If you however intend to send the JSON object as a whole instead of as individual request parameters for some reason, then you'd need to serialize it to a string using JSON.stringify()
(not part of jQuery) and instruct jQuery to set request content type to application/json
instead of (default) application/x-www-form-urlencoded
. This can't be done via $.post()
convenience function, but needs to be done via $.ajax()
as below.
不过,若你打算发送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) {
// ...
}
});
Do note that a lot of starters mix contentType
with dataType
. The contentType
represents the type of the requestbody. The dataType
represents the (expected) type of the responsebody, which is usually unnecessary as jQuery already autodetects it based on response's Content-Type
header.
请注意,很多初学者都contentType
与dataType
. 该contentType
表示的类型请求体。的dataType
表示(预期)类型的反应体,这通常是不必要的,因为已经jQuery的自动检测它基于响应的Content-Type
报头中。
Then, in order to process the JSON object in the servlet which isn't being sent as individual request parameters but as a whole JSON string the above way, you only need to manually parse the request body using a JSON tool instead of using getParameter()
the usual way. Namely, servlets don't support application/json
formatted requests, but only application/x-www-form-urlencoded
or multipart/form-data
formatted requests. Gson also supports parsing a JSON string into a JSON object.
然后,为了处理 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();
// ...
Do note that this all is more clumsy than just using $.param()
. Normally, you want to use JSON.stringify()
only if the target service is e.g. a JAX-RS (RESTful) service which is for some reason only capable of consuming JSON strings and not regular request parameters.
请注意,这一切都比仅使用$.param()
. 通常,您JSON.stringify()
只希望在目标服务是例如 JAX-RS (RESTful) 服务时使用,该服务由于某种原因只能使用 JSON 字符串而不是常规请求参数。
Sending a redirect from servlet
从 servlet 发送重定向
Important to realize and understand is that any sendRedirect()
and forward()
call by the servlet on an ajax request would only forward or redirect the ajax request itselfand not the main document/window where the ajax request originated. JavaScript/jQuery would in such case only retrieve the redirected/forwarded response as responseText
variable in the callback function. If it represents a whole HTML page and not an ajax-specific XML or JSON response, then all you could do is to replace the current document with it.
需要意识到和理解的重要一点是,servlet 对 ajax 请求的任何sendRedirect()
和forward()
调用只会转发或重定向ajax 请求本身,而不是 ajax 请求发起的主文档/窗口。在这种情况下,JavaScript/jQuery 只会检索重定向/转发的响应作为responseText
回调函数中的变量。如果它代表整个 HTML 页面而不是特定于 ajax 的 XML 或 JSON 响应,那么您所能做的就是用它替换当前文档。
document.open();
document.write(responseText);
document.close();
Note that this doesn't change the URL as enduser sees in browser's address bar. So there are issues with bookmarkability. Therefore, it's much better to just return an "instruction" for JavaScript/jQuery to perform a redirect instead of returning the whole content of the redirected page. E.g. by returning a boolean, or an URL.
请注意,这不会更改最终用户在浏览器地址栏中看到的 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;
}
// ...
}
See also:
也可以看看:
回答by Peter Knego
Normally you cant update a page from a servlet. Client (browser) has to request an update. Eiter client loads a whole new page or it requests an update to a part of an existing page. This technique is called Ajax.
通常您不能从 servlet 更新页面。客户端(浏览器)必须请求更新。Eiter 客户端加载一个全新的页面,或者它请求更新现有页面的一部分。这种技术称为 Ajax。
回答by Stephen C
The right way to update the page currently displayed in the user's browser (without reloading it) is to have some code executing in the browser update the page's DOM.
更新用户浏览器中当前显示的页面(无需重新加载)的正确方法是在浏览器中执行一些代码来更新页面的 DOM。
That code is typically javascript that is embedded in or linked from the HTML page, hence the AJAX suggestion. (In fact, if we assume that the updated text comes from the server via an HTTP request, this is classic AJAX.)
该代码通常是嵌入在 HTML 页面中或从 HTML 页面链接的 javascript,因此是 AJAX 建议。(事实上,如果我们假设更新的文本来自服务器通过 HTTP 请求,这就是经典的 AJAX。)
It is also possible to implement this kind of thing using some browser plugin or add-on, though it may be tricky for a plugin to reach into the browser's data structures to update the DOM. (Native code plugins normally write to some graphics frame that is embedded in the page.)
也可以使用一些浏览器插件或附加组件来实现这种事情,尽管插件访问浏览器的数据结构来更新 DOM 可能会很棘手。(本机代码插件通常会写入一些嵌入在页面中的图形框架。)
回答by Mitul Maheshwari
I will show you a whole example of servlet & how do ajax call.
我将向您展示 servlet 的完整示例以及如何调用 ajax。
Here, we are going to create the simple example to create the login form using servlet.
在这里,我们将创建使用 servlet 创建登录表单的简单示例。
index.html
索引.html
<form>
Name:<input type="text" name="username"/><br/><br/>
Password:<input type="password" name="userpass"/><br/><br/>
<input type="button" value="login"/>
</form>
Here is ajax Sample
这是 ajax 示例
$.ajax
({
type: "POST",
data: 'LoginServlet='+name+'&name='+type+'&pass='+password,
url: url,
success:function(content)
{
$('#center').html(content);
}
});
LoginServlet Servlet Code :-
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);
}
}
}
回答by SUBZ
$.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);
}
});
回答by user3468976
Ajax (also AJAX) an acronym for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously Below is example code:
Ajax(也称为 AJAX)是 Asynchronous JavaScript and XML 的首字母缩写词)是一组相互关联的 Web 开发技术,用于在客户端创建异步 Web 应用程序。使用 Ajax,Web 应用程序可以向服务器异步发送数据和从服务器检索数据 下面是示例代码:
Jsp page java script function to submit data to servlet with two variable firstName and lastName:
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 to read data send back to jsp in xml format ( You could use text as well. Just you need to change response content to text and render data on javascript function.)
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>");
}
回答by Thakhani Tharage
Using bootstrap multi select
使用引导多选
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
在 Servlet 中
request.getParameter("input")