我有一个运行良好的Play 2.0框架,我希望能够为所有路由添加特定的get参数(仅由be知道)。这些参数应该被路由忽略。
我解释一下。 假设我有以下路线:
GET /add/:id controllers.MyController.add(id : Int)
GET /remove/:id controllers.MyController.remove(id : Int)
我想要的是,例如,http://mydomain.com/add/77 ?mySecretParam = ok 仍然转到 controllers.MyController.add(id:Int)然后我可以在请求对象中获取mySecretParam。对于所有我的路线也一样。
你知道我该怎么办?
感谢。 格雷格
答案 0 :(得分:3)
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")))
}
}
答案 1 :(得分:2)
这是Java:
您的路线
GET /hello/:id controllers.Application.hello(id: Int)
应用程序控制器中的
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]);
}
您的控制台输出
[info] play - Application started (Dev)
[Request] GET /hello/123?mySecretParam=imhereyee
[mySecretParam] imhereyee
[Request URI] /hello/123?mySecretParam=imhereyee
[Hello-ID]: 123
您问题的关键是Context
对象和来自该
Request
对象