A small example of ruby writing a servlet

Source: Internet
Author: User
Tags require

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".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.