RSS

Archivo de la categoría: Spring

Groovy integration inside a Spring project


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: , ,

Spring I/O 2012


logo springio2012Como las anteriores dos ediciones voy a hacer una pequeña review sobre lo que me ha parecido la Spring I/O de este año. Voy a hacer un post más resumido que otros años por varias razones. La primera es que ya ha pasado más de una semana y creo que no es cuestión de aburrir con un par de posts kilométricos :) . La segunda razón es que a diferencia de otros años no tome muchas notas durante las charlas y me centré en atender, por lo que tengo menos material sobre el que escribir. Empecemos …

Read the rest of this entry »

 
1 comentario

Publicado por en 26 febrero, 2012 en Charlas, Spring

 

Ejemplo básico de Spring MVC con Maven


springsourcelogo

En el siguiente post vamos a hablar un poco de Spring MVC. Pero antes comentar que tengo pensado hacer una serie de post (el primero es este) sobre Spring. En concreto intentaré hablar un poco de proyecto de SpringSource como Spring MVC, Spring Web Flow, Spring Security (O Auth) ó Spring Faces. Además voy a hablar un poco de desarrollo e integración continua y pruebas (Hudson / Jenkins, Sonar, Cobertura, Selenium, Checkstyles, PMD, …). También me gustaría tratar temas de Cloud Computing , siempre como absoluto novato en la materia, analizando herramientas como Google App Engine (GAE) ó Micro Cloud Foundry. Pero para ello todavía queda …. así que empezaré con Spring MVC.

Read the rest of this entry »

 
8 comentarios

Publicado por en 10 septiembre, 2011 en Spring, Spring MVC

 

Etiquetas: , , , , ,

AOP – Programación Orientada a Aspectos


La programación orientada a aspectos (AOP) es una metodología que sirve para complementar a la programación orientada a objetos clásica (OOP).La OOP es muy útil para implementar la lógica de nuestra aplicación. Sin embargo se ve limitada a la hora de incluir una serie de funcionalidades que se usan en diferentes puntos en nuestra aplicación y que en inglés se conocen como crosscutting concerns. Entre estos elementos podrían estar trazar nuestra aplicación (logging), el cacheo de la información o la validación de los argumentos en los distintos métodos.

Read the rest of this entry »

 
Dejar un comentario

Publicado por en 31 marzo, 2011 en Spring

 

Etiquetas: , , ,

 
Seguir

Recibe cada nueva publicación en tu buzón de correo electrónico.

Únete a otros 66 seguidores

%d bloggers like this: