Ruby也能寫(xiě)servlet?是的,沒(méi)開(kāi)玩笑,而且挺方便的,因?yàn)镽uby的標(biāo)準(zhǔn)庫(kù)就自帶了一個(gè)webrick,webrick本身又有一個(gè)serlvet容器,隨時(shí)隨地啟動(dòng)一個(gè)web server,實(shí)在是很方便。
先看個(gè)最簡(jiǎn)單的例子,輸出hello到瀏覽器:
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
是不是跟java很像?所有的serlvet都要繼承自
HTTPServlet::AbstractServlet,并實(shí)現(xiàn)do_GET或者do_POST方法。在這行代碼:
server=HTTPServer.new(:Port=>3000)
我們啟動(dòng)了一個(gè)HTTP Server,端口是3000,然后將
HelloServlet掛載到/hello這個(gè)路徑上,因此,執(zhí)行這個(gè)腳本后,可以通過(guò)http://localhost:3000/hello調(diào)用HelloServlet,簡(jiǎn)單地只是顯示字符串
"hello,ruby servlet"。
這個(gè)簡(jiǎn)單的例子沒(méi)有任何交互,并且顯示的html也是寫(xiě)死在腳本中,顯然更好的方式應(yīng)該通過(guò)模板來(lái)提供,可以使用Ruby標(biāo)準(zhǔn)庫(kù)的erb模板。再給個(gè)有簡(jiǎn)單交互的例子,現(xiàn)在要求用戶輸入姓名,然后提交給HelloServlet,顯示"hello,某某某"。嗯,來(lái)個(gè)最簡(jiǎn)單的提交頁(yè)面:
<html>
<body>
<center>
<form action="http://localhost:3000/hello" method="post">
<input type="text" name="name" size=10/><br/><br/>
<input type="submit" name="submit" value="submit"/>
</form>
</center>
</body>
</html>
注意到,我們采用POST方法提交。再看看erb模板:
<html>
<head></head>
<body>
hello,<%=name%>
</body>
</html>
其中的name是我們將要綁定的變量,根據(jù)用戶提交的參數(shù)。最后,修改下HelloServlet:
require 'webrick'
require 'net/http'
include WEBrick
class HelloServlet < HTTPServlet::AbstractServlet
def do_GET(req,resp)
do_POST(req,resp)
end
def do_POST(req,resp)
name=req.query["name"]
#讀取模板文件
template=IO.read(File.dirname(__FILE__)+"/hello.html")
message=ERB.new(template)
resp["Content-Type"]="text/html;charset=utf-8"
resp.body=message.result(binding)
end
end
if $0==__FILE__
server=HTTPServer.new(:Port=>3000)
server.mount("/hello",HelloServlet)
trap("INT"){ server.shutdown }
server.start
end
與前一個(gè)例子相比,不同點(diǎn)有二,一是通過(guò)
req.query["name"]獲得用戶提交的參數(shù)name,二是resp的body是由模板產(chǎn)生,而不是寫(xiě)死在代碼中。在一些臨時(shí)報(bào)表、臨時(shí)數(shù)據(jù)的展示上,可以充分利用Ruby的這些標(biāo)準(zhǔn)庫(kù)來(lái)快速實(shí)現(xiàn)。