Comprehensive Java web application development framework that enables server-side Java development with modern web UI components and automatic client-server communication.
Vaadin provides comprehensive server communication capabilities including server push, WebSocket support, background tasks, and client-server synchronization. The framework handles most communication automatically but also provides APIs for custom scenarios.
// Server push configuration
import com.vaadin.flow.server.Push;
import com.vaadin.flow.server.PushMode;
import com.vaadin.flow.server.Transport;
import com.vaadin.flow.server.PushConfiguration;
// UI access and operations
import com.vaadin.flow.component.UI;
import com.vaadin.flow.server.Command;
import com.vaadin.flow.shared.Registration;
// Session and service management
import com.vaadin.flow.server.VaadinSession;
import com.vaadin.flow.server.VaadinService;
import com.vaadin.flow.server.VaadinContext;
import com.vaadin.flow.server.WrappedSession;
import com.vaadin.flow.server.WrappedHttpSession;
import com.vaadin.flow.server.DeploymentConfiguration;
// Request and response handling
import com.vaadin.flow.server.VaadinRequest;
import com.vaadin.flow.server.VaadinResponse;
import com.vaadin.flow.server.VaadinServlet;
import com.vaadin.flow.server.VaadinServletConfiguration;
// JavaScript integration
import com.vaadin.flow.component.page.Page;
import com.vaadin.flow.component.page.PendingJavaScriptResult;
import com.vaadin.flow.component.page.History;
import com.vaadin.flow.component.page.Extended;
// Browser information
import com.vaadin.flow.server.WebBrowser;
import com.vaadin.flow.server.BrowserDetails;
// Streaming and resources
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.server.AbstractStreamResource;
import com.vaadin.flow.server.StreamResource.InputStreamFactory;
// Event system
import com.vaadin.flow.component.ComponentEvent;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.DomEvent;
import com.vaadin.flow.component.EventData;
import com.vaadin.flow.dom.Element;
// Error handling
import com.vaadin.flow.server.ErrorHandler;
import com.vaadin.flow.server.ErrorEvent;
import com.vaadin.flow.server.DefaultErrorHandler;
// Session listeners
import com.vaadin.flow.server.SessionInitListener;
import com.vaadin.flow.server.SessionDestroyListener;
// Communication error configuration
import com.vaadin.flow.component.ReconnectDialogConfiguration;
import com.vaadin.flow.component.SessionExpiredDialogConfiguration;
// JSON handling
import elemental.json.JsonValue;
// Core components
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.notification.Notification;
// Functional interfaces
import com.vaadin.flow.function.SerializableConsumer;
import com.vaadin.flow.function.SerializableSupplier;
import com.vaadin.flow.function.SerializableFunction;
// Standard Java types
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Supplier;
// Servlet API
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;Enable server-initiated updates to the client browser.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Push {
PushMode value() default PushMode.AUTOMATIC;
Transport transport() default Transport.WEBSOCKET;
}
public enum PushMode {
DISABLED, // No server push
MANUAL, // Manual push triggering
AUTOMATIC // Automatic push on UI changes
}
public enum Transport {
WEBSOCKET, // WebSocket transport (preferred)
LONG_POLLING, // HTTP long polling fallback
WEBSOCKET_XHR // WebSocket with XHR fallback
}Methods for accessing UI from background threads and triggering push updates.
public class UI extends Component {
// Thread-safe UI access
public void access(Command command);
public void accessSynchronously(Command command);
// Manual push control
public void push();
public void pushConfiguration(PushConfiguration pushConfiguration);
// Current UI access
public static UI getCurrent();
public static Optional<UI> getCurrentOptional();
// Session and service access
public VaadinSession getSession();
public VaadinService getService();
// Polling configuration
public Registration setPollInterval(int intervalInMillis);
public int getPollInterval();
// Browser information
public WebBrowser getWebBrowser();
public Page getPage();
}Functional interface for UI access operations.
@FunctionalInterface
public interface Command extends Serializable {
void execute();
}Utilities for executing background tasks with UI updates.
// Execute task in background thread with UI updates
public class BackgroundTaskService {
public void executeWithProgress(Runnable task, Consumer<String> progressCallback) {
CompletableFuture.runAsync(() -> {
try {
task.run();
UI.getCurrent().access(() -> {
progressCallback.accept("Task completed");
});
} catch (Exception e) {
UI.getCurrent().access(() -> {
progressCallback.accept("Task failed: " + e.getMessage());
});
}
});
}
public <T> CompletableFuture<T> executeAsync(Supplier<T> task) {
UI ui = UI.getCurrent();
return CompletableFuture.supplyAsync(task)
.whenComplete((result, throwable) -> {
ui.access(() -> {
if (throwable != null) {
Notification.show("Error: " + throwable.getMessage());
} else {
Notification.show("Task completed successfully");
}
});
});
}
}Session-level state and configuration management.
public class VaadinSession implements WrappedSession {
// Current session access
public static VaadinSession getCurrent();
// Session state
public void lock();
public void unlock();
public boolean hasLock();
// Attribute management
public void setAttribute(String name, Object value);
public Object getAttribute(String name);
public <T> T getAttribute(String name, Class<T> type);
public void removeAttribute(String name);
public Set<String> getAttributeNames();
// Session lifecycle
public void close();
public boolean isClosed();
// Service access
public VaadinService getService();
public BrowserDetails getBrowser();
// Configuration
public void setConfiguration(DeploymentConfiguration configuration);
public DeploymentConfiguration getConfiguration();
// Error handling
public void setErrorHandler(ErrorHandler errorHandler);
public ErrorHandler getErrorHandler();
// Push configuration
public PushConfiguration getPushConfiguration();
public void setPushConfiguration(PushConfiguration pushConfiguration);
}Service-level configuration and utilities.
public abstract class VaadinService {
// Current service access
public static VaadinService getCurrent();
// Service lifecycle
public void init();
public void destroy();
// Session management
public void storeSession(VaadinSession session, WrappedHttpSession wrappedSession);
public void removeSession(WrappedHttpSession wrappedSession);
// Request handling
public abstract void handleRequest(VaadinRequest request, VaadinResponse response);
// Configuration
public DeploymentConfiguration getDeploymentConfiguration();
public ClassLoader getClassLoader();
// Context
public VaadinContext getContext();
// Statistics
public SessionInitListener getSessionInitListener();
public SessionDestroyListener getSessionDestroyListener();
}HTTP request wrapper with Vaadin-specific functionality.
public interface VaadinRequest extends Serializable {
// Request parameters
String getParameter(String parameter);
Map<String, String[]> getParameterMap();
int getContentLength();
InputStream getInputStream();
// Headers
String getHeader(String headerName);
Enumeration<String> getHeaderNames();
long getDateHeader(String name);
int getIntHeader(String name);
// Request information
String getMethod();
String getRequestURI();
String getContextPath();
String getPathInfo();
String getRemoteAddr();
String getRemoteHost();
int getRemotePort();
boolean isSecure();
// Authentication
String getRemoteUser();
boolean isUserInRole(String role);
Principal getUserPrincipal();
// Wrapped request access
<T> T getWrappedSession(Class<T> wrappedSessionType);
Object getAttribute(String name);
void setAttribute(String name, Object value);
void removeAttribute(String name);
Enumeration<String> getAttributeNames();
// Service access
VaadinService getService();
}HTTP response wrapper with Vaadin-specific functionality.
public interface VaadinResponse extends Serializable {
// Response writing
OutputStream getOutputStream();
PrintWriter getWriter();
// Headers
void setHeader(String name, String value);
void addHeader(String name, String value);
void setDateHeader(String name, long date);
void addDateHeader(String name, long date);
void setIntHeader(String name, int value);
void addIntHeader(String name, int value);
// Status
void setStatus(int statusCode);
void sendError(int errorCode, String message);
void sendRedirect(String url);
// Content
void setContentType(String type);
String getContentType();
void setContentLength(int len);
// Caching
void setCacheTime(long milliseconds);
// Service access
VaadinService getService();
}Execute JavaScript code from server-side Java.
public class Page {
// JavaScript execution
public PendingJavaScriptResult executeJs(String expression, Object... parameters);
public PendingJavaScriptResult executeJs(String expression, Serializable... parameters);
// Browser navigation
public void setLocation(String location);
public void setLocation(URI location);
public void open(String url);
public void open(String url, String windowName);
public void open(String url, String windowName, String windowFeatures);
// Page reload
public void reload();
// History management
public History getHistory();
public Extended getExtended();
}
public interface PendingJavaScriptResult extends Serializable {
void then(SerializableConsumer<JsonValue> resultHandler);
void then(SerializableConsumer<JsonValue> resultHandler, SerializableConsumer<String> errorHandler);
boolean isCanceled();
void cancel();
}Access browser capabilities and information.
public class WebBrowser {
// Browser identification
public String getBrowserApplication();
public int getBrowserMajorVersion();
public int getBrowserMinorVersion();
public boolean isChrome();
public boolean isFirefox();
public boolean isSafari();
public boolean isEdge();
// Capabilities
public boolean isTouchDevice();
public boolean isWebKit();
public boolean isIE();
// Screen information
public int getScreenWidth();
public int getScreenHeight();
public int getTimezoneOffset();
public String getTimeZoneId();
// User agent
public String getUserAgent();
public String getAddress();
// Locale
public Locale getLocale();
public void updateRequestDetails(VaadinRequest request);
}Resource for streaming content to the browser.
public class StreamResource implements AbstractStreamResource {
public StreamResource(String fileName, InputStreamFactory streamFactory);
// Content configuration
public void setContentType(String contentType);
public String getContentType();
public void setCacheTime(long cacheTime);
public long getCacheTime();
public void setHeader(String name, String value);
// Stream factory
@FunctionalInterface
public interface InputStreamFactory extends Serializable {
InputStream createInputStream();
}
}
// Usage for file downloads
public StreamResource createDownload(String fileName, String content) {
return new StreamResource(fileName, () ->
new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
}Framework for custom component events and server communication.
public abstract class ComponentEvent<T extends Component> extends EventObject {
public ComponentEvent(T source, boolean fromClient);
public T getSource();
public boolean isFromClient();
public Optional<Element> getUnloadingElement();
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DomEvent {
String value();
String filter() default "";
boolean allowUpdates() default true;
}
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventData {
String value();
}Global and component-level error handling for communication failures.
public interface ErrorHandler extends Serializable {
void error(ErrorEvent event);
}
public class ErrorEvent extends EventObject {
public ErrorEvent(Throwable throwable);
public Throwable getThrowable();
}
public class DefaultErrorHandler implements ErrorHandler {
public void error(ErrorEvent event);
public static void doDefault(ErrorEvent event);
public static Logger getLogger();
}Events for handling communication failures.
// Reconnection handling
public class ReconnectDialogConfiguration {
public void setDialogText(String dialogText);
public String getDialogText();
public void setDialogTextGaveUp(String dialogTextGaveUp);
public String getDialogTextGaveUp();
public void setReconnectAttempts(int reconnectAttempts);
public int getReconnectAttempts();
public void setReconnectInterval(int reconnectInterval);
public int getReconnectInterval();
}
// Session expiration handling
public class SessionExpiredDialogConfiguration {
public void setDialogText(String dialogText);
public String getDialogText();
}@Push
@Route("live-data")
public class LiveDataView extends VerticalLayout {
private Label statusLabel = new Label();
private ProgressBar progressBar = new ProgressBar();
public LiveDataView() {
add(new H1("Live Data Updates"), statusLabel, progressBar);
// Start background task with push updates
startBackgroundTask();
}
private void startBackgroundTask() {
CompletableFuture.runAsync(() -> {
for (int i = 0; i <= 100; i++) {
final int progress = i;
// Update UI from background thread
getUI().ifPresent(ui -> ui.access(() -> {
progressBar.setValue(progress / 100.0);
statusLabel.setText("Processing: " + progress + "%");
}));
try {
Thread.sleep(100); // Simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
// Final update
getUI().ifPresent(ui -> ui.access(() -> {
statusLabel.setText("Task completed!");
Notification.show("Background task finished");
}));
});
}
}public class FileDownloadExample extends VerticalLayout {
public FileDownloadExample() {
Button downloadButton = new Button("Download Report");
downloadButton.addClickListener(e -> downloadReport());
add(downloadButton);
}
private void downloadReport() {
StreamResource resource = new StreamResource("report.pdf", () -> {
// Generate report data
return generateReportPDF();
});
resource.setContentType("application/pdf");
resource.setHeader("Content-Disposition", "attachment; filename=\"report.pdf\"");
// Trigger download
getUI().ifPresent(ui -> ui.getPage().open(resource));
}
private InputStream generateReportPDF() {
// Generate PDF content
return new ByteArrayInputStream("PDF content".getBytes());
}
}public class JavaScriptInteractionView extends VerticalLayout {
public JavaScriptInteractionView() {
Button callJSButton = new Button("Call JavaScript");
callJSButton.addClickListener(e -> callJavaScript());
add(callJSButton);
}
private void callJavaScript() {
// Execute JavaScript and handle result
getUI().ifPresent(ui -> {
ui.getPage().executeJs("return navigator.userAgent")
.then(jsonValue -> {
String userAgent = jsonValue.asString();
Notification.show("User Agent: " + userAgent);
});
});
// Execute JavaScript with parameters
getUI().ifPresent(ui -> {
ui.getPage().executeJs("alert($0)", "Hello from server!")
.then(result -> {
Notification.show("JavaScript executed");
});
});
}
}public class SessionManagementExample extends VerticalLayout {
public SessionManagementExample() {
Button storeDataButton = new Button("Store Session Data");
storeDataButton.addClickListener(e -> storeSessionData());
Button retrieveDataButton = new Button("Retrieve Session Data");
retrieveDataButton.addClickListener(e -> retrieveSessionData());
add(storeDataButton, retrieveDataButton);
}
private void storeSessionData() {
VaadinSession session = VaadinSession.getCurrent();
session.setAttribute("user-data", "Important user information");
Notification.show("Data stored in session");
}
private void retrieveSessionData() {
VaadinSession session = VaadinSession.getCurrent();
String data = (String) session.getAttribute("user-data");
if (data != null) {
Notification.show("Retrieved: " + data);
} else {
Notification.show("No data found in session");
}
}
}The server communication APIs provide comprehensive control over client-server interactions while maintaining the automatic synchronization that makes Vaadin development productive.
Install with Tessl CLI
npx tessl i tessl/maven-com-vaadin--vaadin