The Artima Developer Community
Sponsored Link

Java Buzz Forum
Using Scala pattern matching to implement a URL handler

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Sam Newman

Posts: 800
Nickname: padark
Registered: Feb, 2004

Sam Newman is quite lazy
Using Scala pattern matching to implement a URL handler Posted: Jul 25, 2009 1:21 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Sam Newman.
Original Post: Using Scala pattern matching to implement a URL handler
Feed Title: magpiebrain
Feed URL: http://feeds.feedburner.com/Magpiebrain
Feed Description: A Java Blog
Latest Java Buzz Posts
Latest Java Buzz Posts by Sam Newman
Latest Posts From magpiebrain

Advertisement

I’ve been playing around with using Scala’s pattern matching support to create a URL handler for use with an embedded Jetty server. This little code snippet creates a Jetty handler that can not only match URLs, but even extract parts of the URL and pass it into the block

protected class MutableHandler extends AbstractHandler {
  override def handle(target: String, request: HttpServletRequest, response: HttpServletResponse) = {
    response.setContentType("text/html");
    val HomePage = "/"
    val StaticResources = new Regex("""/static/(.*)""")
   
    target match {
      case HomePage => {
        ok(response, "Hello!")
      } 
   
      case StaticResources(resource) => {
        ok(response, "You asked for resource " + resource)       
      }
	
      case _ => {           
        notFound(response, "Not Found")       
      }     
    }     
    (request.asInstanceOf[Request]).setHandled(true);     
  }   
} 

The ok, notFound methods simply write the String out to the response stream with the right HTTP code.

The StaticResources regex pulls out everything after the /static/ root. It would be easy to imagine some kind of regex which pulled out the year, month and day from a URL - for example:

val EntriesOnDay = new Regex("""/posts/(\d+)/(\d+)/(\d+)""")
...

target match {
  case EntriesOnDay(year, month, day) => {
    // use year, month, day etc to pull back posts or whatever
  }
}

Read: Using Scala pattern matching to implement a URL handler

Topic: AMD stock sinks on weaker profit margins, worries about chip maker's turnaround Previous Topic   Next Topic Topic: Manhattan Associates posts second-quarter loss, suspends 2009 earnings outlook

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use