从servlet返回JSON [英] Return JSON from servlet
问题描述
这是一个非常基本的请求 - 响应测试。浏览器使用jQuery $ .ajax API将hello from browser发送到servlet,servlet接收此消息,然后使用org.json.simple库创建一个JSON对象,并向浏览器发送一条消息hello from server的JSON响应。
It is a very basic request-response test. Browser sends "hello from browser" to servlet using jQuery $.ajax API, and servlet receives this message, then create a JSON object using org.json.simple library and sends back to browser a JSON response with message "hello from server".
我在localhost上运行它,假设我的IP地址是123.123.12.123,平台是Ubuntu,服务器是Tomcat 6.0,在Eclipse IDE中运行。
I am running this on localhost and just assume my IP address is 123.123.12.123, the platform is Ubuntu, server is Tomcat 6.0, running in the Eclipse IDE.
测试1.我从Eclipse启动服务器,打开Firefox,输入 http:// localhost:8080 / myproject / test.jsp ,我可以看到servlet收到消息,浏览器收到响应,测试通过。
Test 1. I start the server from Eclipse, open Firefox, enter http://localhost:8080/myproject/test.jsp, I can see servlet receives message and browser receives response, test passed.
测试2.服务器仍然在Ubuntu的Eclipse上运行,我从VirtualBox启动Windows 7客户机和Windows 7中的Firefox浏览器,输入 http://123.123.12.123:8080/myproject/test.jsp ,工作按照我的预期,测试通过。
Test 2. server is still running at the Eclipse at Ubuntu, I start Windows 7 guest machine from VirtualBox and the Firefox browser in the Windows 7, enter http://123.123.12.123:8080/myproject/test.jsp, works as I expected, test passed.
测试3.服务器仍然在Eclipse上运行,在Ubuntu,打开Internet Explorer 9浏览器,给它地址 http://123.123.12.123:8080/myproject/test.jsp ,没有任何反应。
调试给了我
Test 3. server is still running at Eclipse at Ubuntu, open Internet Explorer 9 browser, give it address http://123.123.12.123:8080/myproject/test.jsp, nothing happens. The debug gives me
响应HTTP / 1.1 200 OK
Response HTTP/1.1 200 OK
响应正文{消息:你好,来自服务器}
Response body {"message":"hello from server"}
test.jsp是
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="release/js/libs/json2.js"></script>
<script>
$(document).ready(function(){
var request = ({"message":'Hello from browser'});
var jsonobj=JSON.stringify(request);
$.ajax({
data: {para:jsonobj},
dataType: 'json',
url: './TestServlet',
type: 'POST',
success: function(jsonObj){
alert(jsonObj.message);
},
error: function() {
alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
}
});
});
</script>
<body>
</body>
</html>
servlet代码是
The servlet code is
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf8");
response.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
System.out.println(jsonObj.get("message"));
JSONObject obj = new JSONObject();
obj.put("message", "hello from server");
out.print(obj);
}
}
更新:
仔细观察后的变化
error: function() {
alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
}
到
error: function(xhr,err) {
alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
}
我得到警报readyState:0和状态:0。
但我可以在Response body看到{message:hello from server}和
响应头是
I got alert readyState:0 and status:0. But I can see {"message":"hello from server"} at Response body and the response header is
Key Value
Response HTTP/1.1 200 OK
推荐答案
IE缓存AJAX请求积极(不仅仅是Firefox,Chrome和Safari)。
有时你需要在请求时设置缓存头控制器。像 cache:false
。我试图像这样修复你的代码
IE caches AJAX requests aggressively (more than Firefox, Chrome, and Safari, anyway).
Sometimes you need to set cache header controller when request. Like cache:false
. I tried to fix your code like this
request.setCharacterEncoding("utf8");
//response.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
System.out.println(jsonObj.get("message"));
JSONObject obj = new JSONObject();
obj.put("message", "hello from server");
out.print(obj);
我从 application / json更改了你的响应内容类型; charset = utf8
只需 application / json
就行了。
这篇关于从servlet返回JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!