如何在方法中使用doGet响应?

时间:2013-10-09 15:56:54

标签: java servlets selenium selenium-webdriver

我需要在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方法中声明了打印机编写器。我仍然可以在doget方法之外得到response.flushbuffer。

1 个答案:

答案 0 :(得分: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();
}
相关问题