How to get query string parameters in java play framework?

北城余情 提交于 2019-11-30 01:04:21

You can wire in your query parameters into the routes file:

http://www.playframework.com/documentation/2.0.4/JavaRouting in section "Parameters with default values"

Or you can ask for them in your Action:

public class Application extends Controller {

    public static Result index() {
        final Set<Map.Entry<String,String[]>> entries = request().queryString().entrySet();
        for (Map.Entry<String,String[]> entry : entries) {
            final String key = entry.getKey();
            final String value = Arrays.toString(entry.getValue());
            Logger.debug(key + " " + value);
        }
        Logger.debug(request().getQueryString("a"));
        Logger.debug(request().getQueryString("b"));
        Logger.debug(request().getQueryString("c"));
        return ok(index.render("Your new application is ready."));
    }
}

For example the http://localhost:9000/?a=1&b=2&c=3&c=4 prints on the console:

[debug] application - a [1]
[debug] application - b [2]
[debug] application - c [3, 4]
[debug] application - 1
[debug] application - 2
[debug] application - 3

Note that c is two times in the url.

In Play 2.5.x, it is made directly in conf/routes, where one can put default values:

# Pagination links, like /clients?page=3
GET   /clients              controllers.Clients.list(page: Int ?= 1)

In your case (when using strings)

GET   /something            controllers.Somethings.show(x ?= "0", y ?= "0", z ?= "0")

When using strong typing:

GET   /something            controllers.Somethings.show(x: Int ?= 0, y: Int ?= 0, z: Int ?= 0)

See: https://www.playframework.com/documentation/2.5.x/JavaRouting#Parameters-with-default-values for a longer explanation.

You can get all query string parameters as a Map:

Controller.request().queryString()

This method return a Map<String, String[]> object.

In Java/Play 1.x you get them with:

    Request request = Request.current();
    String arg1 = request.params.get("arg1");

    if (arg1 != null) {
        System.out.println("-----> arg1: " + arg1);
    } 

You can use FormFactory:

DynamicForm requestData = formFactory.form().bindFromRequest();
String firstname = requestData.get("firstname");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!