WEBrick

WEBrick

本文摘自:http://anw.stikipad.com/ocean/show/WEBrick

WEBrick 是用 Ruby 寫的 web server, 若有開發 Web Service 需要也可以用, 但若開發 web 應用程式, 你應該用 Rails 比較好.


  1. WEBrick::HTTPServer 為 web server
  2. servlet class 請繼承自 HTTPServlet::AbstractServlet
    
    require 'webrick'
    include WEBrick
    
    #a function stub to start WEBrick
    def start_WEBrick(config = {})
      config.update(:Port => 2000)
    
      server = HTTPServer.new(config)
      yield server if block_given?
    
      ['INT', 'TERM'].each do |signal|
        trap(signal) { server.shutdown }
      end
      server.start
    end
    
    class HelloServlet < HTTPServlet::AbstractServlet
      def do_GET(req, res)
        res["content-type"] = "text/html; charset=UTF-8" 
        res.body = %{
          <html>
          <body>
          Hello World!
          </body>
          </html>
        }
      end
    
      alias do_POST do_GET
    end
    
    #
    start_WEBrick do |server|
      #servlet "/hello" 
      server.mount("/hello", HelloServlet)
    end
    
  3. 啟動後請 http://localhost:2000/hello 就可以看到內容
  4. WEBrick 也可以處理靜態 html 網頁, 利用內建 HTTPServlet::FileHandler
    
    #
    start_WEBrick do |server|
      #document root "/" 
      doc_root = File.join(Dir.pwd, 'htdocs')
      server.mount("/", HTTPServlet::FileHandler, doc_root, {:FancyIndexing => true})
    end
posted @ 2007-02-17 11:49  海浪~~  阅读(543)  评论(0)    收藏  举报