I am send a List Of Stock Objects from my servlet to JSP using server sent events as shown below
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");
}
}
This is the jsp which is listening to above servlet
<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>
The alert is being displayed:
[com.Stock@1cd7a270, com.Stock@10e975db]
You'd either want to iterate over it with a for..in loop like this:
for ( value in event.data )
{
// do something with value here
console.log( value );
}
or use jQuery's each() method :
$.each( event.data, function( index, value )
{
// do something with the stuff here
console.log( index, value );
} );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.