小编典典

从Servlet返回JSON

json

这是一个非常基本的请求-响应测试。浏览器使用jQuery $ .ajax
API将“来自浏览器的hello”发送到servlet,然后servlet接收此消息,然后使用org.json.simple库创建一个JSON对象,并将带有消息“
hello from server”的JSON响应发送回浏览器。

我在本地主机上运行它,只是假设我的IP地址是123.123.12.123,平台是Ubuntu,服务器是Tomcat 6.0,并且在Eclipse
IDE中运行。

测试1.我从Eclipse启动服务器,打开Firefox,输入http:// localhost:8080 / myproject /
test.jsp
,我可以看到servlet收到消息,浏览器收到响应,测试通过。

测试2.服务器仍然在Eclipse中在Ubuntu上运行,我从VirtualBox和在Windows 7中的Firefox浏览器启动Windows
7客户机上,输入http://123.123.12.123:8080/myproject/test.jsp,工程,我预期,测试通过。

测试3.服务器仍在Ubuntu的Eclipse上运行,打开Internet Explorer
9浏览器,将其地址设置为http://123.123.12.123:8080/myproject/test.jsp
什么都没有发生。 调试给了我

响应HTTP / 1.1 200 OK

响应正文{“ message”:“来自服务器的问候”}

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代码是

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和status:0。但我可以在响应正文中看到{“message”:“来自服务器的问候”},响应头是

Key Value
Response    HTTP/1.1 200 OK

阅读 228

收藏
2020-07-27

共1个答案

小编典典

IE积极地缓存AJAX请求(无论如何,它都超过了Firefox,Chrome和Safari)。有时您需要在请求时设置缓存头控制器。像cache:false。我试图像这样修复您的代码

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.toString());

我将您的回复内容类型从更改application/json;charset=utf8为公正application/json,并且有效。

2020-07-27