1

我有一个运行良好的 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。我所有的路线都一样。

你知道我该怎么做吗?

谢谢。格雷格

4

2 回答 2

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")))  
  }
}
于 2012-10-08T08:26:06.003 回答
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对象

于 2012-10-08T08:52:38.530 回答