list1234 发表于 2017-3-1 11:56:55

Jetty使用

  目标:在Linux以及Windows下面配置应用;
  之前使用过smartfox,安装的时候弹出一个浏览器,一路next,印象很深刻。只是记得他是使用Jetty。最近做的项目也是需要进行配置;过往都是使用SWT进行制作;但是此次有一个网页版的监控程序,我的想法就是连带着配置程序一起坐到这个监控程序中。
  Jetty是内嵌式的Servlet容器;启动一个执行html的很简单,但是启动一个Jsp的工程,则需要多写几步,左后是启动默认浏览器并跳转到指定的页面:
      publicstaticvoid main(String[] args)throws Exception{
        Server server = new Server();
        Connector connector = new SelectChannelConnector();
  connector.setPort(8080);
  server.setConnectors(new Connector[] { connector });   
        WebAppContext webAppContext = new WebAppContext("WebContent","/");
  webAppContext.setDescriptor("WebContent/WEB-INF/web.xml");
  webAppContext.setResourceBase("WebContent/WEB-INF");
  webAppContext.setDisplayName("jetty");
  webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader());
  webAppContext.setConfigurationDiscovered(true);
  webAppContext.setParentLoaderPriority(true);
  server.setHandler(webAppContext);
  try{
  server.start();
              StartBrowser browser = new StartBrowser();
  browser.openURL("http://localhost:" + 8080);
        }catch(Exception e){
              e.printStackTrace();
        }
      }
  OpenUrl的实现:
      publicvoid openURL(String sURL) {
  try {
  URIuri = newURI(sURL);
              Desktop desktop = null;
  if (Desktop.isDesktopSupported()) {
  desktop = Desktop.getDesktop();
              }
  if (desktop != null)
  desktop.browse(uri);
         } catch (Exception e){
  e.printStackTrace();
         }
      }
  webAppContext.setResourceBase这句话比较重要,设置了你的那些JSP页面到哪里去找。比如此次我的JSP就是放在WEB-INF的下面。
  另外openUrl切记前面要添加http;否则程序判断不出来应用程序走的协议,将不会启动浏览器进行处理。
  这段代码已经验证在Win8,以及CentOS中可用。
页: [1]
查看完整版本: Jetty使用