如何在java play框架中获取查询字符串参数?
我是java play框架的新手。 我已经设置了所有正常路线,如/ something /:somthingValue和所有其他路线。 现在我想创建路由接受查询参数,如
/东西?X = 10&y = 20&Z = 30
在这里,我希望在“?”之后获得所有参数。 as key ==> value pair。
您可以将查询参数连接到routes文件中:
http://www.playframework.com/documentation/2.0.4/JavaRouting “使用默认值的参数”部分
或者你可以在你的行动中要求他们:
public class Application extends Controller { public static Result index() { final Set> entries = request().queryString().entrySet(); for (Map.Entry 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.")); } }
例如,控制台上打印http://localhost:9000/?a=1&b=2&c=3&c=4
:
[debug] application - a [1] [debug] application - b [2] [debug] application - c [3, 4] [debug] application - 1 [debug] application - 2 [debug] application - 3
请注意,url中的c
是两次。
在Play 2.5.x中,它直接在conf/routes
,其中可以放置默认值:
# Pagination links, like /clients?page=3 GET /clients controllers.Clients.list(page: Int ?= 1)
在你的情况下(使用字符串时)
GET /something controllers.Somethings.show(x ?= "0", y ?= "0", z ?= "0")
使用强类型时:
GET /something controllers.Somethings.show(x: Int ?= 0, y: Int ?= 0, z: Int ?= 0)
有关详细说明,请参阅: https : //www.playframework.com/documentation/2.5.x/JavaRouting#Parameters-with-default-values 。
您可以将所有查询字符串参数作为Map获取:
Controller.request().queryString()
此方法返回Map
对象。
在Java/Play 1.x
您可以使用:
Request request = Request.current(); String arg1 = request.params.get("arg1"); if (arg1 != null) { System.out.println("-----> arg1: " + arg1); }
您可以使用FormFactory :
DynamicForm requestData = formFactory.form().bindFromRequest(); String firstname = requestData.get("firstname");