Scala play 2.0 get request header

I am converting part of my java code to scala, and I would like to be able to get a specific header and return it as a string.

In java I have:

return request().getHeader("myHeader") 

In scala, I was not able to achieve the same. Any help would be greatly appreciated! Thanks!

+6
source share
2 answers

You can write:

 request.get("myHeader").orNull 

If you want something essentially the same as your Java string. But you do not!

request.get("myHeader") returns Option[String] , which means Scala is a way to encourage you to write code that will not throw a null exception pointer.

You can handle Option various ways. For example, if you want to specify a default value:

 val h: String = request.get("myHeader").getOrElse("") 

Or if you want to do something with the header, if it exists:

 request.foreach { h: String => doSomething(h) } 

Or simply:

 request foreach doSomething 

See this trickster for more details.

+7
source

When I tried to answer above for scala with playframework 2.2:

 request.get("myHeader").getOrElse("") 

This gives me the error below:

Get is not a member of play.api.mvc.Request [play.api.mvc.AnyContent]

When i use:

 request.headers.get("myHeader").getOrElse("") 

Now it works. I suggest using this.

+4
source

Source: https://habr.com/ru/post/920983/


All Articles