mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

  • Sunday, 4 October, 2015

    Java EE 8 MVC: A detailed look at Controllers

    Java EE MVC is a new action based MVC framework planned for Java EE 8 and specified in JSR-371. This is the second post of my Java EE 8 MVC tutorial. The first post covered the basics and shows how to get started with Ozark, the Java EE 8 MVC reference implementation.

    In this post we will have a more detailed look at MVC Controllers.

    MVC Controllers

    A controller is responsible for processing incoming requests. It invokes business logic, updates the model and returns the view that should be rendered. An MVC Controller is a JAX-RS resource method annotated with @Controller. If a class is annotated with @Controller, then all resource methods of this class are regarded as controllers.

    The following example shows a simple Controller that renders a product details page for a given product id:

    public class ProductController {
      private Models models;
      private ProductService productService;
      public String getProductDetailPage(@QueryParam("id") long productId) {
        Product product = this.productService.getProduct(productId);
        models.put("product", product);
        return "/WEB-INF/jsp/productDetailPage.jsp";

    This Controller resolves a product id (passed as id request parameter) to a product using a ProductService. The obtained product is added to the model and a path to a view is returned. The view is then rendered with the information stored in the model.

    Like in JAX-RS, the @Path annotation is used to define the URL path. This Controller is accessible via a URL that looks like this:


    The following example shows a hybrid class with one MVC controller method and one traditional JAX-RS resource method:

    public class HybridController {
      public Response jaxrs() {
        return Response.status(200).build();
      public String mvc() {
        return "/WEB-INF/jsp/hello.jsp";

    Controller methods work very similar to JAX-RS resource methods. However, there are two small differences:

    • A return type of String on Controller methods is interpreted as a view path. With JAX-RS resource methods the returned String is interpreted as text content.
    • The default response media type for Controller methods is text/html. Like in JAX-RS the media type can be changed using the @Produces annotation.

    MVC Controller classes and hybrid classes with MVC Controller methods need to be CDI-managed beans. Like JAX-RS resource classes, MVC controller classes are instantiated per request. For every request, a new Controller class instance is created.

    Like in JAX-RS the supported HTTP verb is defined by annotations. If a controller method should listen for HTTP POST requests, it needs to be annotated with @POST instead of @Get.

    For example:

    public class PostController {
      public String post() {
        return "/WEB-INF/jsp/hello.jsp";

    Controller return types

    Four different return types are supported on MVC controller methods:

    • String - The returned string value is interpreted as view path.
    • void - In this case the view need to be defined using the @View annotation
    • Viewable - An abstraction that includes information about a view, the model and the used view engine.
    • Response - A JAX-RS response. The entity type of the response needs to be String, void or Viewable.

    The following class defines four controller methods using different return types. All methods return the same response:

    public class ReturnTypesController {
      public void returnVoid() {
      public String returnString() {
        return "/WEB-INF/jsp/hello.jsp";
      public Viewable returnViewable() {
        return new Viewable("/WEB-INF/jsp/hello.jsp");
      public Response returnResponse() {
        return Response.status(Response.Status.OK)

    Returning a JAX-RS Response is the most flexible way. This way the JAX-RS Response builder can be used to modify the HTTP status code, response headers and more.

    If void is used as return type, the view needs to be defined using the @View annotation. @View can be applied to methods (like in the previous example) and classes. If a class is annotated with @View, the view is applied to all controller methods in this class. A class level @View annotation can be overridden by a more specific view definition on method level, like shown in the following example:

    public class ViewController {
      public void first() {
        // renders foo.jsp
      public void second() {
        // renders bar.jsp
      public String third() {
        // renders baz.jsp
        return "/WEB-INF/jsp/baz.jsp";


    The @Controller annotation can be used on methods and classes. When used on classes, all methods of the class are considered as controllers. Controller methods invoke business logic and determine the view that should be rendered. Classes with Controller methods are CDI managed beans. For every request, a new class instance will be created. Traditional JAX-RS resource methods can be combined with MVC Controller methods in the same class.

    In the next posts about Java EE 8 MVC we will have a look at parameter binding and validation.

    You can find the example source code on GitHub.

  • Monday, 21 September, 2015

    Resource versioning with Spring MVC

    When serving static resources, it is common practice to append some kind of version information to the resource URL. This allows the browser to cache resources for an unlimited time. Whenever the content of the resource is changed, the version information in the URL is changed too. The updated URL forces the client browser to discard the cached resource and reload the latest resource version from the server.

    With Spring it only takes two simple steps to configure versioned resource URLs. In this post we will see how it works.

    Serving versioned URLs

    First we need to tell Spring that resources should be accessible via a versioned URL. This is done in the resource handler MVC configuration:

    public class MvcApplication extends WebMvcConfigurerAdapter {
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        VersionResourceResolver versionResourceResolver = new VersionResourceResolver()
            .addVersionStrategy(new ContentVersionStrategy(), "/**");
            .setCachePeriod(60 * 60 * 24 * 365) /* one year */

    Here we create a resource handler for JavaScript files located in folder named static inside the classpath. The cache period for these JavaScript files is set to one year. The important part is the VersionResourceResolver which supports resource URLs with version information. A VersionStrategy is used to obtain the actual version for a resource.

    In this example we use a ContentVersionStrategy. This VersionStrategy implementation calculates an MD5 hash from the content of the resource and appends it to the file name.

    For example: Assume we have a JavaScript file test.js inside the classpath:/static/ directory. The MD5 hash for test.js is 69ea0cf3b5941340f06ea65583193168.

    We can now send a request to


    which will resolve to classpath:/static/test.js.

    Note that it is still possible to request the resource without the MD5 hash. So this request works too:


    An alternative VersionStrategy implementation is FixedVersionStrategy. FixedVersionStrategy uses a fixed version string that added as prefix to the resource path.

    For example:


    Generating versioned URLs

    Now we need to make sure the application generates resource URLs that contain the MD5 hash.

    One approach for this is to use a ResourceUrlProvider. With a ResourceUrlProvider a resource URL (e.g. /javascript/test.js) can be converted to a versioned URL (e.g. /javascript/test-69ea0cf3b5941340f06ea65583193168.js). A ResourceUrlProvider bean with the id mvcResourceUrlProvider is automatically declared with the MVC configuration.

    In case you are using Thymeleaf as template engine, you can access the ResourceUrlProvider bean directly from templates using the @bean syntax.

    For example:

    <script type="application/javascript"

    If you are using a template engine which does not give you direct access to Spring beans, you can add the ResourceUrlProvider bean to the model attributes. Using a ControllerAdvice, this might look like this:

    public class ResourceUrlAdvice {
      ResourceUrlProvider resourceUrlProvider;
      public ResourceUrlProvider urls() {
        return this.resourceUrlProvider;

    Inside the view we can then access the ResourceUrlProvider using the urls model attribute:

    <script type="application/javascript" 

    This approach should work with all template engines that support method calls.

    An alternative approach to generate versioned URLs is the use of ResourceUrlEncodingFilter. This is a Servlet Filter that overrides the HttpServletResponse.encodeURL() method to generate versioned resource URLs.

    To make use of the ResourceUrlEncodingFilter we simply have to add an additional bean to our configuration class:

    public class MvcApplication extends WebMvcConfigurerAdapter {
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // same as before ..
      public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
        return new ResourceUrlEncodingFilter();

    If the template engine you are using calls the response encodeURL() method, the version information will be automatically added to the URL. This will work in JSPs, Thymeleaf, FreeMarker and Velocity.

    For example: With Thymeleaf we can use the standard @{..} syntax to create URLs:

    <script type="application/javascript" th:src="@{/javascript/test.js}"></script>

    This will result in:

    <script type="application/javascript" 


    Adding version information to resource URLs is a common practice to maximize browser caching. With Spring we just have to define a VersionResourceResolver and a VersionStrategy to serve versioned URLs. The easiest way to generate versioned URLs inside template engines, is the use of an ResourceUrlEncodingFilter.

    If the standard VersionStrategy implementations do not match your requirements, you can create our own VersionStrategy implementation.

    You can find the full example source code on GitHub.

  • Tuesday, 1 September, 2015

    Java EE 8 MVC: Getting started with Ozark

    About a year ago a new action based MVC framework, simply called MVC, was announced for Java EE 8. MVC (specified in JSR 371) is based on JAX-RS and integrates with Java EE technologies like CDI and Bean Validation. The reference implementation for MVC 1.0 is Ozark.

    This is the first article of a multi-part tutorial I am planning to write about Java EE MVC. In this post we will see how to get a basic Java EE MVC application running with Ozark. Upcoming articles will provide more details to specific sections.

    Getting started with Ozark

    Please note that the MVC specification is still an early draft, the final specification is planned to be released in Q3 2016. To have a look at Java EE MVC in this early state, we need a recent nightly build version of GlassFish and the current Ozark milestone release. The Ozark team recommends GlassFish b13 03-16-2015 for the current Ozark version.

    Besides GlassFish we need the following dependencies to create an MVC application:


    As mentioned above, Java EE MVC is based on JAX-RS. So things might look very familiar to you, if you already know about JAX-RS.

    To create our MVC application we first need a JAX-RS Application class:

    public class GettingStartedApplication extends Application {

    This subclass of can be used to define additional JAX-RS components. In this example we do not need any special configuration, so the class can stay empty. With @ApplicationPath we define the base path for our application.

    Creating the Controller

    A controller is responsible for processing incoming requests. Based on the incoming request it executes business logic, updates the model and returns the view that should be rendered. A simple Java EE MVC Controller looks like this:

    public class HelloController {
      Models models;
      public String sayHello(@QueryParam("name") String name) {
        String message = "Hello " + name;
        models.put("message", message);
        return "/WEB-INF/jsp/hello.jsp";

    The Controller class is annotated with @Controller and @Path. This indicates that the class is a Java EE MVC Controller that listens for requests on /getting-started/hello.

    With CDI an instance of Models is injected to the controller. The Models class represents the MVC model. It is filled with data by the controller and is then passed to the view. Models is basically a Map<String, Object> that can contain arbitrary data.

    The sayHello() method processes incoming HTTP GET requests (indicated by @GET). With @QueryParam request parameters can be bound to method parameters. Inside sayHello() the request parameter name is used to create a text message, which is then added to the Model. The returned String defines the path to the view that should be rendered.

    Creating the View

    Views in Java EE MVC applications are typically HTML pages with CSS and JavaScript files. In this example our view is a simple JSP file located at /WEB-INF/jsp/hello.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Getting started</title>

    Inside JSP files, model properties can be accessed via EL. Here, we use ${message} to access the model value with the key message.

    The Java EE MVC specification defines two standard template engines for views: JSP and Facelets. However, other template engines can easily be integrated. We will have a look at the integration of other view technologies in an upcoming post.

    Running the application

    Now we are ready to start GlassFish and deploy our new MVC application. After that, we can send a GET request to our controller and see what it returns. Do not forget that the controller expects a name parameter.

    For example

    GET /getting-started/hello?name=john

    will result in a HTML page containing the message Hello John


    Java EE MVC is the new upcoming Java MVC web framework. It uses a lot of existing Java technologies like JAX-RS, CDI and JSP. The framework itself is quite simple and easy to understand. The complete MVC 1.0 specification is only around 33 pages long and very easy to read.

    We can use the current milestone release of the MVC 1.0 reference implementation Ozark to get a feeling for the upcoming Java EE 8 framework.

    You can find the full source code of the example application on GitHub.

    In future blog posts we will have a look at parameter validation, exception handling and other view technologies.

  • Thursday, 4 June, 2015

    Exception Translation with ET

    Some time ago I wrote a small blog post about exception translation with AspectJ. In this blog post we will see how to accomplish the same using ET and its lighter Java 8 approach.


    Exception translation (or exception conversion) is the process of converting one type of exception into another. The Java code to translate an exception is quite simple and I think every Java developer writes something like this from time to time:

    try {
      // code that can throw FooException
    } catch(FooException e) {
      // convert FooException to BarException
      throw new BarException(e);

    Exception translation is typically applied if exceptions from third party libraries do not fit into your application. Reasons for this might be:

    • Exceptions thrown by a library are too low level and/or you do not want to leak implementation details into other parts of your application. For example, you want to use a more generic DataAccessException instead of a lower level SQLException.
    • A library is using checked exception while you prefer using only runtime exception in your application.

    Exception Translation with ET

    ET is a small and simple library for exception translation. To get started with ET, you just need to add the following dependency to your code:


    ET makes use of Java 8 features, so do not forget to set your compiler Level to Java 8.

    We start with configuring an ExceptionTranslator instance:

    ExceptionTranslator et = ET.newConfiguration()
        .translate(FooException.class, BarException.class).to(BazException.class)

    Here we create an ExceptionTranslator that converts IOException, FooException and BarException. IOException will be translated to MyRuntimeException while FooException and BarException are translated to BazException.

    Please note that ET requires the translation target exceptions (here MyRuntimeException and BazException) to be RuntimeExceptions.
    ExceptionTranslator instances are thread safe and immutable. It is safe to configure an ExceptionTranslator once and then make it globally available.

    Now we can use our new ExceptionTranslator to wrap the code that can throw exceptions we want to convert.

    et.withTranslation(() -> {
      // can throw IOException, FooException and/or BarException

    If now an IOException is thrown by dangerOperation() et will catch it. et then throws a new MyRuntimeException from the caught IOException. The original IOException is stored in the cause field of MyRuntimeException.

    To return a value from a translation block withReturningTranslation() can be used:

    MyResultClass data = et.withReturningTranslation(() -> {
      return myObject.dangerOperation(); 


    ET is a small library that might be useful to you, if you have to do a lot of exception conversion in your code. After configuring your conversion rules once, exceptions can be converted by simply wrapping the code in a lambda expression.

    Have a look at the full ET documentation on GitHub.

  • Friday, 10 April, 2015

    What's new in Grails 3

    A few days ago Grails 3.0 was officially released. Grails is now based on Spring Boot, the build system changed from Gant to Gradle and significant parts of the framework have been rewritten. In this post we will have a look at all the major changes introduced by Grails 3.

    Updated file structure

    We will start with a screenshot that shows a fresh Grails 3 project created from the Grails command line using

    grails create-app hello

    grails 3 project structure

    The first two folders (build and gradle) are related to Gradle, the new build system in Grails 3. As the name implies, build is the directory where build related files like compiled classes and assembled packages are located. The gradle directory contains the Gradle Wrapper that allows you to build the project without a local Gradle installation.

    The content of the conf folder has also been changed. The default format for configuration files is now YAML. If you prefer to write your configuration in Groovy, you can still create a grails-app/conf/application.groovy configuration file manually.
    Logback is now the default logging provider. The logging configuration (previously part of Config.groovy) has been moved to conf/logback.groovy.
    Note that the conf folder is not a source directory anymore.

    init is a new folder in Grails 3. It contains Bootstrap.groovy (same content as in previous Grails versions) and the new Application main class (we will look into this in the Spring Boot section).

    The structure of the src folder has been changed to match Gradle conventions. Additional Java and Groovy files are now located in:

    build.gradle and contain the build configuration. BuildConfig.groovy from previous Grails versions does no longer exist.

    Spring 4.1 and Spring Boot

    Spring Boot is the new basis for Grails. According to Graeme Rocher Grails 3 is nothing less than a ground up rewrite on top of Spring Boot.

    Like Spring Boot applications Grails 3 projects come with an Application class that has a standard main() method. This means you can start a Grails 3 application simply by running the main class from your IDE.

    The default Application class looks like this:

    class Application extends GrailsAutoConfiguration {
      static void main(String[] args) {

    Note that the war file you get when packaging the application can now be executed using the java -jar command:

    java -jar build/libs/myApplication-0.1.war

    This runs the main method which starts the application using an embedded Tomcat server. Of course you can still deploy the war file on an application server of your choice like in previous Grails versions.

    The Application class acts as Spring configuration class. So, we can use Spring's @Bean annotation to define custom beans. Methods like onStartup() or onShutdown() can be overwritten if you want to execute custom code at certain application events.

    class Application extends GrailsAutoConfiguration {
      MyBean myBeanId() {
        return new MyBeanImpl();
      void onStartup(Map<String, Object> event) {
       // custom startup code..

    Grails 3 uses Traits

    In Grails components like Controllers or Domain classes always had some magically attached functionality. For example, in Controllers you can use methods like render(), redirect() or getParams() without subclassing another class. In Grails 3 these features have been rewritten to make use of Traits introduced by Groovy 2.3.
    Certain Traits are automatically attached to Controllers, Services, Tag libraries and so on to make framework methods available. For example, a Controller automatically gets the following Traits: TagLibraryInvoker, AsyncController, RestResponder, Controller.

    The cool thing with Traits is that you can easily add them to your own classes.
    For example: Assume you want to access the request and params objects outside a Grails Controller. All you have to do now is adding the WebAttributes trait to your class:

    class MyCustomComponent implements WebAttributes {
      public MyCustomComponent() {
        // make use of WebAttributes methods like getWebRequest() or getParams()
        println "base url: " + webRequest.baseUrl
        println "params: " + params


    Grails 3 introduced standalone Interceptors. Interceptors can intercept incoming requests to perform common tasks (e.g. logging, authentication, etc.).

    A new Interceptor can be created using create-interceptor command:
    grails create-interceptor MyInterceptor

    A newly created Interceptor looks like this:

    class MyInterceptor {
      boolean before() { 
        // executed before a request is processed by a controller
      boolean after() {
        // executed after a request is processed by a controller
      void afterView() { 
        // executed after the view has been rendered

    Interceptors replace Filters used by previous Grails versions. Filters still work in Grails 3 for backwards compatibility. However, they are considered deprecated now.

    If you are aware of Spring web MVC, you can easily see the similarities to Springs Handler Interceptor.

    Gradle builds

    As mentioned before, Grails 3 uses Gradle instead of Gant as build system. Gradle is used for tasks like compilation, running tests and packaging the application.
    When a Grails command like grails clean is executed, the job is delegated to the corresponding Gradle task (e.g. gradle clean). The Gradle-Wrapper shipped with Grails 3 is used for this.
    If you want to use a local installation of Gradle you can execute the Gradle task directly with your own Gradle version. Gradle 2.2 or newer is recommended.

    The following table shows Grails commands and their corresponding Gradle tasks:

    Grails command      Gradle Task
    clean clean
    compile classes
    package assemble
    run-app run
    test-app test
    war assemble

    BuildConfig.groovy from previous Grails versions has been completely replaced by the Gradle configuration (build.gradle). Third party dependencies are now defined in build.gradle:

    dependencies {
      compile 'org.grails.plugins:hibernate' 
      compile 'org.grails.plugins:cache' 
      compile 'org.hibernate:hibernate-ehcache'
      runtime 'org.grails.plugins:asset-pipeline' 
      runtime 'org.grails.plugins:scaffolding'

    For more details, you can have a look at Dependency Management Guide in the Gradle documentation.

    Grails profiles

    Whenever you run the create-app command Grails 3 will use a Profile to create a new app.
    A Profile encapsulates project structure, commands, templates and plugins. By default Grails 3 uses the web Profile, which creates an app like shown in the screenshot above.

    To create a project with a different Profile, you can use the --profile parameter:

    grails create-app myapp --profile=web-plugin

    Grails 3 comes with three different Profiles:

    • web for standard Grails web applications
    • web-plugin for web application plugins
    • web-micro a minimal micro service application

    Short summary

    Grails 3 comes with major changes. The code basis changed to Spring Boot, Gant was replaced with Gradle, existing features were reimplemented using Traits and new features like Profiles and Interceptors were added.
    With all those changes it can become quite challenging to upgrade an existing Grails 2.x application to Grails 3 (all Plugins need to be updated first). If you plan to Upgrade to Grails 3, you should have a look at the Grails 3 upgrade guide.