RingJavafor Ring

Web server

JavaWebServer answers HTTP requests with Ring functions (the web server of the JDK, libraries/javalib/web.ring).

JavaWebServer is the counterpart of WebServer of RingDotNet. It uses com.sun.net.httpserver, which is part of the JDK: nothing to download.

Ring
load "java.ring"

oServer = new JavaWebServer("http://localhost:8080")
oServer.onGet("/","home")
oServer.onGet("/user/:id","userPage")
oServer.onPost("/echo","echoApi")
oServer.run()                           # serve until stop() is called

func home oRequest
	return "<h1>Hello from Ring</h1>"

func userPage oRequest
	return jWebJson([["id",oRequest.param("id")],["name","Ann"]])

func echoApi oRequest
	return [201,"text/plain","you sent: " + oRequest.body()]

A handler is a Ring function that gets a JavaRequest. It returns a text (status 200, text/html), [status, contentType, text] or jWebJson(value). An error in a handler is an answer with status 500 (the body is Internal Server Error; the error itself is printed on the console of the server, and showErrors(true) puts its text in the body, for development); a path without a route is a 404, or the answer of the notFound("handler") function.

The server#

MethodMeaning
new JavaWebServer(url)start the server: "http://localhost:8080", or a port number; port 0 takes a free port
url(), requests()the real address (http://127.0.0.1:50321); the number of requests that were handled
onGet(path, handler), onPost, onPut, onDelete, route(method, path, handler)the routes; a part :name of the path takes any text (/user/:id)
notFound(handler)the handler of the paths that no route has
showErrors(show)true: the answer of a failed handler carries the error text (default false)
run(), stop()serve until stop() (call it from a handler)
serveOne(ms)handle the requests that wait, for up to ms milliseconds (for your own loop, for example next to a window)
close()shut the server down

The server runs on Java threads, but the handlers run on the Ring thread, when the program pumps the requests (run(), serveOne(), jSleep(), jWaitUntil(): see Callbacks and threads). A program that is also the client has to wait this way: jHttpGet does.

The request#

MethodMeaning
method(), path(), queryString()"GET", "/user/7", "q=ring&page=2"
query(name), param(name), form(name)a value of the query string, of the route (:name) or of a posted form; "" when there is none
body(), header(name)the body as a text (UTF-8); a header of the request
setHeader(name, value)a header of the response
respond(status, type, text)answer at once (when the handler returned nothing else)
exchange()the HttpExchange of the JDK

Client and JSON#

FunctionMeaning
jHttpGet(url)[status, body]
jHttpPost(url, body, contentType)[status, body]
jHttpSend(method, url, body, contentType)PUT, DELETE ...
jJsonText(value)the JSON text of a Ring value: a list whose items all are [name, value] pairs is an object, any other list an array; control characters are escaped
jJsonArray(list)a list that is always an array: jJsonArray([["Ann","Cairo"],["Bob","Giza"]]) (rows of [text, value] would look like an object otherwise)
jWebJson(value)the answer of a handler: status 200, application/json

Samples#

samples/UsingJava/introduction/10_web.ring is a server and a client in one program; samples/UsingJava/ecosystem/07_rest_api.ring is a REST API for notes with JavaDatabase.

samples/UsingJava/introduction/10_web.ring
samples/UsingJava/introduction/10_web.ring
# A web server and a client in one program: the handlers are Ring functions
load "java.ring"

oServer = new JavaWebServer(0)                     # port 0: a free port
oServer.onGet("/","home")
oServer.onGet("/hello/:name","hello")
oServer.onPost("/add","addNumbers")
oServer.onGet("/people","people")
oServer.notFound("missing")

cBase = oServer.url()
? "server at " + left(cBase,17) + "..."

aAnswer = jHttpGet(cBase + "/")
? "" + aAnswer[1] + " " + aAnswer[2]

aAnswer = jHttpGet(cBase + "/hello/Ring")
? "" + aAnswer[1] + " " + aAnswer[2]

aAnswer = jHttpPost(cBase + "/add","a=20&b=22","application/x-www-form-urlencoded")
? "" + aAnswer[1] + " " + aAnswer[2]

aAnswer = jHttpGet(cBase + "/people")
? "" + aAnswer[1] + " " + aAnswer[2]

aAnswer = jHttpGet(cBase + "/nothing")
? "" + aAnswer[1] + " " + aAnswer[2]

oServer.close()

func home oRequest
	return "Welcome"

func hello oRequest
	return "Hello " + oRequest.param("name")

func addNumbers oRequest
	return "" + (0 + oRequest.form("a") + oRequest.form("b"))

func people oRequest
	return jWebJson([
		[ "people", [
			[["name","Ann"],["age",31]],
			[["name","Bob"],["age",25]]
		] ]
	])

func missing oRequest
	return [404,"text/plain","no page " + oRequest.path()]
Output
server at http://127.0.0.1:...
200 Welcome
200 Hello Ring
200 42
200 {"people":[{"name":"Ann","age":31},{"name":"Bob","age":25}]}
404 no page /nothing

t23_web.ring runs the server against the client of the same program (routes, parameters, forms, JSON, errors, headers).

RingJava - use Java classes and methods from Ring programs.