Reputation: 167
I have a Play 2.0 framework that is working well and I want to be able to add a specific get parameter (known only by be) to all routes. That parameters should be ignore by routes.
I explain. Suppose I have routes like :
GET /add/:id controllers.MyController.add(id : Int)
GET /remove/:id controllers.MyController.remove(id : Int)
What I want is, for example, that http://mydomain.com/add/77?mySecretParam=ok still goes to controllers.MyController.add(id : Int) and then I could get mySecretParam in request object. And the same for all my routes.
Do you have any idea how can I do ?
Thanks. Greg
Upvotes: 1
Views: 460
Reputation: 7542
package controllers
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
object Application extends Controller {
def mySecretParam(implicit request: Request[_]): Option[String] = {
val theForm = Form(of("mySecretParam" -> nonEmptyText))
val boundForm = theForm.bindFromRequest
if(!boundForm.hasErrors)
Option(boundForm.get)
else
None
}
def index = Action { implicit request=>
Ok(views.html.index(mySecretParam.getOrElse("the default")))
}
}
Upvotes: 3
Reputation: 217
Here's Java:
Your route
GET /hello/:id controllers.Application.hello(id: Int)
in Application controller
public static Result hello(int id){
//Retrieves the current HTTP context, for the current thread.
Context ctx = Context.current();
//Returns the current request.
Request req = ctx.request();
//you can get this specific key or e.g. Collection<String[]>
String[] param = req.queryString().get("mySecretParam");
System.out.println("[mySecretParam] " + param[0]);
//[req uri] /hello/123?mySecretParam=ok
System.out.println("[Request URI] "+req.uri().toString());
System.out.println("[Hello-ID]: " + id); //the function parameter in controller
return ok("[Hello-ID]: " + id + "\n[mySecretParam] " + param[0]);
}
Your console output
[info] play - Application started (Dev)
[Request] GET /hello/123?mySecretParam=imhereyee
[mySecretParam] imhereyee
[Request URI] /hello/123?mySecretParam=imhereyee
[Hello-ID]: 123
The key to your question is Context
object and Request
object from that
Upvotes: 2