How to extract value from Path parameters in play2 mini?

384 Views Asked by At

The method I will use is DELETE request, and I have this url for web service call:

http://www.localhost:9000/example/com/foo/bar

I want to extract /foo and /bar and store it in a variable.

Does anybody know how to do this? Thanks!

I'm using play2-mini for web service and dispatch for scala for making http request.

2

There are 2 best solutions below

1
On

Play has a very sophisticated way of passing parameters and that is through Routes definition. In your conf/Routes file define a Route like

GET  /example/com/:foo  controllers.yourcontroller.deleteAction(foo: String)

when you will enter

http://www.localhost:9000/example/com/user

in your browser, deleteAction defined by your Controller will be invoked and string "user" will be passed to it in its parameter foo. there you can manipulate it. Note that part of URI followed by colon is dynamic. It will accept anything that fulfills requirement of being a string and will forward it to deleteAction by storing it in foo variable.

0
On

You can use regexp as shown in the following code :

object App extends Application { 
  def route = Routes(
    Through("/people/(.*)".r) {groups: List[String] =>
      Action{ 
        val id :: Nil = groups
        Ok(<h1>It works with regex!, id: {id}</h1>).as("text/html") 
      }
    }, 
    {
      case GET(Path("/coco")) & QueryString(qs) => Action{ request =>
        println(request.body)
        println(play.api.Play.current)
        val result = QueryString(qs,"foo").getOrElse("noh")
        Ok(<h1>It works!, query String {result}</h1>).as("text/html") }

      case GET(Path("/cocoa")) => Action{ request =>
        Ok(<h1>It works with extractors!</h1>).as("text/html") }
      },
    Through("/flowers/id/") {groups: List[String] =>
      Action{ 
        val id :: Nil = groups
        Ok(<h1>It works with simple startsWith! -  id: {id}</h1>).as("text/html") 
      }
    }
  )
}