Creating an Embedded Vaadin Application Tutorial

In this section, we demonstrate how to create a basic embedded application: that is, an application that can be embedded in another page.

Note
The technology you use to create the host page is irrelevant: you can use Vaadin or non-Vaadin server-side Java technologies, like JSP, Thymeleaf, or servlet, or even a basic static HTML page.

In order to be able to embed a Vaadin application, you need to create:

  • An entry point. This is achieved by creating a WebComponentExporter for the Vaadin Component you want to embed, and

  • A VaadinServlet to handle requests to your web component. The servlet can be declared in a non-Vaadin application, or deployed separately as a standalone WAR file.

Our scenario uses:

  • A single custom servlet to handle the main application logic.

    • The servlet displays primarily static content.

    • The content differs depending on whether a user is logged in or not.

  • An embeddable Vaadin Component to implement a login form.

Note
VaadinServlet forms part of the application, but its mapping differs from the main servlet mapping.

You can start with a clean project, or start building on top of the Vaadin Base Starter (download the “Plain Java Servlet” version).

  1. Create the MainAppServlet servlet class.

    This servlet serves the static page which embeds our login form as a web component.

    Java

    1. @WebServlet(urlPatterns = {"/example"})
    2. public class MainAppServlet extends HttpServlet {
    3. @Override
    4. protected void doGet(HttpServletRequest req, HttpServletResponse response)
    5. throws ServletException, IOException {
    6. response.setContentType("text/html;charset=UTF-8");
    7. Object authToken = req.getSession().getAttribute("auth_token");
    8. boolean isAuthenticated = authToken != null;
    9. try (PrintWriter out = response.getWriter()) {
    10. out.println("<!DOCTYPE html>");
    11. out.println("<html><head>");
    12. out.println("<meta http-equiv='Content-Type' content='text/html; "
    13. + "charset=UTF-8'>");
    14. if (!isAuthenticated) {
    15. out.println("<script type='text/javascript' "
    16. + "src='/vaadin/VAADIN/build/webcomponentsjs/"
    17. + "webcomponents-loader.js'></script>");
    18. out.println("<script type='module' src='/vaadin/web-component"
    19. + "/login-form.js'></script>");
    20. out.println("<script type='text/javascript' "
    21. + "src='/log-in.js' defer></script>");
    22. }
    23. out.println("</head><body>");
    24. if (isAuthenticated) {
    25. out.println("<h1>Welcome "
    26. + UserService.getInstance().getName(authToken)
    27. + "</h1>");
    28. } else {
    29. out.println("<login-form userlbl='Username' pwdlbl='Password'>"
    30. + "</login-form>");
    31. }
    32. out.println("</body>");
    33. out.println("</html>");
    34. }
    35. }
    36. }

    Let’s analyze the HTML content generated by MainAppServlet:

    • This line loads the web component polyfill:

      HTML

      1. <script type='text/javascript'
      2. src='/vaadin/VAADIN/build/webcomponentsjs/webcomponents-loader.js'>
      3. </script>
    • This line loads the web component:

      HTML

      1. <script type='module'
      2. src='/vaadin/web-component/login-form.js'>
      3. </script>
      • Both script src attributes start with /vaadin/. This is the URI to use to map to the Vaadin servlet (see step 3 below).

      • The second part the link URI,/web-component/login-form.js, is the standard URI to use to import the web component. It consists of the hard-coded web-component part, followed by login-form.js, which is the web component file. The web component file is generated by Vaadin, based on the configuration set in the exporter.

    • The name of the web component in our example must be "login-form". This name must be used in both the super constructor of the exporter (see LoginFormExporter in step 5 below) and the HTML code where the web component is inserted. In our example this is right under the <body> tag:

      HTML

      1. <login-form userlbl='Username' pwdlbl='Password'>
      2. </login-form>
      • The "login-form" web component has two properties, userlbl and pwdlbl. These values are passed from the HTML to a web component instance.

        Note
        If embedding applications is targeted towards very specific browsers, the polyfill is not needed. For example Chrome and Firefox do not need the polyfill while Edge does.
  1. Create the UserService class. This class contains the authentication logic and is shared between the MainAppServlet and the web component class (created in step 5 below). You can use any interface and implementation you like. This example is a custom stub implementation and is provided as a reference.

    Java

    1. public final class UserService {
    2. private static final UserService INSTANCE =
    3. new UserService();
    4. private UserService(){
    5. }
    6. public static UserService getInstance() {
    7. return INSTANCE;
    8. }
    9. public String getName(Object authToken) {
    10. return "Joe";
    11. }
    12. public Optional<Object> authenticate(String user,
    13. String passwd) {
    14. if ("admin".equals(user) &&
    15. "admin".equals(passwd)) {
    16. return Optional.of(new Object());
    17. } else {
    18. return Optional.empty();
    19. }
    20. }
    21. }
  2. Register the VaadinServlet.

    Java

    1. @WebServlet(urlPatterns = { "/vaadin/*" })
    2. public class WebComponentVaadinServlet extends VaadinServlet {
    3. }
    • As mentioned above, the /vaadin/* mapping allows the VaadinServlet to handle web component requests. You can use any URI, but be sure to use the same URI in the mapping and in the import declaration.

    • If you are operating in compatibility mode, see Embedding Applications in Compatibility and Production Mode for more information about implementing the VaadinServlet.

      Note
      If you deploy your web component exporter(s) as a standalone WAR application, an explicit servlet registration is unnecessary. A servlet instance is registered automatically with the “/*” mapping.
  3. Create the LoginForm component class.

    Java

    1. public class LoginForm extends Div {
    2. private TextField userName = new TextField();
    3. private PasswordField password =
    4. new PasswordField();
    5. private Div errorMsg = new Div();
    6. private String userLabel;
    7. private String pwdLabel;
    8. private FormLayout layout = new FormLayout();
    9. private List<SerializableRunnable> loginListeners =
    10. new CopyOnWriteArrayList<>();
    11. public LoginForm() {
    12. updateForm();
    13. add(layout);
    14. Button login = new Button("Login",
    15. event -> login());
    16. add(login, errorMsg);
    17. }
    18. public void setUserNameLabel(
    19. String userNameLabelString) {
    20. userLabel = userNameLabelString;
    21. updateForm();
    22. }
    23. public void setPasswordLabel(String pwd) {
    24. pwdLabel = pwd;
    25. updateForm();
    26. }
    27. public void updateForm() {
    28. layout.removeAll();
    29. layout.addFormItem(userName, userLabel);
    30. layout.addFormItem(password, pwdLabel);
    31. }
    32. public void addLoginListener(
    33. SerializableRunnable loginListener) {
    34. loginListeners.add(loginListener);
    35. }
    36. private void login() {
    37. Optional<Object> authToken = UserService
    38. .getInstance()
    39. .authenticate(userName.getValue(),
    40. password.getValue());
    41. if (authToken.isPresent()) {
    42. VaadinRequest.getCurrent()
    43. .getWrappedSession()
    44. .setAttribute("auth_token",
    45. authToken.get());
    46. fireLoginEvent();
    47. } else {
    48. errorMsg.setText("Authentication failure");
    49. }
    50. }
    51. private void fireLoginEvent() {
    52. loginListeners.forEach(
    53. SerializableRunnable::run);
    54. }
    55. }
    • The example uses several Vaadin components: FormLayout, TextField, PasswordField and Button.

    • The code takes care of authentication and sets an authentication token in the HttpSession, which makes it available while the session is live.

    • Because the main application servlet uses the same HttpSession instance, it changes behavior and redirects authenticated users to the main servlet that now shows content specific to authenticated users. There are various ways to do this:

      • Execute JavaScript directly from your Java code and set the location to "/example" : getUI().get().getPage().executeJs("window.location.href='/example'");.

      • Use a solution similar to this example: design the component code so that its logic is isolated and it does not need to know anything about the embedding context. This method allows you to completely decouple the embedded component logic from the application that uses it. In this example, the addLoginListener method allows you to register a listener which is called in the fireLoginEvent method.

  1. The final step is to export the LoginForm component as an embeddable web component using the web component exporter.

    Java

    1. public class LoginFormExporter
    2. extends WebComponentExporter<LoginForm> {
    3. public LoginFormExporter() {
    4. super("login-form");
    5. addProperty("userlbl", "")
    6. .onChange(LoginForm::setUserNameLabel);
    7. addProperty("pwdlbl", "")
    8. .onChange(LoginForm::setPasswordLabel);
    9. }
    10. @Override
    11. protected void configureInstance(
    12. WebComponent<LoginForm> webComponent,
    13. LoginForm form) {
    14. form.addLoginListener(() ->
    15. webComponent.fireEvent("logged-in"));
    16. }
    17. }
    • The exporter defines its tag name as "login-form" by calling the super constructor super("login-form");.

    • The addProperty method defines the component properties (userlbl='Username' and `pwdlbl='Password') to receive values from the HTML element to the web component instance. In this example we declare the labels for user name field and password field via HTML, instead of hard-coding them in the LoginForm component class.

    • LoginFormExporter class implements the abstract method, configureInstance, which registers a login listener.

    • The login listener fires a client-side "logged-in" event, using the webcomponent.fireEvent() method. The main application needs to handle this event somehow.

    • The custom event is handled by the JavaScript file declared via the line <script type='text/javascript' src='log-in.js'></script> in MainAppServlet. This is the log-in.js file content:

      • Place the log-in.js under ./src/main/webapp/

        HTML

        1. var editor = document.querySelector("login-form");
        2. editor.addEventListener("logged-in", function(event) {
        3. window.location.href='/example';
        4. });
    • The embedding servlet uses the API provided by LoginForm via a custom event and adds an event listener for the event. The listener simply redirects the page to the "/example" location.

  2. Run the application with mvn jetty:run. Once jetty has started, navigate to http://localhost:8080/example.

    • Type in login information and click on “Login” button

      • Username: admin

      • Password: admin