<!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.
}
@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>.
});
});
});
$(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 id , String name 和 BigDecimal price 属性 . servlet:
$(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>.
});
});
});
$(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({
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);
}
});
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);
}
7 回答
实际上,关键字是"ajax":异步JavaScript和XML . 然而,去年它不仅仅是Asynchronous JavaScript和JSON . 基本上,您让JS执行异步HTTP请求并根据响应数据更新HTML DOM树 .
由于它可以在所有浏览器(尤其是Internet Explorer与其他浏览器)之间工作,因此有很多JavaScript库可以简化这一功能,并且可以涵盖尽可能多的浏览器特定的错误/怪癖 . ,例如jQuery,Prototype,Mootools . 由于jQuery最受欢迎,我将在下面的例子中使用它 .
Kickoff示例将String作为纯文本返回
像下面一样创建
/some.jsp
(注意:代码不希望将JSP文件放在子文件夹中,如果这样做,请相应地更改servlet URL):使用
doGet()
方法创建一个servlet,如下所示:将此servlet映射到
/someservlet
或/someservlet/*
的URL模式,如下所示(显然,URL模式可供您自由选择,但您需要在相应的所有位置更改JS代码示例中的someservlet
URL):或者,当您还没有使用Servlet 3.0兼容容器(Tomcat 7,Glassfish 3,JBoss AS 6等等或更新版本)时,请以旧式方式将其映射到_1723563中(另请参阅our Servlets wiki page):
现在在浏览器中打开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:JS代码:
请注意,当您将响应内容类型设置为
application/json
时,jQuery会自动将响应解析为JSON,并直接为您提供JSON对象(responseJson
)作为函数参数 . 如果您忘记设置它或依赖于text/plain
或text/html
的默认值,那么之后responseJson
参数将不需要手动摆弄JSON.parse(),因此如果您首先将内容类型设置为正确,则完全没有必要 .将 Map <String,String>作为JSON返回
这是另一个显示
Map<String, String>
为<option>
的示例:和JSP:
同
将列表<Entity>作为JSON返回
这是一个在
<table>
中显示List<Product>
的示例,其中Product
类具有Long id
,String name
和BigDecimal price
属性 . servlet:JS代码:
将列表<Entity>作为XML返回
这是一个与前一个示例有效相同的示例,但后来使用XML而不是JSON . 当使用JSP作为XML输出生成器时,您会发现对表和所有表进行编码并不那么繁琐 . JSTL这种方式更有用,因为您可以实际使用它来迭代结果并执行服务器端数据格式化 . servlet:
JSP代码(注意:如果将
<table>
放在<jsp:include>
中,它可以在非ajax响应中的其他地方重用):JS代码:
您现在可能已经意识到为什么XML比使用Ajax更新HTML文档的特定目的更强大 . JSON很有趣,但毕竟一般只对所谓的"public web services"有用 . 像JSF这样的MVC框架使用XML作为他们的ajax魔法 .
对现有表单进行Ajax化
您可以使用jQuery $.serialize()轻松地对现有的POST表单进行ajax,而无需摆弄收集和传递单个表单输入参数 . 假设一个现有的表单在没有JavaScript / jQuery的情况下工作得很好(因此当最终用户禁用JavaScript时会优雅地降级):
你可以逐步用ajax增强它如下:
您可以在servlet中区分正常请求和ajax请求,如下所示:
jQuery Form plugin与上面的jQuery示例相比更少或更多,但它根据文件上传的要求对
multipart/form-data
表单提供了额外的透明支持 .手动向servlet发送请求参数
如果你不想发布一些数据,那么你可以使用jQuery $.param()轻松地将JSON对象转换为URL编码的查询字符串 .
可以重复使用上面所示的相同
doPost()
方法 . 请注意,上面的语法也适用于jQuery中的$.get()
和servlet中的doGet()
.手动将JSON对象发送到servlet
但是,如果由于某种原因打算将JSON对象作为一个整体而不是作为单独的请求参数发送,那么您需要使用JSON.stringify()(不是jQuery的一部分)将其序列化为字符串,并指示jQuery将请求内容类型设置为
application/json
而不是(默认)application/x-www-form-urlencoded
. 这不能通过$.post()
便利功能完成,但需要通过$.ajax()
完成,如下所示 .请注意,很多初学者将
contentType
与dataType
混在一起 .contentType
表示 request 正文的类型 .dataType
表示 response 正文的(预期)类型,这通常是不必要的,因为jQuery已根据响应的Content-Type
标头自动检测它 .然后,为了处理servlet中的JSON对象,该对象不作为单独的请求参数发送,而是作为整个JSON字符串以上述方式发送,您只需要使用JSON工具手动解析请求体,而不是使用
getParameter()
通常的方式 . 即,servlet不支持application/json
格式化的请求,但仅支持application/x-www-form-urlencoded
或multipart/form-data
格式的请求 . Gson还支持将JSON字符串解析为JSON对象 .请注意,这一切都比使用
$.param()
更笨拙 . 通常,只有当目标服务是例如,您才想使用JSON.stringify()
. 一种JAX-RS(RESTful)服务,由于某种原因只能使用JSON字符串而不是常规请求参数 .从servlet发送重定向
要实现和理解的重要一点是,servlet对ajax请求的任何
sendRedirect()
和forward()
调用只会转发或重定向ajax请求本身,而不是ajax请求所在的主文档/窗口 . 在这种情况下,JavaScript / jQuery仅在回调函数中将重定向/转发的响应检索为responseText
变量 . 如果它代表整个HTML页面而不是特定于ajax的XML或JSON响应,那么您所能做的就是用它替换当前文档 .请注意,这不会更改最终用户在浏览器地址栏中看到的URL . 因此,可书籍性存在问题 . 因此,最好只返回JavaScript / jQuery的“指令”来执行重定向,而不是返回重定向页面的整个内容 . 例如 . 通过返回布尔值或URL .
另见:
Call Servlet and invoke Java code from JavaScript along with parameters
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
How to switch easily between ajax-based website and basic HTML website?
How to upload files to server using JSP/Servlet and Ajax?
更新当前显示在用户浏览器中的页面(无需重新加载)的正确方法是在浏览器中执行一些代码更新页面的DOM .
该代码通常是嵌入HTML页面或从HTML页面链接的javascript,因此是AJAX建议 . (事实上,如果我们假设更新的文本是通过HTTP请求来自服务器的,那么这就是经典的AJAX . )
也可以使用一些浏览器插件或附加组件来实现这种事情,尽管插件可能很难进入浏览器的数据结构来更新DOM . (本机代码插件通常会写入页面中嵌入的某些图形框架 . )
我将向您展示一个servlet的完整示例以及ajax如何调用 .
在这里,我们将创建一个使用servlet创建登录表单的简单示例 .
index.html
Here is ajax Sample
LoginServlet Servlet Code :-
Ajax(也是AJAX)是Asynchronous JavaScript和XML的首字母缩写,是一组在客户端用于创建异步Web应用程序的相互关联的Web开发技术 . 使用Ajax,Web应用程序可以异步向服务器发送数据和从中检索数据 . 下面是示例代码:
jsp页面java脚本函数用两个提交数据到servlet变量firstName和lastName:
用于读取数据的Servlet以xml格式发送回jsp(您也可以使用文本 . 只需要将响应内容更改为文本并在javascript函数上呈现数据 . )
通常,您无法从servlet更新页面 . 客户端(浏览器)必须请求更新 . Eiter客户端加载一个全新的页面,或者它请求更新现有页面的一部分 . 这种技术称为Ajax .
使用bootstrap多选
Ajax
In Servlet