2012-10-08 56 views
1

我有一個運行良好的Play 2.0框架,我希望能夠向所有路由添加一個特定的get參數(僅由be知道)。該參數應該被路由忽略。播放:添加一個全局可選的GET參數到所有路由

我解釋一下。 假設我有這樣的路線:

GET  /add/:id    controllers.MyController.add(id : Int) 
GET  /remove/:id   controllers.MyController.remove(id : Int) 

我要的是,例如,http://mydomain.com/add/77mySecretParam = OK還是到controllers.MyController.add(ID:智力)?,然後我能得到請求對象中的mySecretParam。和一樣我的路線相同。

你有什麼想法我該怎麼辦?

謝謝。 格雷格

回答

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"))) 
    } 
} 
+0

就是這樣。一個Apache配置刪除了我的查詢字符串... – Greg

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對象