我是Web应用程序和Servlet的新手,我有以下问题:
每当我在servlet中打印一些东西并通过webbrowser调用它时,它就会返回一个包含该文本的新页面.有没有办法使用Ajax在当前页面中打印文本?
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.
Since it's pretty a tedious work 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.
Kickoff example returningString
as plain text
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):
SO question 4112686
Create a servlet with a doGet()
method which look like this:
@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):
@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):
someservlet
com.example.SomeServlet
someservlet
/someservlet/*
现在在浏览器中打开http:// localhost:8080/context/test.jsp并按下按钮.您将看到div的内容使用servlet响应进行更新.
List
以JSON身份返回
使用JSON而不是明文作为响应格式,您甚至可以进一步采取措施.它允许更多的动态.首先,您希望有一个工具来转换Java对象和JSON字符串.它们也有很多(请参阅本页底部的概述).我个人最喜欢的是Google Gson.下载并将其JAR文件放在/WEB-INF/lib
webapplication的文件夹中.
这是一个显示List
为的示例
.servlet:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List 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 = $("").appendTo($("#somediv")); // Create HTML element and append it to HTML DOM element with ID "somediv".
$.each(responseJson, function(index, item) { // Iterate over the JSON array.
$("- ").text(item).appendTo($ul); // Create HTML
- element, set its text content with currently iterated item and append it to the
.
});
});
});
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.
Map
as JSON
Here's another example which displays Map
as :
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map 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:
$(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.
$("
with
Returning List
as JSON
Here's an example which displays The JS code: 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: The JSP code (note: if you put the The JS code: 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 JSF use XML under the covers for their ajax magic. You can use jQuery You can progressively enhance it with ajax as below: You can in the servlet distinguish between normal requests and ajax requests as below: The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for 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 The same 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 Do note that a lot of starters mix 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 Do note that this all is more clumsy than just using Important to realize and understand is that any 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.
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 这是ajax Sample LoginServlet Servlet代码: - Ajax(也是AJAX)是Asynchronous JavaScript和XML的首字母缩写,是一组在客户端用于创建异步Web应用程序的相互关联的Web开发技术.使用Ajax,Web应用程序可以异步向服务器发送数据和从中检索数据.下面是示例代码: Jsp页面java脚本函数用两个变量firstName和lastName向servlet提交数据: 用于读取数据的Servlet以xml格式发送回jsp(您也可以使用文本.只需要将响应内容更改为文本并在javascript函数上呈现数据.) 通常,您无法从servlet更新页面.客户端(浏览器)必须请求更新.Eiter客户端加载一个全新的页面,或者它请求更新现有页面的一部分.这种技术称为Ajax.List
in a where the
Product
class has the properties Long id
, String name
and BigDecimal price
. The servlet:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List
$(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 = $("
").appendTo($("#somediv")); // Create HTML
element and append it to HTML DOM element with ID "somediv".
$.each(responseJson, function(index, product) { // Iterate over the JSON array.
$("
").appendTo($table) // Create HTML element, set its text content with currently iterated item and append it to the .
.append($("
").text(product.id)) // Create HTML element, set its text content with id of currently iterated product and append it to the .
.append($(" ").text(product.name)) // Create HTML element, set its text content with name of currently iterated product and append it to the .
.append($(" ").text(product.price)); // Create HTML element, set its text content with price of currently iterated product and append it to the .
});
});
});
Returning List
as XML
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List
in a
, it may be reusable elsewhere in a non-ajax response):
<%@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" %>
${product.id}
$(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 element and append its HTML to HTML DOM element with ID "somediv".
});
});
$.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):
$(document).on("submit", "#someform", function(event) {
var $form = $(this);
$.post($form.attr("action"), $form.serialize(), function(response) {
// ...
});
event.preventDefault(); // Important! Prevents submitting the form.
});
@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.
}
}
multipart/form-data
forms as required by file uploads.$.param()
to easily convert a JSON object to an URL-encoded query string.var params = {
foo: "fooValue",
bar: "barValue",
baz: "bazValue"
};
$.post("someservlet", $.param(params), function(response) {
// ...
});
doPost()
method as shown here above can be reused. Do note that above syntax also works with $.get()
in jQuery and doGet()
in servlet.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.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
with dataType
. The contentType
represents the type of the request body. The dataType
represents the (expected) type of the response body, which is usually unnecessary as jQuery already autodetects it based on response's Content-Type
header.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.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()
. 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.sendRedirect()
and forward()
call by the servlet on an ajax request would only forward or redirect the ajax request itself and 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.document.open();
document.write(responseText);
document.close();
String redirectURL = "http://example.com";
Map
function(responseJson) {
if (responseJson.redirect) {
window.location = responseJson.redirect;
return;
}
// ...
}
See also:
@kuhaku:不.如果您从上到下阅读帖子,您将了解原因.
2> Stephen C..:
3> Mitul Mahesh..: $.ajax
({
type: "POST",
data: 'LoginServlet='+name+'&name='+type+'&pass='+password,
url: url,
success:function(content)
{
$('#center').html(content);
}
});
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.
"+
"The Details are as follws :
Name : ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
5> user3468976..: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);
}
/**
* @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("
6> Peter Knego..:
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有