How to print HTTP request data in a Play Framework controller action

As a quick note to self, here’s how to just printed some HTTP request information in a Play Framework controller action:

def login = Action { implicit request =>
    println("*** ENTERED 'login' ACTION ***")
    println(s"    content-type: ${request.contentType}")
    println(s"    headers: ${request.headers}")
    println(s"    body: ${request.body}")
    println(s"    query string: ${request.rawQueryString}")
  
    loginForm.bindFromRequest.fold(
        errors => {
            NotFound(Json.toJson(Map(
                "success" -> toJson(false), 
                "msg" -> toJson("Bad Login Data"), 
                "id" -> toJson(0))))
        },
        user => {
            // TODO verify the user is in the database; currently assuming a successful login
            Ok(Json.toJson(Map(
                "success" -> toJson(true),
                "msg" -> toJson("Welcome"),
                "id" -> toJson(0))))
                .withSession("username" -> "alvin", "authenticated" -> "yes")
        }
    )
}

The rest of the code doesn’t matter, I just wanted to show how to access the request information in a Play controller.

(That being said, the withSession code may also be useful. That shows how to create a Play session cookie (PLAY_SESSION)).

Post new comment

The content of this field is kept private and will not be shown publicly.