Can ruby write a servlet? Yes, it's not funny, and it's handy, because Ruby's standard library brings a webrick,webrick itself and a Serlvet container, and it's convenient to start a Web server anytime, anywhere.
First look at the simplest example, output hello to the browser:
require 'webrick'
require 'net/http'
include WEBrick
class HelloServlet < HTTPServlet::AbstractServlet
def hello(resp)
resp["Content-Type"]="text/html;charset=utf-8"
resp.body="hello,ruby servlet"
end
private :hello
def do_GET(req,resp)
hello(resp)
end
def do_POST(req,resp)
hello(resp)
end
end
if $0==__FILE__
server=HTTPServer.new(:Port=>3000)
server.mount("/hello",HelloServlet)
trap("INT"){ server.shutdown }
server.start
end
Is it similar to Java? All Serlvet are inherited from Httpservlet::abstractservlet and implemented Do_get or Do_post methods. In this line of code:
Server=httpserver.new (:P ort=>3000)
We started an HTTP Server with a port of 3000 and then mounted the helloservlet onto the/hello path, so after executing this script, you can pass the Http://localhost:3000/ Hello calls HelloServlet, simply displays the string "Hello,ruby servlet".