0

Undertow を使用しようとしています。ここで簡単な例:

public class MyExample {

private static int SIMPLE_HANDLER_CALL = 0;
private static int LIBRE_OFFICE_CALL = 0;

public static void main(String[] args) {

    Undertow server = Undertow.builder()
            .addHttpListener(3333, "localhost")
            .setHandler(new SimpleHttpHandler())
            .build();

    server.start();
}

private static class SimpleHttpHandler implements HttpHandler{
    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        System.out.println("---------------------------------------------");
        System.out.println("start handleRequest()");
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
        connectToPg(exchange, "msgPrev = " + Integer.toString(SIMPLE_HANDLER_CALL) + "; msgCur = " + Integer.toString(++SIMPLE_HANDLER_CALL));
        System.out.println("end handleRequest()");
    }
}

private static void connectToPg(HttpServerExchange exchange, String msg){
    try(
            Connection connection = DriverManager.getConnection("jdbc:postgresql://10.10.2.158:5432/myDb", "myUser", "myPass");
            Statement st = connection.createStatement();
    )
    {
        ResultSet rs = st.executeQuery("select count(*) as CNT from event.event");

        java.util.Date now = new java.util.Date();
        while(rs.next()){
            int cnt = rs.getInt("CNT");
            System.out.print("cnt = " + cnt);
            exchange.getResponseSender().send("Date = " + now + "; cnt = " + cnt);
        }

        System.out.println("rs = " + rs.toString());
        System.out.println("msg = " + msg);
    }
    catch (Exception ex){
        System.out.println(ex.getMessage());
    }
    finally {
        System.out.println("end connectToPg()");
    }
}
}

できます。私はタイプする

http://localhost:3333/

ブラウザーとハンドラーで Postgres へのクエリを作成し、回答を受け取ります。しかし、handler は 2 回繰り返します。コンソールに次のような出力が表示されます。

---------------------------------------------
start handleRequest()
cnt = 12rs = org.postgresql.jdbc4.Jdbc4ResultSet@12eeffa4
msg = msgPrev = 0; msgCur = 1
end connectToPg()
end handleRequest()
---------------------------------------------
start handleRequest()
cnt = 12rs = org.postgresql.jdbc4.Jdbc4ResultSet@17b98b20
msg = msgPrev = 1; msgCur = 2
end connectToPg()
end handleRequest()

なぜ2回呼び出されるのですか?

4

1 に答える 1

0

交換パラメーターを印刷 (またはログアウト) して、どのような要求が処理されているかを確認することをお勧めします。

System.out.println(exchange.getRequestURL());

1 つのオプションは、2 番目の要求が /favicon.ico に対するものであることです。より制御された方法でリクエストを作成することもできます。REST クライアントの 1 つまたは curl を使用します。

于 2014-10-02T12:28:58.187 に答える