Thursday, March 1, 2012

Jetty server

//src: http://www.redtoad.ca/ataylor/2012/02/simple-servlets-in-groovy/

@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.26')
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletConfig;
 
class SimpleGroovyServlet extends HttpServlet {
    def requestHandler
    def context
    void init(ServletConfig config) {
        super.init(config)
        context = config.servletContext
    }
    void service(HttpServletRequest request, HttpServletResponse response) {
        requestHandler.binding = new ServletBinding(request, response, context)
        use (ServletCategory) {
            requestHandler.call()
        }
    }
    static void run(int port, Closure requestHandler) {
        def servlet = new SimpleGroovyServlet(requestHandler: requestHandler)
        def jetty = new Server(port)
        def context = new Context(jetty, '/', Context.SESSIONS)
        context.addServlet(new ServletHolder(servlet), '/*')
        jetty.start()
    }
}

SimpleGroovyServlet.run(8080) { ->
    response.contentType = 'text/plain'
    println "hello world!"
    println "my path is ${request.pathInfo}"
    println "my params are $params"
}

//also try: groovy -l 8080 -e "println 'hello world'"
//alternate: https://github.com/groovypp/gretty/wiki/Getting-Started

No comments:

Post a Comment