Showing posts with label Hibernate Framework. Show all posts
Showing posts with label Hibernate Framework. Show all posts

Tuesday, 29 January 2013

Anatomy Of The Default OpenShift Spring Web Application

OpenShift lets users create different kind of applications by using cartridges, including Spring applications running on JBoss EAP6. As confirmed by Kazaag on StackOverflow, porting a Spring application developed on Tomcat 7 on JBoss EAP6 should not be a hassle, especially if Tomcat specific features are not used in the application.

The purpose of this post is to discuss the default Spring application offered by OpenShift. On top of typical Spring files, a couple of jboss files are included:
  • jboss-as-spring-mvc-context.xml - This is the equivalent of the servlet-context.xml file in a simple Spring Web MVC application without annotations.
  • jboss-deployment-structure.xml - This file is about solving classloader issues, which is not typical of Spring applications. Thanks to Thomas' answer on StackOverflow, we know this file is not necessary in most cases.
  • spring-quickstart-ds.xml - Registers IronJacamar, JBoss' JCA implementation. One could use Spring's implementation instead.
  • infrastructure.xml - Registers the entity manager factory in JNDI, and enables the JTA transaction management.
Remaining files are typical of Spring MVC applications without annotations.


Tuesday, 8 January 2013

Spring Selenium Tests With Annotations

This post describes how to implement Selenium tests in Java. It is inspired from the post by Alex Collins, with annotations. The code is available on GitHub in the Spring-Selenium-Test directory. Some alternative and much lighter techniques are available to unit test a Spring MVC application. To unit test services, see here.

Page, Configuration & Controller

We create a simple page with 'Hello World':
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Welcome !!!</title>
</head>
<body>
  <h1>
   Hello World !
  </h1>
</body>
</html>
We keep our controller very simple:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}
and our controller too:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

}

For Selenium Testing

We create a configuration for testing. It provides the URL to open the application locally. The application is opened with Firefox:
@Configuration
public class TestConfig {

    @Bean
    public URI getSiteBase() throws URISyntaxException {
        return new URI("http://localhost:10001/spring-selenium-test-1.0.0");
    }

    @Bean(destroyMethod="quit")
    public FirefoxDriver getDrv() {
        return new FirefoxDriver();
    }

}
We also define an abstract class as a basis for all tests. It automatically closes Firefox after the test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ TestConfig.class })
public abstract class AbstractTestIT {

    @Autowired
    protected URI siteBase;

    @Autowired
    protected WebDriver drv;

    {
        Runtime.getRuntime().addShutdownHook(new Thread() {
           @Override
           public void run() {
                drv.close();
           }
        });
    }

}
And we implement a selenium test where we make sure our page contains 'Hello World':
public class SeleniumTestIT extends AbstractTestIT {

    @Test
    public void testWeSeeHelloWorld() {
        drv.get(siteBase.toString());
        assertTrue(drv.getPageSource().contains("Hello World"));
    }

}
The maven dependencies are the same as those described in Alex Collins's post.

Building The Application

If you build the application, it will open and close firefox automatically. The test will be successful.

Sunday, 18 November 2012

Spring Internationalization Example (with Annotations)

Spring InternationalizationThis post describes how to implement message internationalization in Spring. The code example is available from GitHub in the Spring-MVC-Internationalization directory. It is based on the Spring MVC with annotations example.

Internationalization

We define two resource bundles (setA and setB) containing string translations for German, French and English. These are created in the src/main/resources maven directory.

Configuration

We need to create:
  • a ResourceBundleMessageSource bean to load the string translations
  • a LocaleChangeInterceptor bean which will intercept requests and extract a parameter value (if available) to detect language changes
  • a SessionLocaleResolver bean to store the user's locale preference in the session
  • to register the LocaleChangeInterceptor in the interceptor registry
 We extend our web configuration:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    ...

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource result
            = new ResourceBundleMessageSource();

        String[] basenames = {
            "i18n.setA.setA",
            "i18n.setB.setB"
        };

        result.setBasenames(basenames);

        return result;

    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor result = new LocaleChangeInterceptor();
        result.setParamName("lang");

        return result;

    }

    @Bean
    public LocaleResolver localeResolver() {

        SessionLocaleResolver result = new SessionLocaleResolver();
        result.setDefaultLocale(Locale.ENGLISH);

        return result;

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}

Controller

We simply our controller a lot:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

}

JSP Page

We only keep the index.jsp page, where we add links to change the language of displayed messages:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<!doctype html>
<html lang="en">
<head>
  <title>Welcome To Spring MVC Internationalization !!!</title>
</head>
<body>
  <h1>Spring MVC Internationalization !!!</h1>
  <p>Choose:
      <a href="<c:url value='?lang=en'/>">English</a>
      | <a href="<c:url value='?lang=fr'/>">French</a>
      | <a href="<c:url value='?lang=de'/>">German</a>
  </p>

  <p>Greetings: <spring:message code="greetings" text="missing" /></p>
  <p>Text 2: <spring:message code="text2" text="missing" /></p>
  <p>Current: <c:out value="${pageContext.response.locale}" /></p>
</body>
</html>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8383/spring-mvc-internationalization/

The main page will be displayed:


If you click on German, the German text is displayed:


More Spring related posts here.

Spring Bean XML To Annotation Configuration

Here is an example of converting an XML based bean configuration to a annotation based configuration.

Assuming an XML files contain the following:
<bean id="localeChangeInterceptor"
    class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
</bean>
<bean id="handlerMapping"
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
   <property name="interceptors">
       <ref bean="localeChangeInterceptor" />
   </property>
</bean>
The second beans refers to the first one for initialization.

The corresponding Java with annotation configuration is:
@Configuration
public class MyConfig {

    // ...

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor result
            = new LocaleChangeInterceptor();

        result.setParamName("lang");

        return result;

    }

    @Bean
    public DefaultAnnotationHandlerMapping handlerMapping() {

        DefaultAnnotationHandlerMapping result
            = new DefaultAnnotationHandlerMapping();

        Object[] interceptors = {
            localeChangeInterceptor()
        };

        result.setInterceptors(interceptors);

        return result;

    }

}

More Spring related posts here.

Sunday, 11 November 2012

Introduction To Spring JPA Data Features

This post is a quick introduction to Spring JPA Data's (SJD) features. This Spring module is built on top of the Spring Data Commons module, which is a prerequisite read in order to understand this post.

Features

This module offers several features:
  • JpaRepository<T, ID extends Serializable> - This interface extends the CrudRepository and PageAndSortingRepository interfaces of the Spring Data Commons module. It offers a couple of extra flush, find all and delete operations. See here for an operational example.
  • JPA Query Methods - This is a powerful mechanism allowing Spring to create queries from method names in classes/interfaces implementing Repository. For example: List<Invoice> findByStartDateAfter(Date date); is automatically translated into select i from Invoice i where u.startDate > ?1.
  • @Query - Queries can be associated to methods in Repository classes/interfaces. For example, a method can be annotated with @Query("select i from Invoice i where u.startDate > ?1")
  • @Modifying - This annotation can be used in combination with @Query to indicate that the corresponding query will perform modifications. Hence, any outdated entities are cleared first.
  • @Lock - This annotation is used to set the lock mode type (none, optimistic, pessimistic, etc...) for a given @Query.
  • JpaSpecificationExecutor and Specification - This interface adds a couple find and count of methods to repository classes/interfaces. All, have a Specification  parameter, which add predicates (i.e., where clauses) to corresponding queries.
  • Auditable, AbstractPersistable and AbstractAuaditable - The Auditable interface allows one to track modifications made to an entity (creation, last modification...). The AbstractPersistable and AbstractAuditable are abstract class facilities avoiding the boilerplate code.
  • MergingPersistenceUnitManager - If a developer decides to modularize his/her application, he/she may still want to use a unique persistence unit, even though they are declared in separate XML file. The MergingPersistenceUnitManager solves this issue.
At last, to enable JPA repositories, the:

    @EnableJpaRepositories("com.my.repositories")

should be set on a Java @Configuration class.

More Spring related posts here.

Introduction To Spring Data Commons Features

This post is a quick introduction to Spring Data Common's (SDC) features.

Features

This Spring module provides a set of interfaces to manipulate data in repositories:
  • Repository - This is a marker interface indicating which object are going to access the repository.
  • CrudRepository<T, ID extends Serializable> - This interface extends Repository and provides a set of CRUD (Create, Read, Update, Delete) methods to manipulate T objects having ID as a key.
  • PageAndSortingRepository<T, ID extends Serializable> - This interface extends CrudRepository and provides method to fetch T objects in a sorted way or using pages.
  • Pageable & PageRequest - The Pageable interface is implemented by PageRequest. Page requests are created to indicate which page and page sizes should be used to fetch objects from the PageAndSortingRepository interface.
  • Page<T> - This interface contains the fetched objects returned for a given page request.
The above repository interfaces can expose too many methods for some developers. For example, one may not be comfortable with the idea of exposing write methods. The solution is to create your own customized repository interface and annotate it with:

    @RepositoryDefinition(
        domainClass=MyClass.class,
        idClass=MyClassID.class)

Then, copy the the repository methods you want to expose in this customized interface and Spring will deal with them.

There are situations where developers want to implement their own repository interfaces by extending the repository interfaces available in SDC. However, these interfaces should not be instantiated in their applications. To prevent this, they can use the @NoRepositoryBean on these customized interfaces.

More Spring related posts here.

Thursday, 8 November 2012

Spring MVC REST Calls With HTTP Only

This post describes how to perform REST calls to a Spring MVC application using HTTP only. This example is a variation of the Spring MVC REST Calls With Ajax example. The code is available on GitHub in the Spring-REST-With-HTML-Only directory.

Web.xml

We need to add the HiddenHttpMethodFilter to our web.xml. It searches HTML form PUTs for a _method parameter. If the corresponding value is GET, PUT, POST or DELETE, the call is transformed into a REST call before it is transmitted to the controllers:
...
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <servlet-name>MyServlet</servlet-name>
</filter-mapping>
...

Main Page

We replace the buttons by HTML post forms:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <title>Welcome To REST With HTML Only !!!</title>
</head>
<body>
    <h1>Welcome To REST With HTML Only !!!</h1>
    <form action="<c:url value='/MyData/123466/'/>"
          method="post" >
        <input type="hidden" name="_method" value="GET">
        <input type="submit" value="GET">
    </form>
    <form action="<c:url value='/MyData'/>"
          method="post" >
        <input type="hidden" name="time" value="555555">
        <input type="hidden" name="message" value="User PUT call !!!">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="PUT">
    </form>
    <form action="<c:url value='/MyData'/>"
          method="post" >
        <input type="submit" value="POST">
    </form>
    <form action="<c:url value='/MyData/654321'/>"
          method="post" >
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="DELETE">
    </form>
</body>
</html>

Controller

We need to modify our controller for PUT calls:
@Controller
@RequestMapping(value = "/MyData")
public class MyRESTController {

    @RequestMapping(value="/{time}", method = RequestMethod.GET)
    public @ResponseBody MyData getMyData(
            @PathVariable long time) {

        return new MyData(time, "REST GET Call !!!");
    }

    @RequestMapping(method = RequestMethod.PUT)
    public @ResponseBody MyData putMyData(
            @RequestParam("time") long time,
            @RequestParam("message") String message) {

        return new MyData(time, message);
    }

    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody MyData postMyData() {
        return new MyData(
            System.currentTimeMillis(), "REST POST Call !!!");
    }

    @RequestMapping(value="/{time}", method = RequestMethod.DELETE)
    public @ResponseBody MyData deleteMyData(
            @PathVariable long time) {

        return new MyData(time, "REST DELETE Call !!!");
    }

}

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-rest-with-html-only

The main page will be displayed:

Spring MVC REST Calls With HTML Only


If you click on a button, the corresponding JSON will be displayed:

Spring MVC With HTML Only JSON
More Spring related posts here.

Spring MVC REST Calls From Java

Sometimes, web applications running on servers need to access REST resources located on other servers. From a REST perspective, the physical server act as a logical REST client. This example describes how to proceed. It is based on the Spring MVC REST Calls With Ajax example. The code is available on GitHub in the Spring-Server-Side-REST-Call directory.

Controller

To simulate a remote server, we create a fake remote controller:
@Controller
@RequestMapping(value = "/MyRemoteData")
public class MyRemoteController {

    @RequestMapping(value="/{time}", method = RequestMethod.GET)
    public @ResponseBody MyRemoteData getMyRemoteData(
            @PathVariable long time) {

        return new MyRemoteData(
            "My remote data called at: " + time + " !!!");
    }

}
It return a MyRemoteData object as a JSON:
public class MyRemoteData {

    private String data = "";

    public MyRemoteData() { }

    public MyRemoteData(String message) {
       this.data = message;
    }

    // Setter & Getters

}
We simplify our existing controller to a simple GET. It uses Spring's RestTemplate to make a REST Http GET call to fetch remote data from our 'remote' server:
@Controller
@RequestMapping(value = "/MyData")
public class MyRESTController {

    @RequestMapping(value="/{time}", method = RequestMethod.GET)
    public @ResponseBody MyData getMyData(
            @PathVariable long time) {

        RestTemplate restTemplate = new RestTemplate();

        String remote = "http://localhost:8585/spring-server-side-rest-call/"
            + "MyRemoteData/" + System.currentTimeMillis();

        MyRemoteData mrd = restTemplate.getForObject(
            remote, MyRemoteData.class);

        return new MyData(System.currentTimeMillis(), mrd.getData());

    }

}

Main Page

We simplify our main page and only keep our GET button:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script type="text/javascript"
    src="<c:url value='/resources/js/SpringServerSideRestCall.js'/>">
  </script>
  <title>Welcome To REST With Java !!!</title>
</head>
<body>
  <h1>Welcome To REST With Java !!!</h1>
  <button type="button" onclick="RestGet()">GET</button>
</body>
</html>
Ditto for our javascript:
var prefix = "/spring-server-side-rest-call";

var RestGet = function() {

    $.ajax({
        type: 'GET',
        url:  prefix + "/MyData/" + Date.now(),
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
    });

}

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-server-side-rest-call/

The main page will be displayed:

Spring REST Calls From Java

If you click on get, a pop-up is displayed:


More Spring related posts here.

Wednesday, 7 November 2012

Spring MVC REST Calls With Ajax

This post provides a simple example of REST calls to a Spring MVC web application. It is based on the Serving Static Resources With Spring MVC and Fetching JSON With Ajax In Spring MVC Context example. The code is available on GitHub in the Spring-REST-With-Ajax directory.

Main Page

Our main page contains four buttons linked to Javascript functions performing Ajax calls:
...
<body>
<h1>Welcome To REST With Ajax !!!</h1>
<button type="button" onclick="RestGet()">GET</button>
<button type="button" onclick="RestPut()">PUT</button>
<button type="button" onclick="RestPost()">POST</button>
<button type="button" onclick="RestDelete()">DELETE</button>
</body>
...

Javascript

Our Javascript file contains the four functions:
var prefix = "/spring-rest-with-ajax";

var RestGet = function() {
        $.ajax({
        type: 'GET',
        url:  prefix + "/MyData/" + Date.now(),
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
   });
}

var RestPut = function() {

    var JSONObject= {
        "time": Date.now(),
        "message": "User PUT call !!!"
    };
 
    $.ajax({
        type: 'PUT',
        url:  prefix + "/MyData",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(JSONObject),
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
    });
}

var RestPost = function() {
        $.ajax({
        type: 'POST',
        url:  prefix + "/MyData",
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
    });
}

var RestDelete = function() {
        $.ajax({
        type: 'DELETE',
        url:  prefix + "/MyData/" + Date.now(),
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
    });
}

Controller

Our controller captures the REST calls and returns a JSON. In a real applications, one would perform CRUD operations rather than returning JSONs:
@Controller
@RequestMapping(value = "/MyData")
public class MyRESTController {

    @RequestMapping(value="/{time}", method = RequestMethod.GET)
    public @ResponseBody MyData getMyData(
            @PathVariable long time) {
  
        return new MyData(time, "REST GET Call !!!");
    }
 
    @RequestMapping(method = RequestMethod.PUT)
    public @ResponseBody MyData putMyData(
            @RequestBody MyData md) {
  
        return md;
    }
 
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody MyData postMyData() {
 
        return new MyData(System.currentTimeMillis(),
            "REST POST Call !!!");
    }

    @RequestMapping(value="/{time}", method = RequestMethod.DELETE)
    public @ResponseBody MyData deleteMyData(
            @PathVariable long time) {
  
        return new MyData(time, "REST DELETE Call !!!");
    }
}

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-rest-with-ajax/

The main page will be displayed:



If you click on any button, a pop-up will be displayed:


See here for more about REST • More Spring related posts here.

Tuesday, 6 November 2012

Spring MVC Error Handling

This post describes the different techniques to perform error handling in Spring MVC 3. The code is available on GitHub in the Spring-MVC-Error-Handling directory. It is based on the Spring MVC With Annotations examples.

Handling Exceptions Before Spring 3

Before Spring 3, exceptions were handled with HandlerExceptionResolvers. This interface defines a single method:
ModelAndView resolveException(
  HttpServletRequest request,
  HttpServletResponse response,
  Object handler,
  Exception ex)
Notice it returns a ModelAndView object. Therefore, encountering an error meant being forwarded to a special page. However, this method is not suited for REST Ajax calls to JSONs (for example). In this case, we do not want to return a page, and we may want to return a specific HTTP status code. A solution, described further, is available.

For the sake of this example, two fake CustomizedException1 and CustomizedException2 exceptions have been created. To map customized exceptions to views, one could (and can still) use a SimpleMappingExceptionResolver:
SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {

    SimpleMappingExceptionResolver result
        = new SimpleMappingExceptionResolver();

    // Setting customized exception mappings
    Properties p = new Properties();
    p.put(CustomizedException1.class.getName(), "Errors/Exception1");
    result.setExceptionMappings(p);

    // Unmapped exceptions will be directed there
    result.setDefaultErrorView("Errors/Default");

    // Setting a default HTTP status code
    result.setDefaultStatusCode(HttpStatus.BAD_REQUEST.value());

    return result;

}
We map CustomizedException1 to the Errors/Exception1 JSP page (view). We also set a default error view for unmapped exception, namely CustomizedException2 in this example. We also set a default HTTP status code.

Here is the Exception1 JSP page, the default page is similar:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <title>Welcome To Exception I !!!</title>
</head>
<body>
    <h1>Welcome To Exception I !!!</h1>
    Exception special message:<
    ${exception.specialMsg}
    <a href="<c:url value='/'/>">Home</a>
</body>
</html>
We also create a dummy error controller to help triggering these exceptions:
@Controller
public class TriggeringErrorsController {

    @RequestMapping(value = "/throwCustomizedException1")
    public ModelAndView throwCustomizedException1(
        HttpServletRequest request,HttpServletResponse response)
            throws CustomizedException1 {

        throw new CustomizedException1(
            "Houston, we have a problem!");
    }

    @RequestMapping(value = "/throwCustomizedException2")
    public ModelAndView throwCustomizedException2(
        HttpServletRequest request,HttpServletResponse response)
            throws CustomizedException2 {

        throw new CustomizedException2(
            "Something happened on the way to heaven!");
    }

    ...

}
Before Spring 3, one would declare a SimpleMappingExceptionResolver as a @Bean in web.xml. However, we will use a HandlerExceptionResolverComposite which we will describe later.

We also configure a target page for HTTP status codes in web.xml, which is an other way to deal with issues:
<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/pages/Errors/My404.jsp</location>
</error-page>

What Is New Since Spring 3.X?

The @ResponseStatus annotation is a new mean to set a Http status code when a method is invoked. These are handled by the ResponseStatusExceptionResolver. The @ExceptionHandler annotation facilitates the handling of exceptions in Spring. Such annotations are processed by the AnnotationMethodHandlerExceptionResolver.

The following illustrates how these annotations can be used to set an HTTP status code to the response when our customized exception is triggered. The message is returned in the response's body:
@Controller
public class TriggeringErrorsController {

    ...

    @ExceptionHandler(Customized4ExceptionHandler.class)
    @ResponseStatus(value=HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String handleCustomized4Exception(
        Customized4ExceptionHandler ex) {

        return ex.getSpecialMsg();

    }

    @RequestMapping(value = "/throwCustomized4ExceptionHandler")
    public ModelAndView throwCustomized4ExceptionHandler(

        HttpServletRequest request,HttpServletResponse response)
            throws Customized4ExceptionHandler {

        throw new Customized4ExceptionHandler("S.O.S !!!!");

    }

}
On the user side, if one uses an Ajax call, the error can be retrieved with the following (we are using JQuery):
$.ajax({
    type: 'GET',
    url:  prefix + "/throwCustomized4ExceptionHandler",
    async: true,
    success: function(result) {
        alert('Unexpected success !!!');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status + " " + jqXHR.responseText);
    }
});
Some people using Ajax like to return a JSON with the error code and some message to handle exceptions. I find it overkill. A simple error number with a message keeps it simple.

Since we are using several resolvers, we need a composite resolver (as mentioned earlier):
@Configuration
public class ErrorHandling {

    ...

    @Bean
    HandlerExceptionResolverComposite getHandlerExceptionResolverComposite() {

        HandlerExceptionResolverComposite result
            = new HandlerExceptionResolverComposite();

        List<HandlerExceptionResolver> l
            = new ArrayList<HandlerExceptionResolver>();

        l.add(new AnnotationMethodHandlerExceptionResolver());
        l.add(new ResponseStatusExceptionResolver());
        l.add(getSimpleMappingExceptionResolver());
        l.add(new DefaultHandlerExceptionResolver());

        result.setExceptionResolvers(l);

        return result;

}
The DefaultHandlerExceptionResolver resolves standard Spring exceptions and translates them to corresponding HTTP status codes.

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-mvc-error-handling/

The main page will look like this:

Spring MVC Error Handling

If you click on the Exception 1 link, the following page will display:

Spring MVC Exception Handling

If you click on the Exception 2 link, the following page will display:


If you click on the Exception Handler button, a pop-up will be displayed:

Spring MVC Exception Handling Pop-Up

These techniques are enough to cover error handling in Spring.

More Spring related posts here.

Sunday, 4 November 2012

Fetching JSON With Ajax In Spring MVC Context

This post explains how to fetch a JSON using Ajax from a Spring MVC web application. It is based on the Spring MVC With Annotations and Serving Static Resources With Spring MVC examples. The code is available on GitHub in the Spring-Fetching-JSON-With-Ajax directory.

Main Index Page

We use a simple index.jsp page, where we set a button that fetches a JSON, and a <div> where the result will be displayed:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script type="text/javascript"
    src="<c:url value='/resources/js/FetchingJsonWithAjax.js'/>">
  </script>
  <title>Welcome To Fetching JSON With Ajax !!!</title>
</head>
<body>
    <h1>Fetching JSON With Ajax !!!</h1>
    <div id="theJson"></div>
    <button type="button" onclick="fetch_json()">
        Fetch JSON
    </button>
</body>
</html>

Javascript

On the button, we attach the fetch_json() Javascript method, which is called when the button is clicked:
var fetch_json = function() {

    $.ajax({
        type: 'GET',
        url:  "/spring-fetching-json-with-ajax/getJSON",
        dataType: 'json',
        async: true,
        success: function(result) {

            var tmp = "Fetch time is: " + result.milliTime + " !"
               + "and the JSON is:"
               + JSON.stringify(result);

            $("#theJson").html(tmp);

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Issue fetching the JSON: "
                + textStatus + " "
                + errorThrown + " !");
        }

    });

}
If successful, we set the result on the <div>, else we pop-up a message with the error.

Controller

The controller is kept simple, and a MilliTime object is returned for the Ajax call:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";
    }

    @RequestMapping(value="/getJSON", method = RequestMethod.GET)
    public @ResponseBody MilliTimeItem getJSON() {
        return new MilliTimeItem(System.currentTimeMillis());
    }

}

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-fetching-json-with-ajax/

After clicking on the Fetch JSON button, something similar to the following will be displayed:



More Spring related posts here.

Serving Static Resources With Spring MVC

This post explains how to server static content from a Spring MVC web application. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-Serving-Static-Resources directory.

JSP Page

We keep only the main index.jsp page:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script type="text/javascript"
    src="<c:url value='/resources/js/SomeJavascript.js'/>">
  </script>
  <title>Welcome To Spring Serving Static Resources !!!</title>
</head>
<body>
    <h1>Spring - Serving Static Resources !!!</h1>
    <img border="0"
      src="<c:url value='/resources/img/MyArt.png'/>" alt="My Art" />
</body>
</html>
Regarding static resources:
  • We link JQuery from Google's CDN.
  • We link our own SomeJavascript.js and make sure the URL is properly constructed.
  • In the body, we add an image.

Resources

Spring Project Structure For Resources
In the Spring project itself, we put all the resources under a separate resources directory which does not stand under WEB-INF.
  • Images are stored under /resources/img.
  • Javascript is storted under /resources/js.
Our Javascript is a simple pop-up messages displayed when the HTML document is loaded:
$(document).ready(function() {
    alert("JS loaded successfully!");
});

Web Configuration & Controller

We need to modify our web configuration to add a static resource handler and configure it by specifying where to fetch these:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    ...

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

      registry
        .addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");
    }

}
We also simplify our controller:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";
    }

}

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-serving-static-resources/

The image and the pop-up will be displayed:



More Spring related posts here.

Monday, 29 October 2012

Returning a JSON in Spring (With Annotations)

This post provides the simplest example to return a JSON from a Spring controller. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-Returning-A-JSON directory.

For a full Spring MVC REST calls with Ajax example, see here.

Dependencies

On top of current dependencies, we add the Jackson mapper dependency:
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.10</version>
</dependency>
This dependency enables the conversion of Java objects into a JSON representation.

Data

For this example, we use a simple SomeData class:
public class SomeData {

    private String name;
    private long time;

    public SomeData(String name, long time) {
        this.name = name;
        this.time = time;
    }

    public SomeData() {
        name = "";
        time = System.currentTimeMillis();
    }

    // Setters & Getters

}

Controller

We modify our controller as following:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

    @RequestMapping(value="/getJSON/{name}", method = RequestMethod.GET)
    public @ResponseBody SomeData getJSON(@PathVariable String name) {

        SomeData result
            = new SomeData(name, System.currentTimeMillis());

        return result;

    }

}
The getJSON() method has special annotations usage:
  • @RequestMapping's value contains {name} which will be extracted by Spring an inserted as the parameter value in the method.
  • @ResponseBody's indicates that the body of the response to the user's request must be filled with what is returned by the method. Here, we return a SomeData object. Since we have added the Jackson dependency, Spring will automatically detect it and perform the conversion of this object into its JSON representation.
  • @PathVariable extracts the parameter's name from the URL's {name} and sets its as the parameter value in the getJSON() method.

JSP Index Page

Our index page remains very simple:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome !!!</title>
</head>
<body>
    <h1>
    Welcome To Spring Returning A JSON !!!
    </h1>
    <a href="<c:url value='/getJSON/Arthur'/>">Get JSON for Arthur !!!</a>
</body>
</html>
It contains a link making a call to /getJSON/Arthur.

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8383/spring-returning-a-json/.

The home page will display:


Click on the link to retrieve the JSON:



More Spring related posts here.

Friday, 26 October 2012

Spring FreeMarker Integration Example (With Annotations)

This post provides a simple example of FreeMarker integration within a Spring application. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-FreeMarker-Integration directory.

FreeMarker also offers two great tutorials: the Template Author's Guide and the Programmer's Guide.

Configuration

We need to modify our Web configuration to set a FreeMarker viewer and a FreeMarker configurer:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {

        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setCache(false);
        // resolver.setPrefix("");
        resolver.setSuffix(".ftl");

        return resolver;

    }

    @Bean
    public FreeMarkerConfigurer getFreemarkerConfig() {

        FreeMarkerConfigurer result = new FreeMarkerConfigurer();
        result.setTemplateLoaderPath("WEB-INF/pages/");

        return result;

    }

}
Our controller remains very simple:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {

        model.addAttribute("MsTime", System.currentTimeMillis());

        return "Home";

    }

}

FreeMarker Template

We use a simple FreeMarker template:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring FreeMarker Example !!!</title>
</head>
<body>
    This is the Spring FreeMarker Example !!!

    Time is: ${MsTime}!
</body>
</html>

Maven Dependency

We need the following dependency:
 <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.19</version>
</dependency>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8282/spring-freemarker-integration/.

The home page will display:



More Spring related posts here.

Monday, 22 October 2012

Setting Logging Dependencies In Spring

This post describes how to set-up logging dependencies in Spring. It is based on information available in a post by Dave Syer. A reminder on Java logging frameworks is available here. The code example is available at GitHub in the Spring-Logging-Dependencies directory.

Spring uses Jakarta Commons Logging API (JCL). Unfortunately, many people do not like its runtime discovery algorithm. We can disactivate it and use SLF4J with Logback instead. We will use a variation of the Spring MVC with Annotations example to do so.

Here is the modified controller:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {

    private static final Logger LOG
        = LoggerFactory.getLogger(MyController.class);

    @RequestMapping(value = "/")
    public String home(Model model) {

        String s = "Logging at: " + System.currentTimeMillis();
        LOG.info(s);

        model.addAttribute("LogMsg", s);

        return "index";

    }

}
We create a SFL4J logger and log some information with current time in milliseconds.

The maven dependencies are:
<properties>
    ...
    <spring.version>3.1.2.RELEASE</spring.version>
    <slf4j.version>1.7.1</slf4j.version>
    <logback.version>0.9.30</logback.version>
</properties>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
    <type>jar</type>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>${slf4j.version}</version>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
    <type>jar</type>
</dependency>

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>${logback.version}</version>
</dependency>

Once built, one can start the example by browsing: http://localhost:9393/spring-logging-dependencies/. It will display the following:

Spring Logging Configuration

In the logs, you will find the logged statement:

Spring Logging Statement

More Spring posts here.

Monday, 17 September 2012

Spring Security And Annotation Configuration Example

This post is the mix between the Spring MVC with Annotations Example and the Spring Security Configuration Introduction. The code example is available on Github in the Spring-Security-And-Annotation-Config directory.

We are going to add a mandatory login page before one can access the main page of the Spring MVC with Annotations example.

Configuration

First, we create a MyServlet-security.xml file:
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

    http://www.springframework.org/schema/security

    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <http auto-config="true">
    <intercept-url pattern="/*" access="ROLE_USER"/>
  </http>

  <authentication-manager alias="authenticationManager">
    <authentication-provider>
      <user-service>
        <user authorities="ROLE_USER" name="guest" password="guest"/>
      </user-service>
    </authentication-provider>
  </authentication-manager>

</beans:beans>
We rely on the automatic configuration of Spring security, and we request that one must login with ROLE_USER privilege to access any to page of the website. We set an authentication manager and create a simple guest user login, with the guest password.

We add the security filters under contextConfigLocation:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      com.jverstry.Configuration
    </param-value>
  </context-param>

  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
      org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
  </filter>

  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file></welcome-file>
  </welcome-file-list>

</web-app>
At last we add one @ImportSource line in our WebConfig configuration class:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
@ImportResource("/WEB-INF/MyServlet-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {

  @Bean
  public ViewResolver getViewResolver() {

    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("WEB-INF/pages/");
    resolver.setSuffix(".jsp");

    return resolver;

  }

}

Running The Example

After compiling the project, one can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:9191/spring-mvc-with-annotations/

Login with guest guest:


 ...and access the main page:


More Spring related posts here.

Saturday, 15 September 2012

Spring Security Configuration Introduction

This post describes the basic Spring security configuration steps all Spring applications must implement.

Setting Filters

Spring security relies on user request filters. These must be configured in the web.xml file under the contextConfigLocation elements:
<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Security Configuration

A <name>-security.xml file must be created in /WEB-INF with this initial structure:
<beans:beans
  xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    ...
</beans:beans>
<name> must be the name of the servlet as configured in web.xml.

Spring configuration can only be performed with XML documents. However, one can mix Java configuration and Spring XML configuration like this when using MVC:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "my.packages")
@ImportResource("WEB-INF/<name>-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {
    ...
}
The above imports the Spring security configuration.

REM: the tutorial available here recommends configuring the <name>-security.xml file in the contextConfigLocation section of web.xml. However, it does not work when using Java configuration. One must use @ImportResource as described above.

Maven Dependencies

The following maven dependencies are required for Spring security:
<properties>
    ...
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>
...
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring.version}</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>${spring.version}</version>
</dependency>

For a concrete Spring Security example, click here • More Spring related posts here.

Wednesday, 12 September 2012

Spring Sitemesh Integration Example

This post is a follow-up to the quick introduction to Sitemesh concepts. It provides a simple example of Sitemesh integration in a simple Spring application. The code is available on GitHub in the Spring-Sitemesh-Integration directory.

Configuration

We need to add the sitemesh filter configuration in the web.xml file. We apply the filter to all pages:
<filter>
    <filter-name>sitemesh</filter-name>
    <filter-class>
        com.opensymphony.module.sitemesh.filter.PageFilter
    </filter-class>
</filter>

<filter-mapping>
    <filter-name>sitemesh</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
We create a WEB-INF/sitemesh.xml configuration file. We specify the location of the decorators.xml file, together with the page parser and a delivered decorater mapper:
<sitemesh>
    <property name="decorators-file" value="/WEB-INF/decorators.xml"/>
    <excludes file="${decorators-file}"/>
    <page-parsers>
        <parser default="true"
            class="com.opensymphony.module.sitemesh.parser.FastPageParser"/>
        <parser content-type="text/html"
            class="com.opensymphony.module.sitemesh.parser.FastPageParser"/>
    </page-parsers>

    <decorator-mappers>
        <mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">
            <param name="config" value="${decorators-file}"/>
        </mapper>
    </decorator-mappers>
</sitemesh>
We create a WEB-INF/decorators.xml configuration file to specify our decoration JSP page:
<decorators defaultdir="/decorators">
    <decorator name="default" page="MyDecorator.jsp">
        <pattern>/*</pattern>
    </decorator>
</decorators>

Decorator

We define our decorator JSP page, which adds a default header and footer. It also retrieves the decorated document's title, head and body:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<!DOCTYPE html>
<html>
<head>
    <title><decorator:title default="SiteMesh Integration"/></title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <decorator:head/>
</head>
<body>

    <div id="header">
        <h1>Header Added By Sitemesh</h1>
    </div>

    <div id="content">
        <decorator:body/>
    </div>

    <div id="Footer">
        <h2>Some Copyright Added By Sitemesh</h2>
    </div>

</body>
</html>

Pages To Decorate

We define a simple Home.jsp page:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Home Page !!!</title>
    </head>
    <body>
        This is the home page content !!!<br /><br />
        <a href="<c:url value='/AnotherPage'/>">Another Page</a>
    </body>
</html>
...with a link to AnotherPage.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Another Page !!!</title>
    </head>
    <body>
        This is the content of another page !!!
    </body>
</html>

Maven Dependency

We need the following dependency:
 <dependency>
    <groupId>opensymphony</groupId>
    <artifactId>sitemesh</artifactId>
    <version>2.4.2</version>
</dependency>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse: http://localhost:8282/spring-sitemesh-integration/.

The home page will display:

The other page displays:
More Spring related posts here.