Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request parameter with Play Framework?

I am learning play framework and understand that I can map a request such as /manager/user as:

  GET      /manage/:user    Controllers.Application.some(user:String) 

How would I map a request like /play/video?video_id=1sh1?

like image 616
user2054833 Avatar asked Feb 12 '13 22:02

user2054833


People also ask

Can a get request have query parameters?

You may use the queryParam() method not just once, but as many times as the number of query parameters in your GET request.

What are request query parameters?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

What is routing in Java?

A Router is an actor that routes incoming messages to outbound actors. The router routes the messages sent to it to its underlying actors called 'routees'.


1 Answers

You have at least two possibilities, let's call them approach1 and approach2.

  1. In the first approach you can declare a routes param with some default value. 0 is good candidate, as it will be easiest to build some condition on top of it. Also it's typesafe, and pre-validates itself. I would recommend this solution at the beginning.
  2. Second approach reads params directly from request as a String so you need to parse it to integer and additionally validate if required.

routes:

GET     /approach1      controllers.Application.approach1(video_id: Int ?=0) GET     /approach2      controllers.Application.approach2 

actions:

public static Result approach1(int video_id) {     if (video_id == 0) return badRequest("Wrong video ID");     return ok("1: Display video no. " + video_id); }  public static Result approach2() {     int video_id = 0;      if (form().bindFromRequest().get("video_id") != null) {         try {             video_id = Integer.parseInt(form().bindFromRequest().get("video_id"));         } catch (Exception e) {             Logger.error("int not parsed...");         }     }      if (video_id == 0) return badRequest("Wrong video ID");     return ok("2: Display video no. " + video_id); } 

PS: LOL I just realized that you want to use String identifier... anyway both approaches will be similar :)

like image 133
biesior Avatar answered Sep 20 '22 03:09

biesior