How to show different content based on the path in Racket web servlets?

天涯浪子 提交于 2019-12-06 06:04:22

问题


I'm trying to follow the tutorial on the Racket guide on simple web apps, but can't get one, basic, basic thing.

How can you have a servlet serve different content based on the request URL? Despite my scouring, even the huge blog example was one big file and everything handled with huge get query strings behind my back. How can I do anything based on URLs? Clojure's Noir framework puts this basic feature big up front on the home page (defpage) but how to do this with Racket?


回答1:


The URL is part of the request structure that the servlet receives as an argument. You can get the URL by calling request-uri, then you can look at it to do whatever you want. The request also includes the HTTP method, headers, and so on.

But that's pretty low-level. A better solution is to use dispatch-rules to define a mapping from URL patterns to handler functions. Here's an example from the docs:

(define-values (blog-dispatch blog-url)
  (dispatch-rules
   [("") list-posts]
   [("posts" (string-arg)) review-post]
   [("archive" (integer-arg) (integer-arg)) review-archive]
   [else list-posts]))

Make your main servlet handler blog-dispatch. The URL http://yoursite.com/ will be handled by calling (list-posts req), where req is the request structure. The URL http://yoursite.com/posts/a-funny-story will be handled by calling (review-post req "a-funny-story"). And so on.



来源:https://stackoverflow.com/questions/18025366/how-to-show-different-content-based-on-the-path-in-racket-web-servlets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!