Java Play 框架:使用参数重定向到控制器方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21233156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:30:23  来源:igfitidea点击:

Play Framework: Redirect to controller method with arguments

javaplayframeworkhttp-getplayframework-2.2

提问by Matthias Munz

I am building a web application with PLAY framework 2.2.1 and am trying to display all available http get query parameters for the requested site in the address bar, even the ones that are not set in the request. In cases where not all http get parameters are set, I want to add the unset parameters with the default values and make a redirect.

我正在使用 PLAY 框架 2.2.1 构建一个 Web 应用程序,并尝试在地址栏中显示请求站点的所有可用 http get 查询参数,即使是未在请求中设置的参数。在未设置所有 http get 参数的情况下,我想使用默认值添加未设置的参数并进行重定向。

I have a site that can be requested with GET:

我有一个可以通过 GET 请求的站点:

GET /test controllers.Application.test(q:String, w:String ?= null, f:String ?= null, o:String ?= null)

Here is the method that I'd like to have in controllers.Application:

这是我想要的方法controllers.Application

public static Result test(String q, String w, String f, String o){

    ...

    // In case not all parameters where set
    if (reload == 1){
            return redirect(controllers.Application.test(qDefault, wDefault, fDefault, oDefault));
    }
    else {
        ok(...);
    }
}

The problem is that redirect() takes a String and not a Result object.

问题是 redirect() 需要一个 String 而不是 Result 对象。

My first solution is to write

我的第一个解决方案是写

return controllers.Application.test(qDefault, wDefault, fDefault, oDefault);

But unfortunately the adress bar does not update.

但不幸的是地址栏没有更新。

My second solution is to build the string manually:

我的第二个解决方案是手动构建字符串:

return redirect("/test?q=" + query + "&f=" + f + "&w=" + w + "&o=" + showOptions);

This works fine, but is there no other way more elegant way to do this?

这工作正常,但有没有其他更优雅的方法来做到这一点?

采纳答案by Isammoc

Use the routesobject :

使用routes对象:

public static Result index() {
    return redirect(controllers.routes.Application.test(qDefault, wDefault, fDefault, oDefault)); 
}

Source : Official Documentation

来源:官方文档

回答by Sakib Sami

in addition this is also valid

另外这也是有效的

public static Result index() {
    return redirect("path"); 
}