HTML and Scala together in Servlet Get method

19 views
Skip to first unread message

Hayden Freedman

unread,
Apr 3, 2017, 10:40:23 PM4/3/17
to scalatra-user
I'm putting together a simple little web app with Scalatra and was wondering if I can type HTML and Scala together in a get method. For example:


import org.scalatra._

class ROFLServlet extends Rofl_roster_managementStack {

  get("/") {
    <html>
      <body>
        <h1>Hello, world!</h1>
        Say <a href="hello-scalate">hello to ROFL</a>.
      </body>
    </html>
    
    println("Hello world!")
    println("This is some Scala code I want to run.")
  }
}

So I am trying to send some HTML to the root page and also run some code on the backend. Is this an acceptable usage? It seemed like it was working for me at first but sometimes it doesn't seem to send anything to the front end (I just get a blank page.)

Stefan Ollinger

unread,
Apr 4, 2017, 6:34:14 AM4/4/17
to scalat...@googlegroups.com
Hey,
the expression in the { } curly braces (the argument to `get(..)`) evaluates to its last value.
A Unit is rendered as a blank page. `println` is of type String => Unit, so println("str") will yield a Unit.
You can save the HTML in a value, e.g. val view = <html>...</html> and then return `view`.

Regards,
Stefan
--
You received this message because you are subscribed to the Google Groups "scalatra-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scalatra-use...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Hayden Freedman

unread,
Apr 4, 2017, 10:00:46 AM4/4/17
to scalatra-user
Hello Stefan,

I have modified my code to the following:


import org.scalatra._

class ROFLServlet extends Rofl_roster_managementStack {

  get("/") {
    val view = <html>
      <body>
        <h1>Hello, world!</h1>
        Say <a href="hello-scalate">hello to ROFL</a>.
      </body>
    </html>
    
    println("Hello world!")
    println("This is some Scala code I want to run.")
    return view
  }
}

When I try to compile, I get an error: "Return outside method definition." I'm afraid I don't quite understand what get("/") is doing. Is it a method or a function? Is it able to accept a return value? I am fairly new to Scala so some of the fundamentals may escape me at this point.

Stefan Ollinger

unread,
Apr 4, 2017, 10:35:15 AM4/4/17
to scalat...@googlegroups.com
You dont need to use the keyword `return`.

Please take a look at:
  - https://tpolecat.github.io/2014/05/09/return.html
  - "6.11 Blocks" https://www.scala-lang.org/files/archive/spec/2.12/06-expressions.html.

Sorry if saying "... then return `view`" got you on the wrong track.

Regards,
Stefan

Hayden Freedman

unread,
Apr 4, 2017, 10:58:05 AM4/4/17
to scalatra-user
Thanks for the resources, I'll do some perusing :)
Reply all
Reply to author
Forward
0 new messages