从servlet返回JSON

时间:2012-03-10 10:21:22

标签: jquery json internet-explorer java-ee servlets

这是一个非常基本的请求 - 响应测试。浏览器使用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.jsp没有任何反应。 调试给了我

响应HTTP / 1.1 200确定

响应正文{“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 body看到{“message”:“hello from server”} 响应头是

Key Value
Response    HTTP/1.1 200 OK

4 个答案:

答案 0 :(得分:12)

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,并且确实有效。

答案 1 :(得分:3)

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

答案 2 :(得分:0)

使用Gson,您可以发送json响应

@WebServlet(urlPatterns = {“ / jsonResponse”})     公共类JsonResponse扩展了HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
    Subject subject1 = new Subject(1, "Computer Fundamentals");
    Subject subject2 = new Subject(2, "Computer Graphics");
    Subject subject3 = new Subject(3, "Data Structures");
    Set subjects = new HashSet();
    subjects.add(subject1);
    subjects.add(subject2);
    subjects.add(subject3);
    student.setSubjects(subjects);
    Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
    student.setAddress(address);
    Gson gson = new Gson();
    String jsonData = gson.toJson(student);
    PrintWriter out = response.getWriter();
    try {
        out.println(jsonData);
    } finally {
        out.close();
    }

}

}

更多json response from servlet in java

答案 3 :(得分:0)

<% 
     Gson gs = new Gson();
     BeanHelpBH bh = new BeanHelpBH();
     List<Baihatmoi> lst = bh.getTenbaihatbyName("Ao moi ca mau");
    String bha = gs.toJson(lst);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    out.print(bha);
    out.flush();


%>

  script : 
        <script>
             $(document).ready(function(){
               $.get('jsontest.jsp',function(data){
            [enter image description here][1] console.log(data);

              });

           });
        </script>