首页 文章

从servlet返回JSON

提问于
浏览
12

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

我在localhost上运行它,假设我的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客户机和Windows 7中的Firefox浏览器,输入http://123.123.12.123:8080/myproject/test.jsp,按照我的预期工作,测试通过 .

测试3.服务器仍然在Eclipse上运行Ubuntu,打开Internet Explorer 9浏览器,给它地址http://123.123.12.123:8080/myproject/test.jspnothing happens. 调试给了我

响应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和状态:0 . 但我可以在Response主体看到{“message”:“hello from server”}并且响应头是

Key Value
Response    HTTP/1.1 200 OK

2 回答

  • 3

    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);
    

    我将您的响应内容类型从 application/json; charset=utf8 更改为 application/json ,这很有效 .

  • 12

    我遇到了同样的问题 . 它在Firefox上工作得很好,但在IE上却没有...我发现在阅读这篇文章后我的问题与'Content-Type'有关 . 问题似乎是IE有“charset = UTF8”的问题 . 但是,如果你使用'charset = UTF-8'(带破折号),它就可以了!那么你的Content-Type应该是:application / json; charset = UTF-8

相关问题