0
# Server Communication
1
2
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.
3
4
## Core Imports
5
6
```java
7
// Server push configuration
8
import com.vaadin.flow.server.Push;
9
import com.vaadin.flow.server.PushMode;
10
import com.vaadin.flow.server.Transport;
11
import com.vaadin.flow.server.PushConfiguration;
12
13
// UI access and operations
14
import com.vaadin.flow.component.UI;
15
import com.vaadin.flow.server.Command;
16
import com.vaadin.flow.shared.Registration;
17
18
// Session and service management
19
import com.vaadin.flow.server.VaadinSession;
20
import com.vaadin.flow.server.VaadinService;
21
import com.vaadin.flow.server.VaadinContext;
22
import com.vaadin.flow.server.WrappedSession;
23
import com.vaadin.flow.server.WrappedHttpSession;
24
import com.vaadin.flow.server.DeploymentConfiguration;
25
26
// Request and response handling
27
import com.vaadin.flow.server.VaadinRequest;
28
import com.vaadin.flow.server.VaadinResponse;
29
import com.vaadin.flow.server.VaadinServlet;
30
import com.vaadin.flow.server.VaadinServletConfiguration;
31
32
// JavaScript integration
33
import com.vaadin.flow.component.page.Page;
34
import com.vaadin.flow.component.page.PendingJavaScriptResult;
35
import com.vaadin.flow.component.page.History;
36
import com.vaadin.flow.component.page.Extended;
37
38
// Browser information
39
import com.vaadin.flow.server.WebBrowser;
40
import com.vaadin.flow.server.BrowserDetails;
41
42
// Streaming and resources
43
import com.vaadin.flow.server.StreamResource;
44
import com.vaadin.flow.server.AbstractStreamResource;
45
import com.vaadin.flow.server.StreamResource.InputStreamFactory;
46
47
// Event system
48
import com.vaadin.flow.component.ComponentEvent;
49
import com.vaadin.flow.component.ComponentEventListener;
50
import com.vaadin.flow.component.DomEvent;
51
import com.vaadin.flow.component.EventData;
52
import com.vaadin.flow.dom.Element;
53
54
// Error handling
55
import com.vaadin.flow.server.ErrorHandler;
56
import com.vaadin.flow.server.ErrorEvent;
57
import com.vaadin.flow.server.DefaultErrorHandler;
58
59
// Session listeners
60
import com.vaadin.flow.server.SessionInitListener;
61
import com.vaadin.flow.server.SessionDestroyListener;
62
63
// Communication error configuration
64
import com.vaadin.flow.component.ReconnectDialogConfiguration;
65
import com.vaadin.flow.component.SessionExpiredDialogConfiguration;
66
67
// JSON handling
68
import elemental.json.JsonValue;
69
70
// Core components
71
import com.vaadin.flow.component.Component;
72
import com.vaadin.flow.component.notification.Notification;
73
74
// Functional interfaces
75
import com.vaadin.flow.function.SerializableConsumer;
76
import com.vaadin.flow.function.SerializableSupplier;
77
import com.vaadin.flow.function.SerializableFunction;
78
79
// Standard Java types
80
import java.io.InputStream;
81
import java.io.OutputStream;
82
import java.io.PrintWriter;
83
import java.io.ByteArrayInputStream;
84
import java.io.Serializable;
85
import java.net.URI;
86
import java.nio.charset.StandardCharsets;
87
import java.security.Principal;
88
import java.util.Enumeration;
89
import java.util.Locale;
90
import java.util.Map;
91
import java.util.Optional;
92
import java.util.Set;
93
import java.util.UUID;
94
import java.util.concurrent.CompletableFuture;
95
import java.util.function.Consumer;
96
import java.util.function.Supplier;
97
98
// Servlet API
99
import javax.servlet.ServletException;
100
import javax.servlet.annotation.WebServlet;
101
```
102
103
## Server Push
104
105
### @Push Annotation
106
107
Enable server-initiated updates to the client browser.
108
109
```java { .api }
110
@Target(ElementType.TYPE)
111
@Retention(RetentionPolicy.RUNTIME)
112
public @interface Push {
113
PushMode value() default PushMode.AUTOMATIC;
114
Transport transport() default Transport.WEBSOCKET;
115
}
116
117
public enum PushMode {
118
DISABLED, // No server push
119
MANUAL, // Manual push triggering
120
AUTOMATIC // Automatic push on UI changes
121
}
122
123
public enum Transport {
124
WEBSOCKET, // WebSocket transport (preferred)
125
LONG_POLLING, // HTTP long polling fallback
126
WEBSOCKET_XHR // WebSocket with XHR fallback
127
}
128
```
129
130
### UI Access and Push
131
132
Methods for accessing UI from background threads and triggering push updates.
133
134
```java { .api }
135
public class UI extends Component {
136
// Thread-safe UI access
137
public void access(Command command);
138
public void accessSynchronously(Command command);
139
140
// Manual push control
141
public void push();
142
public void pushConfiguration(PushConfiguration pushConfiguration);
143
144
// Current UI access
145
public static UI getCurrent();
146
public static Optional<UI> getCurrentOptional();
147
148
// Session and service access
149
public VaadinSession getSession();
150
public VaadinService getService();
151
152
// Polling configuration
153
public Registration setPollInterval(int intervalInMillis);
154
public int getPollInterval();
155
156
// Browser information
157
public WebBrowser getWebBrowser();
158
public Page getPage();
159
}
160
```
161
162
### Command Interface
163
164
Functional interface for UI access operations.
165
166
```java { .api }
167
@FunctionalInterface
168
public interface Command extends Serializable {
169
void execute();
170
}
171
```
172
173
## Background Processing
174
175
### Background Task Execution
176
177
Utilities for executing background tasks with UI updates.
178
179
```java { .api }
180
// Execute task in background thread with UI updates
181
public class BackgroundTaskService {
182
183
public void executeWithProgress(Runnable task, Consumer<String> progressCallback) {
184
CompletableFuture.runAsync(() -> {
185
try {
186
task.run();
187
UI.getCurrent().access(() -> {
188
progressCallback.accept("Task completed");
189
});
190
} catch (Exception e) {
191
UI.getCurrent().access(() -> {
192
progressCallback.accept("Task failed: " + e.getMessage());
193
});
194
}
195
});
196
}
197
198
public <T> CompletableFuture<T> executeAsync(Supplier<T> task) {
199
UI ui = UI.getCurrent();
200
return CompletableFuture.supplyAsync(task)
201
.whenComplete((result, throwable) -> {
202
ui.access(() -> {
203
if (throwable != null) {
204
Notification.show("Error: " + throwable.getMessage());
205
} else {
206
Notification.show("Task completed successfully");
207
}
208
});
209
});
210
}
211
}
212
```
213
214
## Session Management
215
216
### VaadinSession
217
218
Session-level state and configuration management.
219
220
```java { .api }
221
public class VaadinSession implements WrappedSession {
222
// Current session access
223
public static VaadinSession getCurrent();
224
225
// Session state
226
public void lock();
227
public void unlock();
228
public boolean hasLock();
229
230
// Attribute management
231
public void setAttribute(String name, Object value);
232
public Object getAttribute(String name);
233
public <T> T getAttribute(String name, Class<T> type);
234
public void removeAttribute(String name);
235
public Set<String> getAttributeNames();
236
237
// Session lifecycle
238
public void close();
239
public boolean isClosed();
240
241
// Service access
242
public VaadinService getService();
243
public BrowserDetails getBrowser();
244
245
// Configuration
246
public void setConfiguration(DeploymentConfiguration configuration);
247
public DeploymentConfiguration getConfiguration();
248
249
// Error handling
250
public void setErrorHandler(ErrorHandler errorHandler);
251
public ErrorHandler getErrorHandler();
252
253
// Push configuration
254
public PushConfiguration getPushConfiguration();
255
public void setPushConfiguration(PushConfiguration pushConfiguration);
256
}
257
```
258
259
### VaadinService
260
261
Service-level configuration and utilities.
262
263
```java { .api }
264
public abstract class VaadinService {
265
// Current service access
266
public static VaadinService getCurrent();
267
268
// Service lifecycle
269
public void init();
270
public void destroy();
271
272
// Session management
273
public void storeSession(VaadinSession session, WrappedHttpSession wrappedSession);
274
public void removeSession(WrappedHttpSession wrappedSession);
275
276
// Request handling
277
public abstract void handleRequest(VaadinRequest request, VaadinResponse response);
278
279
// Configuration
280
public DeploymentConfiguration getDeploymentConfiguration();
281
public ClassLoader getClassLoader();
282
283
// Context
284
public VaadinContext getContext();
285
286
// Statistics
287
public SessionInitListener getSessionInitListener();
288
public SessionDestroyListener getSessionDestroyListener();
289
}
290
```
291
292
## Request and Response
293
294
### VaadinRequest
295
296
HTTP request wrapper with Vaadin-specific functionality.
297
298
```java { .api }
299
public interface VaadinRequest extends Serializable {
300
// Request parameters
301
String getParameter(String parameter);
302
Map<String, String[]> getParameterMap();
303
int getContentLength();
304
InputStream getInputStream();
305
306
// Headers
307
String getHeader(String headerName);
308
Enumeration<String> getHeaderNames();
309
long getDateHeader(String name);
310
int getIntHeader(String name);
311
312
// Request information
313
String getMethod();
314
String getRequestURI();
315
String getContextPath();
316
String getPathInfo();
317
String getRemoteAddr();
318
String getRemoteHost();
319
int getRemotePort();
320
boolean isSecure();
321
322
// Authentication
323
String getRemoteUser();
324
boolean isUserInRole(String role);
325
Principal getUserPrincipal();
326
327
// Wrapped request access
328
<T> T getWrappedSession(Class<T> wrappedSessionType);
329
Object getAttribute(String name);
330
void setAttribute(String name, Object value);
331
void removeAttribute(String name);
332
Enumeration<String> getAttributeNames();
333
334
// Service access
335
VaadinService getService();
336
}
337
```
338
339
### VaadinResponse
340
341
HTTP response wrapper with Vaadin-specific functionality.
342
343
```java { .api }
344
public interface VaadinResponse extends Serializable {
345
// Response writing
346
OutputStream getOutputStream();
347
PrintWriter getWriter();
348
349
// Headers
350
void setHeader(String name, String value);
351
void addHeader(String name, String value);
352
void setDateHeader(String name, long date);
353
void addDateHeader(String name, long date);
354
void setIntHeader(String name, int value);
355
void addIntHeader(String name, int value);
356
357
// Status
358
void setStatus(int statusCode);
359
void sendError(int errorCode, String message);
360
void sendRedirect(String url);
361
362
// Content
363
void setContentType(String type);
364
String getContentType();
365
void setContentLength(int len);
366
367
// Caching
368
void setCacheTime(long milliseconds);
369
370
// Service access
371
VaadinService getService();
372
}
373
```
374
375
## Client-Side Integration
376
377
### JavaScript Execution
378
379
Execute JavaScript code from server-side Java.
380
381
```java { .api }
382
public class Page {
383
// JavaScript execution
384
public PendingJavaScriptResult executeJs(String expression, Object... parameters);
385
public PendingJavaScriptResult executeJs(String expression, Serializable... parameters);
386
387
// Browser navigation
388
public void setLocation(String location);
389
public void setLocation(URI location);
390
public void open(String url);
391
public void open(String url, String windowName);
392
public void open(String url, String windowName, String windowFeatures);
393
394
// Page reload
395
public void reload();
396
397
// History management
398
public History getHistory();
399
public Extended getExtended();
400
}
401
402
public interface PendingJavaScriptResult extends Serializable {
403
void then(SerializableConsumer<JsonValue> resultHandler);
404
void then(SerializableConsumer<JsonValue> resultHandler, SerializableConsumer<String> errorHandler);
405
boolean isCanceled();
406
void cancel();
407
}
408
```
409
410
### Browser Information
411
412
Access browser capabilities and information.
413
414
```java { .api }
415
public class WebBrowser {
416
// Browser identification
417
public String getBrowserApplication();
418
public int getBrowserMajorVersion();
419
public int getBrowserMinorVersion();
420
public boolean isChrome();
421
public boolean isFirefox();
422
public boolean isSafari();
423
public boolean isEdge();
424
425
// Capabilities
426
public boolean isTouchDevice();
427
public boolean isWebKit();
428
public boolean isIE();
429
430
// Screen information
431
public int getScreenWidth();
432
public int getScreenHeight();
433
public int getTimezoneOffset();
434
public String getTimeZoneId();
435
436
// User agent
437
public String getUserAgent();
438
public String getAddress();
439
440
// Locale
441
public Locale getLocale();
442
public void updateRequestDetails(VaadinRequest request);
443
}
444
```
445
446
## WebSocket and Streaming
447
448
### StreamResource
449
450
Resource for streaming content to the browser.
451
452
```java { .api }
453
public class StreamResource implements AbstractStreamResource {
454
public StreamResource(String fileName, InputStreamFactory streamFactory);
455
456
// Content configuration
457
public void setContentType(String contentType);
458
public String getContentType();
459
public void setCacheTime(long cacheTime);
460
public long getCacheTime();
461
public void setHeader(String name, String value);
462
463
// Stream factory
464
@FunctionalInterface
465
public interface InputStreamFactory extends Serializable {
466
InputStream createInputStream();
467
}
468
}
469
470
// Usage for file downloads
471
public StreamResource createDownload(String fileName, String content) {
472
return new StreamResource(fileName, () ->
473
new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
474
}
475
```
476
477
## Event System
478
479
### Component Events
480
481
Framework for custom component events and server communication.
482
483
```java { .api }
484
public abstract class ComponentEvent<T extends Component> extends EventObject {
485
public ComponentEvent(T source, boolean fromClient);
486
487
public T getSource();
488
public boolean isFromClient();
489
public Optional<Element> getUnloadingElement();
490
}
491
492
@Target(ElementType.METHOD)
493
@Retention(RetentionPolicy.RUNTIME)
494
public @interface DomEvent {
495
String value();
496
String filter() default "";
497
boolean allowUpdates() default true;
498
}
499
500
@Target(ElementType.PARAMETER)
501
@Retention(RetentionPolicy.RUNTIME)
502
public @interface EventData {
503
String value();
504
}
505
```
506
507
## Error Handling
508
509
### Error Handling
510
511
Global and component-level error handling for communication failures.
512
513
```java { .api }
514
public interface ErrorHandler extends Serializable {
515
void error(ErrorEvent event);
516
}
517
518
public class ErrorEvent extends EventObject {
519
public ErrorEvent(Throwable throwable);
520
521
public Throwable getThrowable();
522
}
523
524
public class DefaultErrorHandler implements ErrorHandler {
525
public void error(ErrorEvent event);
526
527
public static void doDefault(ErrorEvent event);
528
public static Logger getLogger();
529
}
530
```
531
532
### Communication Error Events
533
534
Events for handling communication failures.
535
536
```java { .api }
537
// Reconnection handling
538
public class ReconnectDialogConfiguration {
539
public void setDialogText(String dialogText);
540
public String getDialogText();
541
public void setDialogTextGaveUp(String dialogTextGaveUp);
542
public String getDialogTextGaveUp();
543
public void setReconnectAttempts(int reconnectAttempts);
544
public int getReconnectAttempts();
545
public void setReconnectInterval(int reconnectInterval);
546
public int getReconnectInterval();
547
}
548
549
// Session expiration handling
550
public class SessionExpiredDialogConfiguration {
551
public void setDialogText(String dialogText);
552
public String getDialogText();
553
}
554
```
555
556
## Usage Examples
557
558
### Server Push Implementation
559
560
```java
561
@Push
562
@Route("live-data")
563
public class LiveDataView extends VerticalLayout {
564
private Label statusLabel = new Label();
565
private ProgressBar progressBar = new ProgressBar();
566
567
public LiveDataView() {
568
add(new H1("Live Data Updates"), statusLabel, progressBar);
569
570
// Start background task with push updates
571
startBackgroundTask();
572
}
573
574
private void startBackgroundTask() {
575
CompletableFuture.runAsync(() -> {
576
for (int i = 0; i <= 100; i++) {
577
final int progress = i;
578
579
// Update UI from background thread
580
getUI().ifPresent(ui -> ui.access(() -> {
581
progressBar.setValue(progress / 100.0);
582
statusLabel.setText("Processing: " + progress + "%");
583
}));
584
585
try {
586
Thread.sleep(100); // Simulate work
587
} catch (InterruptedException e) {
588
Thread.currentThread().interrupt();
589
break;
590
}
591
}
592
593
// Final update
594
getUI().ifPresent(ui -> ui.access(() -> {
595
statusLabel.setText("Task completed!");
596
Notification.show("Background task finished");
597
}));
598
});
599
}
600
}
601
```
602
603
### File Download with Streaming
604
605
```java
606
public class FileDownloadExample extends VerticalLayout {
607
608
public FileDownloadExample() {
609
Button downloadButton = new Button("Download Report");
610
downloadButton.addClickListener(e -> downloadReport());
611
add(downloadButton);
612
}
613
614
private void downloadReport() {
615
StreamResource resource = new StreamResource("report.pdf", () -> {
616
// Generate report data
617
return generateReportPDF();
618
});
619
620
resource.setContentType("application/pdf");
621
resource.setHeader("Content-Disposition", "attachment; filename=\"report.pdf\"");
622
623
// Trigger download
624
getUI().ifPresent(ui -> ui.getPage().open(resource));
625
}
626
627
private InputStream generateReportPDF() {
628
// Generate PDF content
629
return new ByteArrayInputStream("PDF content".getBytes());
630
}
631
}
632
```
633
634
### JavaScript Integration
635
636
```java
637
public class JavaScriptInteractionView extends VerticalLayout {
638
639
public JavaScriptInteractionView() {
640
Button callJSButton = new Button("Call JavaScript");
641
callJSButton.addClickListener(e -> callJavaScript());
642
643
add(callJSButton);
644
}
645
646
private void callJavaScript() {
647
// Execute JavaScript and handle result
648
getUI().ifPresent(ui -> {
649
ui.getPage().executeJs("return navigator.userAgent")
650
.then(jsonValue -> {
651
String userAgent = jsonValue.asString();
652
Notification.show("User Agent: " + userAgent);
653
});
654
});
655
656
// Execute JavaScript with parameters
657
getUI().ifPresent(ui -> {
658
ui.getPage().executeJs("alert($0)", "Hello from server!")
659
.then(result -> {
660
Notification.show("JavaScript executed");
661
});
662
});
663
}
664
}
665
```
666
667
### Session Management
668
669
```java
670
public class SessionManagementExample extends VerticalLayout {
671
672
public SessionManagementExample() {
673
Button storeDataButton = new Button("Store Session Data");
674
storeDataButton.addClickListener(e -> storeSessionData());
675
676
Button retrieveDataButton = new Button("Retrieve Session Data");
677
retrieveDataButton.addClickListener(e -> retrieveSessionData());
678
679
add(storeDataButton, retrieveDataButton);
680
}
681
682
private void storeSessionData() {
683
VaadinSession session = VaadinSession.getCurrent();
684
session.setAttribute("user-data", "Important user information");
685
Notification.show("Data stored in session");
686
}
687
688
private void retrieveSessionData() {
689
VaadinSession session = VaadinSession.getCurrent();
690
String data = (String) session.getAttribute("user-data");
691
if (data != null) {
692
Notification.show("Retrieved: " + data);
693
} else {
694
Notification.show("No data found in session");
695
}
696
}
697
}
698
```
699
700
The server communication APIs provide comprehensive control over client-server interactions while maintaining the automatic synchronization that makes Vaadin development productive.