如何在servlet中序列化Java对象

时间:2014-04-04 14:47:21

标签: java servlets serialization

我使用服务器发送的事件从我的servlet向JSP发送一个Stock对象列表,如下所示

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        List<Stock> list = new ArrayList<Stock>();
         response.setContentType("text/event-stream");
        response.addHeader("Refresh", "20");
        PrintWriter out = response.getWriter();

            for(int i=0;i<2;i++)
            {
                Stock st = new Stock();
                st.setPrice("123");
                st.setSymbol("BPCL");
                list.add(st);
            }

        out.write("data: "+ list + "\n\n");
    }
}

这是正在监听servlet

的jsp
<html>
<body bgcolor="yellow">
    <script>

        function registerSSE()
        {
            var source = new EventSource('http://localhost:8086/StreamFromShareKhan/StreamServlet');  
            source.onmessage=function(event)
            {
               alert(event.data);
            };


        }
    </script>
    <output id ="result"></output>

    <input type="button" onclick="registerSSE()" value="View Good Stocks">

</body>
</html>

正在显示警报:

 [com.Stock@1cd7a270, com.Stock@10e975db]

1 个答案:

答案 0 :(得分:1)

你想要用for..in loop这样迭代它:

for ( value in event.data )
{
    // do something with value here
    console.log( value );
}

或使用jQuery's each() method

$.each( event.data, function( index, value )
{
    // do something with the stuff here
    console.log( index, value );
} );