2016-12-27 72 views
0

我寫了一個方法,它返回一個轉換爲String的數組。在main方法中調用此方法並將其打印出來時,數組將被填充。當我在doGet方法中調用同樣的方法將它打印在我的html文件中時,該數組是空的並且僅打印:[] 通常,doGet方法可以工作,因爲當方法返回的不是數組而是「hello」 html文件打印字符串。doGet()不起作用的Java SSE方法

這裏北京時間代碼:

public static String test(senderonpremise s){ 

    String t; 

    //this should be printed 
    t = String.valueOf(s.arrivalList);  
    //startSending(); 

    //this works in doGet() 
    //return "this works"; 

    // when I return this it works in the main-method but not in DoGet() 
    return t; 
} 


public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
    resp.setContentType("text/event-stream"); 
    resp.setCharacterEncoding("UTF-8"); 

    senderonpremise s = new senderonpremise(); 
    PrintWriter out = resp.getWriter(); 

    String next = "data: " + test(s) + "\n\n"; 
    out.write(next); 
    out.flush(); 

} 

/** 
    public static void main(String[] args) { 
     senderonpremise s = new senderonpremise(); 
     System.out.print(test(s)); 
    } 
**/ 
+0

這是不可能的答案你的問題。 'senderonpremise'代碼是未知的。另外,您應該遵循[Java命名約定](http://www.oracle.com/technetwork/java/codeconventions-135099.html)。 –

回答

0

我建議你使用JEaSSE庫:https://github.com/mariomac/jeasse,這是重量輕,工作了使用Servlet 3.X盒子

@WebServlet(asyncSupported = true) 
public class ExampleServlet1 extends HttpServlet { 

EventTarget target; 

@Override 
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
    target = new ServletEventTarget(req).ok().open(); 
} 

public void onGivenEvent(String info) { 
    target.send("givenEvent",info); 
} 
}