Jetty关闭了程序

时间:2013-02-04 21:08:19

标签: user-interface jetty

我正在尝试创建一个GUI界面来启动和停止具有不同返回字符串的Jetty服务器。目前我有一个编程的启动和停止按钮,它将“Hello World”返回到localhost:8080。我的代码发布在下面,是的我有导入,删除以简化它。

public class JettyGUI extends AbstractHandler{

private static Server server = new Server(8080);
private static boolean running = false;

private static void gui() {

    JFrame frame = new JFrame("Jetty");
    JButton start_button = new JButton("Start");
    JButton stop_button = new JButton("Stop");
    JPanel panel = new JPanel();

    panel.setBackground(Color.BLACK);

    panel.add(start_button);
    panel.add(stop_button);

    frame.add(panel);

    frame.setSize(300, 150);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    start_button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            System.out.println("Start pressed.");
            startServer();
        }
    });
    stop_button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            System.out.println("Stop pressed.");
            JettyGUI.stopServer();
        }
    });

}


private static void stopServer() {
    if(running == false){
        System.err.println("Server is already running!");
    }
    else{
        try {
            server.stop();
        } 
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
    System.out.println("Server stopped!");
}

private static void startServer() {
    if(running == true){
        System.err.println("Server is already running!");
    }
    else{
        try{
            server.setHandler(new JettyGUI());
            server.start();
            server.join();
        }
        catch(Exception ex){
            System.out.println(ex);
        }
      System.out.println("Server started!");  
    }
}

    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    response.setContentType("text;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    baseRequest.setHandled(true);
    response.getWriter().println("Hello World!"); //print this text

}

public static void main(String[] args) {

    gui();

}

}

当我按下“开始”按钮时,Jetty API似乎接管了我的应用程序,我再也无法按下“停止”按钮。有人能告诉我一种方法来浏览这个或以不同方式编程吗?

谢谢! :) -Henry Harris

1 个答案:

答案 0 :(得分:0)

server.join();将使当前线程等待,直到服务器停止。

将它评论出来,作为一个你不需要它的GUI程序。