Hi,
In message <007b01c227bb$8d13fc20$dd31200a@JAZZ>,
`"Norman Makoto Su" <normsu@slab.tnr.sharp.co.jp>' wrote:
> When using WEBrick, it seems that a new servlet instance is created each time a
> client accesses it. If so, is there anyway to prevent this (so that only one
> instance of the servlet is created initially and all subsequent accesses are
> referred to the same servlet)? In other words, I want it to print out "Count
> 0", "Count 1", etc.
There are two approaches.
The first one uses the class variable:
class HelloServlet < HTTPServlet::AbstractServlet
@@i = 0
def do_GET(req, res)
res.body = "<HTML>Count #{@@i}</HTML>"
res['Content-Type'] = "text/html"
@@i += 1
end
end
However, since the counter will be shared by all instances,
this approach lacks in flexibility. Furthermore, in order to
make it thread safety, it is necessary to add more code.
The second one uses the data container created in the
exterior of the servlet:
class Counter
attr_reader :value
def initialize
@m = Mutex.new
@value = 0
end
def +(i)
@m.synchronize{ @value += i }
end
end
class HelloServlet2 < HTTPServlet::AbstractServlet
def initialize(server, counter)
@counter = counter
end
def do_GET(req, res)
res.body = "<HTML>Count #{@counter.value}</HTML>"
res['Content-Type'] = "text/html"
@counter += 1
end
end
s = HTTPServer.new( :Port => 2000 )
counter = Counter.new
s.mount("/hello21", HelloServlet2, counter)
s.mount("/hello22", HelloServlet2, counter)
trap("INT"){ s.shutdown }
s.start
By this approach, the completeness of data can be left to
the container. (It will be effective when more complicated
method). Moreover, it can choose whether for two or more
mount points to share a counter.
hope this helps.
--
gotoyuzo