Skip to content

Software Development at Program Tom LTD

Place for coding, programming, development and software in general.

Menu
  • Blog
  • PDF Booklets
  • Dev Utils & Content
  • Java Spring Boot Or Web Apps
  • English
    • български
    • English
    • Español
    • Português
    • हिन्दी
    • Русский
    • Deutsch
    • Français
    • Italiano
    • العربية
  • About Us
Menu
How to integrate Velocity Views in Vaadin Web App

How to integrate Velocity Views in Vaadin Web App

Posted on November 13, 2024 by Toma Velev

To integrate Velocity templates into a Vaadin Web application, you’ll need to follow these steps to combine the two frameworks. This can be particularly useful if you want to use Velocity for templating certain parts of the application, like emails, custom HTML content, or other non-Vaadin UI areas.

Steps to Integrate Velocity with Vaadin

  1. Add Velocity Dependencies
    Ensure you have the Velocity dependency in your project. If you’re using Maven, add the following to your pom.xml:

    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.3</version>
    </dependency>
    
  2. Configure the Velocity Engine
    Set up a VelocityEngine bean or an instance in your Vaadin application. Configure it to locate templates and initialize properties.

    import org.apache.velocity.app.VelocityEngine;
    import java.util.Properties;
    
    public class VelocityConfig {
        public static VelocityEngine createVelocityEngine() {
            Properties properties = new Properties();
            properties.setProperty("resource.loader", "class");
            properties.setProperty("class.resource.loader.class", 
    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    
            VelocityEngine velocityEngine = new VelocityEngine(properties);
            velocityEngine.init();
            return velocityEngine;
        }
    }
    

    Here, the ClasspathResourceLoader allows you to store Velocity templates in the resources folder of your project. Adjust these settings if you need templates from a different location.

  3. Create Velocity Templates
    Add .vm files (Velocity templates) under src/main/resources/templates (or another directory if you configured it differently). For instance, you could create welcome.vm:

    <div>
        <h1>Welcome, $name!</h1>
        <p>Thank you for joining us at $appName.</p>
    </div>

    Note: In this file you need to have only one root element and it must not be <html>. Use anything else – Paragraph, Div, whatever.

  4. Rendering Velocity Templates in Vaadin
    To render Velocity templates, you need to populate a VelocityContext with data and then merge it with the template. Here’s an example of how to render a template and display the result in a Vaadin Html:

    import com.vaadin.flow.component.orderedlayout.VerticalLayout;
    import com.vaadin.flow.router.Route;
    import org.apache.velocity.VelocityContext;
    import org.apache.velocity.app.VelocityEngine;
    import java.io.StringWriter;
    import com.vaadin.flow.component.Html;
    
    @Route("welcome")
    public class WelcomeView extends VerticalLayout {
    
        public WelcomeView() {
            VelocityEngine velocityEngine = VelocityConfig.createVelocityEngine();
            VelocityContext context = new VelocityContext();
            context.put("name", "Toma");
            context.put("appName", "Program Tom . com / Dev");
    
            StringWriter writer = new StringWriter();
            velocityEngine.mergeTemplate("templates/welcome.vm", "UTF-8", context, writer);
    
            Htmllabel = new Html(writer.toString());
            add(label);
        }
    }
    

    This example uses a VelocityContext to pass data (like name and appName) to the welcome.vm template, merges the context into the template, and displays the rendered HTML in a Vaadin Label.

  5. Considerations
    • CSS and Styling: Since Velocity renders HTML content, you might want to style it within the .vm files, or use Vaadin components and style those if integration with Vaadin’s theming is required.
    • Error Handling: Handle template errors gracefully, especially if templates are missing or not correctly rendered.
    • Caching: Use caching mechanisms for templates if they are frequently used and don’t change often to improve performance.

By combining Velocity with Vaadin in this way, you can leverage Velocity’s templating capabilities while maintaining the interactive functionality of Vaadin for other parts of your web app.

Could it be used in a Servlet along side the Vaadin App?

Yes, you can use Velocity in a servlet alongside a Vaadin app. This approach is especially useful if you want to generate static or semi-static HTML content, like reports or dynamically generated emails, without involving Vaadin’s component-based UI structure. Here’s how you can set up a Velocity servlet within a Vaadin application:

Create a Servlet or a Spring Boot Controller
Define a servlet to render Velocity templates. The servlet will use a VelocityContext to populate data and then merge it with the specified template.


import jakarta.annotation.PostConstruct;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.io.StringWriter;

@Controller
@WebServlet(urlPatterns = "/velocity/*")
public class VelocityServlet extends HttpServlet {

    private VelocityEngine velocityEngine;

    @Override
    public void init() throws ServletException {
        super.init();
        velocityEngine = VelocityConfig.createVelocityEngine();
    }

    @PostConstruct
    public void initStuff() {
        velocityEngine = VelocityConfig.createVelocityEngine();
    }

    @GetMapping("/velocity/*")
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
        // Create context with data
        VelocityContext context = new VelocityContext();
        context.put("name", "Toma");
        context.put("appName", "Program Tom . Com / LTD");

        // Merge template
        StringWriter writer = new StringWriter();
        velocityEngine.mergeTemplate("templates/welcome.vm", "UTF-8", context, writer);

        // Set response type and write output
        resp.setContentType("text/html");
        resp.getWriter().write(writer.toString());
    }
}

In this example:

  • The servlet is mapped to /velocity/*, allowing you to access it by visiting http://localhost:8080/velocity/.
  • VelocityContext is used to pass dynamic data to the template.
  • The merged output is written directly to the servlet response as HTML content.
  1. Deploying the Servlet Alongside the Vaadin App
    In a Vaadin application with a servlet-based backend, Vaadin’s primary servlet (e.g., VaadinServlet) handles the UI while your custom servlet (like VelocityServlet) can handle Velocity template rendering. Both can coexist in the same application, but make sure they are mapped to different URL patterns to avoid conflicts.
  2. Accessing from the Vaadin App
    If you need to link to the servlet or fetch the generated content within the Vaadin application, you can аdd hyperlinks pointing to the /velocity/* URL.
  1. Use Cases
    This setup is useful for:
    • Generating static HTML reports or PDFs.
    • Creating dynamic email templates or notifications.
    • Serving simple HTML content outside of Vaadin’s component model, like terms of service or non-interactive informational pages.

By combining Velocity in a servlet with a Vaadin app, you gain flexibility to generate HTML content both within and outside of the Vaadin UI framework.

  • Jenkins SCP File Upload to Remote Server
  • Essential Programming Books – Principles & Flutter
  • Social Media Platforms 🌍
  • Strategies to prevent review regressions
  • How to set Google Map Theme in a Flutter App

Categories

  • Apps (22)
  • ChatGPT (23)
  • Choosing a Framework (38)
  • Flutter (269)
  • Graphical User Interface (14)
  • Marketing (117)
  • Software Development (286)
  • Spring (45)
  • StartUp (22)
  • Uncategorized (14)
  • Uncategorized (4)
  • Vaadin (15)

Tags

Algorithms (9) crypto (29) flutterdev (39) General (86) Java (7) QR & Bar Codes (3) Software Dev Choices (33) Spring Boot (1) standards (1) Theme (3) User Authentication & Authorization (9) User Experience (10) Utilities (19) WordPress (11)

Product categories

  • All Technologies (84)
    • Flutter Apps (24)
    • GPT (4)
    • Java (38)
    • Native Android (3)
    • PHP (9)
    • Spring (Boot) / Quarkus (35)
    • Utils (15)
    • Vaadin 24+ (27)
    • Vaadin 8 (1)
  • Apps (18)
    • Employees DB (1)
    • Notes (6)
    • Personal Budget (1)
    • Recipes Book (1)
    • Stuff Organizer (1)
    • To-Do (2)
  • PDF Books (3)
  • Source Code Generators (8)

Recent Posts

  • Jenkins SCP File Upload to Remote Server
  • Essential Programming Books – Principles & Flutter
  • Social Media Platforms 🌍
  • Strategies to prevent review regressions
  • How to set Google Map Theme in a Flutter App

Post Categories

  • Apps (22)
  • ChatGPT (23)
  • Choosing a Framework (38)
  • Flutter (269)
  • Graphical User Interface (14)
  • Marketing (117)
  • Software Development (286)
  • Spring (45)
  • StartUp (22)
  • Uncategorized (14)
  • Uncategorized (4)
  • Vaadin (15)