RSS

Groovy integration inside a Spring project

03 Jul

In this post we are going to talk a little bit about how to integrate Groovy (or another Scripting language like JRuby or BeanShell) within a Spring project. Achiving that is not really complicated, the only thing you need to do is add your Groovy scripts with a special schema within your application context. The example I am going to show you is uploaded to my Github account. You can find it right here.

And what are we going to do?. We are create a simple sample, based in the official Spring documentation you may find here or here too. We are going to write our Spring MVC controller, but thanks to Groovy we are going to be able to redefine our controller redirection with no need to compile our code again.

The example is pretty simple, imaging you have a controller related to a specified url (say home.htm). What we want is changing the page the controller eventually render. So we need to write our code using Groovy.

The application structure looks like as follows:
springGroovy structure

We have two controller classes:

  • HomeController: It’s a java class that implements the Controller class imported from Spring MVC. The class itself do nothing, another Controller that we code in Groovy is injected within the class. This Groovy controller will be responsible to redirect the request. So we have to call its handleRequest method inside the handleRequest method of our HomeController.
    package com.hopcroft.examples.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    public class HelloController implements Controller {
    	private Controller helloGroovyController;
    
    	public Controller getHelloGroovyController() {
    		return helloGroovyController;
    	}
    
    	public void setHelloGroovyController(Controller helloGroovyController) {
    		this.helloGroovyController = helloGroovyController;
    	}
    
    	public ModelAndView handleRequest(HttpServletRequest arg0,
    			HttpServletResponse arg1) throws Exception {
    		return helloGroovyController.handleRequest(arg0, arg1);
    	}
    
    }
  • HomeGroovyController: this Groovy class is code in Groovy and as we previously mentioned, do the redirect job. It seems like another Java class but we save it as a Groovy script/file.
    package com.hopcroft.examples.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    public class HelloGroovyController implements Controller {
    
        protected final Log logger = LogFactory.getLog(getClass());
    
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            logger.info("Returning index view");
    
            return new ModelAndView("index.jsp");
        }
    
    }

Wiring the controller in the Spring context.

To define the controller within our context we need to use the tag. Take a look at the context definition below.

<pre class="brush: xml; gutter: true; first-line: 1">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:soap="http://cxf.apache.org/bindings/soap"
	xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
    http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd"
	default-autowire="byName"&gt;

	&lt;lang:groovy id="helloGroovyController" script-source="classpath:groovy/HelloGroovyController.groovy"&gt;&lt;/lang:groovy&gt;

	&lt;bean name="/helloGroovy.htm" id="controller" class="com.hopcroft.examples.controller.HelloController"&gt;
		&lt;property name="helloGroovyController" ref="helloGroovyController" /&gt;
	&lt;/bean&gt;

&lt;/beans&gt;</pre>

As you may notice, it’s not really difficult to understand. We have two bean definition, one is a Groovy file where you add the script-source property to define the location of the Groovy Controller. The other one is a common bean to which we’ll inject the previous Groovy bean as a property.

And that’s all, now you can deploy your web application to you favourite web container and see how it’s working. You can change your Groovy controller in runtime and notice the changes with no reploying.
Another important thing to bold is the pom file. In order to compile our Groovy file (to be sure that isn’t going to fail once the server is up) we have add the build-helper-maven plugin to our project.

Don’t forget you can read the post in my new blog here

 
2 comentarios

Publicado por en 3 julio, 2012 en groovy, Spring

 

Etiquetas: , ,

2 Respuestas a “Groovy integration inside a Spring project

  1. www.writerscafe.org

    15 diciembre, 2012 at 3:36 pm

    Hello there! Would you mind if I share your blog with my facebook group?
    There’s a lot of folks that I think would really appreciate your content. Please let me know. Many thanks

     
    • hop2croft

      15 diciembre, 2012 at 4:25 pm

      Hi!.
      Thank you for reading the blog. Yeah, of course, feel free to share this blog wherever you may find interesting. Besides, if you wanna share http://java4developers.com/ too, feel free to do it. It’s basically the same blog with a nicer look.

      Regards.

       

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

 
A %d blogueros les gusta esto: