从 servlet 返回 JSON [英] Return JSON from servlet

查看:22
本文介绍了从 servlet 返回 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的请求-响应测试.浏览器使用 jQuery $.ajax API 向 servlet 发送hello from browser",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收到消息,浏览器收到响应,测试通过.

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

Test 3. server 仍然在 Eclipse at Ubuntu 上运行,打开 Internet Explorer 9 浏览器,给它地址 http://123.123.12.123:8080/myproject/test.jsp什么也没发生.调试给了我

响应 HTTP/1.1 200 OK

响应正文 {"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"><头><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>在此处插入标题</title><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><脚本>$(document).ready(function(){var request = ({"message":'来自浏览器的你好'});var jsonobj=JSON.stringify(request);$.ajax({数据:{para:jsonobj},数据类型:'json',url: './TestServlet',类型:'POST',成功:函数(jsonObj){警报(jsonObj.message);},错误:函数(){alert('Ajax readyState: '+xhr.readyState+' status: '+xhr.status + ' ' + err);}});});<身体>

servlet 代码是

<前>导入 java.io.IOException;导入 java.io.PrintWriter;导入 javax.servlet.ServletException;导入 javax.servlet.http.HttpServlet;导入 javax.servlet.http.HttpServletRequest;导入 javax.servlet.http.HttpServletResponse;导入 org.json.simple.JSONObject;导入 org.json.simple.JSONValue;/*** Servlet 实现类 TestServlet*/公共类 TestServlet 扩展 HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/公共 TestServlet() {极好的();}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//TODO 自动生成的方法存根}/*** @see HttpServlet#doPost(HttpServletRequest 请求,HttpServletResponse 响应)*/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", "你好来自服务器");out.print(obj);}}

更新:

仔细观察变化后

<前>错误:函数(){alert('Ajax readyState: '+xhr.readyState+' status: '+xhr.status + ' ' + err);}

<前>错误:函数(xhr,错误){alert('Ajax readyState: '+xhr.readyState+' status: '+xhr.status + ' ' + err);}

我收到了警报 readyState:0 和 status:0.但我可以在响应正文中看到 {"message":"hello from server"} 和响应头是

<前>核心价值响应 HTTP/1.1 200 OK

解决方案

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", "你好来自服务器");out.print(obj.toString());

我从 application/json 更改了您的响应内容类型;charset=utf8application/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".

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.

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.

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.

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

Response HTTP/1.1 200 OK

Response body {"message":"hello from server"}

The test.jsp is

<%@ 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+'
status: '+xhr.status + ' ' + err);
        }
    });
});
</script>
<body>
</body>
</html>

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

    }

}

Update:

After a closer look by change

 error: function() {
            alert('Ajax readyState: '+xhr.readyState+'
status: '+xhr.status + ' ' + err);
}

to

error: function(xhr,err) {
            alert('Ajax readyState: '+xhr.readyState+'
status: '+xhr.status + ' ' + err);
        }

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

I changed your response content-type from application/json; charset=utf8 to just application/json and that worked.

这篇关于从 servlet 返回 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆