A web server
JavaWebServer answers requests with Ring functions; jHttpGet and jHttpPost call it from the same program.
What you will learn#
- routes with
onGet,onPostand a part:name, - the request:
param,query,body, - the answer: a text,
[status, type, text]orjWebJson, - a client that waits while the handlers run.
The program#
# Tutorial 25: a web server and a client in one program
load "java.ring"
# 1. the server: a route is a path and the name of a Ring function (port 0 takes a free port)
oServer = new JavaWebServer(0)
oServer.onGet("/","home")
oServer.onGet("/hello/:name","hello")
oServer.onGet("/search","search")
oServer.onPost("/echo","echo")
oServer.onGet("/api/book","book")
cBase = oServer.url()
? "the server runs"
# 2. the client waits while the Ring functions answer
aAnswer = jHttpGet(cBase + "/")
? "" + aAnswer[1] + " " + aAnswer[2]
# 3. a part of the path (:name) and the query string
? jHttpGet(cBase + "/hello/Ring")[2]
? jHttpGet(cBase + "/search?q=java&page=2")[2]
# 4. a POST with a body
? jHttpPost(cBase + "/echo","a text","text/plain")[2]
# 5. JSON: a list of [name, value] pairs is an object
aAnswer = jHttpGet(cBase + "/api/book")
? aAnswer[2]
# 6. a path without a route is a 404
? jHttpGet(cBase + "/nothing")[1]
? "requests handled: " + oServer.requests()
oServer.close()
func home oRequest
return "<h1>Hello</h1>"
func hello oRequest
return "Hello " + oRequest.param("name") + "!"
func search oRequest
return "searching " + oRequest.query("q") + " on page " + oRequest.query("page")
func echo oRequest
return [201,"text/plain","you sent: " + oRequest.body()]
func book oRequest
return jWebJson([["title","The Hobbit"],["year",1937],["tags",["fantasy","classic"]]])the server runs
200 <h1>Hello</h1>
Hello Ring!
searching java on page 2
you sent: a text
{"title":"The Hobbit","year":1937,"tags":["fantasy","classic"]}
404
requests handled: 6How it works#
The server of the JDK runs on its own threads, but the handlers are Ring functions that run on the Ring thread, when the program waits. jHttpGet waits in the way that lets them run, so a server and its client can live in one program. A program that only serves calls oServer.run(). See Web server.
Exercises#
- Add a route that returns the time as JSON.
- Keep a counter in a global variable and show it on
/. - Add a
notFoundhandler with a nicer page.