先看个最简单例子输出hello到浏览器:
require 'webrick'
require 'net/http'
WEBrick
HelloServlet < HTTPServlet::AbstractServlet
def hello(resp)
resp["Content-Type"]="text/html;char=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
$0__FILE__
server=HTTPServer.(:Port=>3000)
server.mount("/hello",HelloServlet)
trap("INT"){ server.shutdown }
server.start
end
是不是跟java很像?所有serlvet都要继承自HTTPServlet::AbstractServlet并实现do_GET或者do_POST思路方法在这行代码:
server=HTTPServer.(:Port=>3000)
我们启动了个HTTP Server端口是3000然后将HelloServlet挂载到/hello这个路径上因此执行这个脚本后可以通过http://localhost:3000/helloHelloServlet简单地只是显示串"hello,ruby servlet"
这个简单例子没有任何交互并且显示html也是写死在脚本中显然更好方式应该通过模板来提供可以使用Ruby标准库erb模板再给个有简单交互例子现在要求用户输入姓名然后提交给HelloServlet显示"hello,某某某"嗯来个最简单提交页面:
<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是我们将要绑定变量根据用户提交参数最后修改下HelloServlet:
require 'webrick'
require 'net/http'
WEBrick
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.(template)
resp["Content-Type"]="text/html;char=utf-8"
resp.body=message.result(binding)
end
end
$0__FILE__
server=HTTPServer.(:Port=>3000)
server.mount("/hello",HelloServlet)
trap("INT"){ server.shutdown }
server.start
end
和前个例子相比区别点有 2是通过req.query["name"]获得用户提交参数name 2是respbody是由模板产生而不是写死在代码中在些临时报表、临时数据展示上可以充分利用Ruby这些标准库来快速实现
最新评论