0

我需要在 selenium 方法中使用 response.flushbuffer。

我的代码

static PrintWriter writer;
static int timer = 0;

protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
{
    runDriver("radio", "click", "complete");
}

public static void runDriver(String col1, String Col2, String col3)
{
    WebElement ack1 = driver.findElement(By.id("represent"));
    try
    {
        ack1.click();
        String click1 = "<tr><td>" + col1 + "</td><td>" + col2 + "</td><td>" + col3 + "</td></tr>";
        writer.println(click1);
        response.flushBuffer(); // Won't let me put this here!
        Thread.sleep(timer);                                                                                        
     }
    catch(InterruptedException e)
    {
        writer.println( e+" ID:21");
    }
}

我试图将 Webdriver 的相同操作隔离到一种方法,这样我就不必重复它了。我也尝试过这样做。

static PrintWriter writer;
static int timer = 0;

protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
{
    String radio1 = "Radio";
    String clicked = "Click";
    String complete = " Complete";

    top(radio1, clicked, complete);
    response.flushBuffer();
    bottom();
}

    public static void top(String col1, String col2, String col3)
    {
        writer.println("<tr><td>" + col1 + "</td><td>" + col2 + "</td><td>" + col3 + "</td></tr>");
    }

    public static void bottom()
    {
        try
        {
            Thread.sleep(timer);
        }
        catch(Exception e)
        {
            writer.println( "error: " + e);
        }
    }

但它给了我一个 NullPointerException。我需要使用 response.flushBuffer() 的原因是用户可以看到发生的过程。否则它将完成该过程然后输出文本。

更新 **

我修复了 NPE。事实证明,我仍然在 doget 方法中声明了 Printer writer。我仍然可以在 doget 方法之外获得 response.flushbuffer 。

4

1 回答 1

1

首先,请注意 servlet 中的全局变量由所有请求共享,并可能导致线程安全问题。除了少数用例(例如全局计数器)之外,在 servlet 中使用它们几乎总是一个坏主意。

为什么不简单地将response对象传递给top()方法?例如:

public static void top(String col1, String col2, String col3, HttpServletResponse response)
{
    PrintWriter writer = response.getWriter();
    writer.println("<tr><td>" + col1 + "</td><td>" + col2 + "</td><td>" + col3 + "</td></tr>");
    response.flushBuffer();
}
于 2013-10-09T20:05:01.217 回答