How does spray find resources - e.g. javascript

2019-04-28 21:59发布

问题:

It was simple to build my first servlet with spray-io.

But the recources referenced in the header are never found.

< head> ... < script src="javascript/jquery/jquery-1.9.1.js"/> ... < / head>

In which directory does one have to put those recsources, or how can spray be directed to look up there?

Simple question, but I could not figure out.

Many thankx

Girgl

回答1:

With Spray routing, I use these directives -

pathPrefix("css") { get { getFromResourceDirectory("css") } } ~
pathPrefix("js") { get { getFromResourceDirectory("js") } } ~ 

"css" and "js" have to be in src/main/resources directory



回答2:

If you are using spray routing, then it should be easy, just provide a route for your static resources. For example you can do the following:

Let's say that your static resources are in /css, /js and /img folders:

def staticPrefixes = List("css", "js", "img") map { pathPrefix(_) } reduce { _ | _ }

with pathPrefix you are making each path a prefix of an unmatched path. Then you need a directive to extract path to static file from the request, for example you can do it like this:

def stripLeadingSlash(path: String) = if (path startsWith "/") path.tail else path

val staticPath =
  staticPrefixes &
  cache(routeCache()) &
  extract(ctx ⇒ stripLeadingSlash(ctx.request.uri.path.toString))

then construct your route which would manage your resources:

val staticRoutes =
    get {
      staticPath { path ⇒
        getFromResource(path.toString)
      }
    }


标签: spray