0
# Dropwizard Jersey
1
2
Dropwizard Jersey provides comprehensive Jersey REST framework integration for Dropwizard applications. It offers type-safe parameter converters, session management, validation integration, optional handling, standardized error handling, HTTP caching, GZIP compression, and Jackson JSON processing to build robust RESTful web services.
3
4
## Package Information
5
6
- **Package Name**: dropwizard-jersey
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: Add to `pom.xml`:
10
11
```xml
12
<dependency>
13
<groupId>io.dropwizard</groupId>
14
<artifactId>dropwizard-jersey</artifactId>
15
<version>4.0.14</version>
16
</dependency>
17
```
18
19
## Core Imports
20
21
```java
22
import io.dropwizard.jersey.DropwizardResourceConfig;
23
import io.dropwizard.jersey.setup.JerseyEnvironment;
24
import io.dropwizard.jersey.params.*;
25
import io.dropwizard.jersey.sessions.Session;
26
import io.dropwizard.jersey.sessions.Flash;
27
import io.dropwizard.jersey.validation.Validators;
28
import io.dropwizard.jersey.caching.CacheControl;
29
import io.dropwizard.jersey.PATCH;
30
```
31
32
## Basic Usage
33
34
```java
35
import io.dropwizard.jersey.DropwizardResourceConfig;
36
import io.dropwizard.jersey.setup.JerseyEnvironment;
37
import io.dropwizard.jersey.params.UUIDParam;
38
import io.dropwizard.jersey.sessions.Session;
39
import io.dropwizard.jersey.caching.CacheControl;
40
import io.dropwizard.jersey.PATCH;
41
42
import jakarta.servlet.http.HttpSession;
43
import jakarta.ws.rs.*;
44
import jakarta.ws.rs.core.MediaType;
45
import java.util.UUID;
46
import java.util.concurrent.TimeUnit;
47
48
// Configure Jersey with Dropwizard enhancements
49
DropwizardResourceConfig config = new DropwizardResourceConfig();
50
JerseyEnvironment jersey = new JerseyEnvironment(holder, config);
51
52
// Register a resource
53
jersey.register(UserResource.class);
54
55
@Path("/users")
56
@Produces(MediaType.APPLICATION_JSON)
57
public class UserResource {
58
59
// Type-safe parameter handling
60
@GET
61
@Path("/{id}")
62
public User getUser(@PathParam("id") UUIDParam userId) {
63
UUID id = userId.get(); // Automatic parsing and validation
64
return userService.findById(id);
65
}
66
67
// Session management
68
@POST
69
@Path("/{id}/preferences")
70
public void savePreferences(@PathParam("id") UUIDParam userId,
71
@Session HttpSession session,
72
UserPreferences prefs) {
73
session.setAttribute("userId", userId.get());
74
userService.savePreferences(userId.get(), prefs);
75
}
76
77
// HTTP caching
78
@GET
79
@Path("/public")
80
@CacheControl(maxAge = 300, maxAgeUnit = TimeUnit.SECONDS)
81
public List<User> getPublicUsers() {
82
return userService.getPublicUsers();
83
}
84
85
// PATCH method support
86
@PATCH
87
@Path("/{id}")
88
public User updateUser(@PathParam("id") UUIDParam userId,
89
UserUpdate update) {
90
return userService.updateUser(userId.get(), update);
91
}
92
}
93
```
94
95
## Architecture
96
97
Dropwizard Jersey is built around several key components:
98
99
- **Resource Configuration**: `DropwizardResourceConfig` extends Jersey's ResourceConfig with Dropwizard-specific providers and features
100
- **Environment Facade**: `JerseyEnvironment` provides a simplified interface for Jersey configuration
101
- **Parameter System**: Type-safe parameter converters for common types with automatic validation and error handling
102
- **Session Integration**: HTTP session support with flash message capabilities for web applications
103
- **Validation Framework**: Hibernate Validator integration with JAX-RS for request/response validation
104
- **Error Handling**: Standardized error responses with `ErrorMessage` format and exception mappers
105
- **Optional Handling**: Support for Java 8 Optional and Guava Optional types with automatic 404 responses for empty values
106
- **JSR310 Support**: Date/time parameter converters for modern Java time API
107
108
## Capabilities
109
110
### Framework Configuration
111
112
Core Jersey framework integration providing the main configuration classes and environment setup for Dropwizard applications.
113
114
```java { .api }
115
public class DropwizardResourceConfig extends ResourceConfig {
116
public DropwizardResourceConfig();
117
public DropwizardResourceConfig(MetricRegistry metricRegistry);
118
public static DropwizardResourceConfig forTesting();
119
public static DropwizardResourceConfig forTesting(MetricRegistry metricRegistry);
120
public String getUrlPattern();
121
public void setUrlPattern(String urlPattern);
122
public String getContextPath();
123
public void setContextPath(String contextPath);
124
public ResourceConfig register(Object component);
125
}
126
127
public class JerseyEnvironment {
128
public void register(Object component);
129
public void register(Class<?> componentClass);
130
public void packages(String... packages);
131
public void enable(String featureName);
132
public void disable(String featureName);
133
public void property(String name, Object value);
134
public <T> T getProperty(String name);
135
public DropwizardResourceConfig getResourceConfig();
136
}
137
```
138
139
[Framework Configuration](./framework-configuration.md)
140
141
### Parameter Handling
142
143
Type-safe parameter converters for common data types with automatic parsing, validation, and error handling for JAX-RS resource methods.
144
145
```java { .api }
146
public abstract class AbstractParam<T> {
147
protected AbstractParam(String input);
148
protected AbstractParam(String input, String parameterName);
149
public T get();
150
protected abstract T parse(String input) throws Exception;
151
protected String errorMessage(Exception e);
152
}
153
154
public class UUIDParam extends AbstractParam<UUID> {
155
public UUIDParam(String input);
156
public UUIDParam(String input, String parameterName);
157
}
158
159
public class IntParam extends AbstractParam<Integer> {
160
public IntParam(String input);
161
public IntParam(String input, String parameterName);
162
}
163
164
public class LongParam extends AbstractParam<Long> {
165
public LongParam(String input);
166
public LongParam(String input, String parameterName);
167
}
168
169
public class NonEmptyStringParam extends AbstractParam<String> {
170
public NonEmptyStringParam(String input);
171
public NonEmptyStringParam(String input, String parameterName);
172
}
173
```
174
175
[Parameter Handling](./parameter-handling.md)
176
177
### Session Management
178
179
HTTP session integration with injection support and flash message capabilities for web applications requiring session state.
180
181
```java { .api }
182
@Target({ElementType.PARAMETER, ElementType.FIELD})
183
@Retention(RetentionPolicy.RUNTIME)
184
public @interface Session {
185
boolean doNotCreate() default false;
186
}
187
188
public class Flash<T> {
189
public Optional<T> get();
190
public void set(T value);
191
}
192
193
public class HttpSessionFactory implements Factory<HttpSession> {
194
public HttpSession provide();
195
}
196
197
public class FlashFactory implements Factory<Flash<?>> {
198
public Flash<?> provide();
199
}
200
```
201
202
[Session Management](./session-management.md)
203
204
### Error Handling
205
206
Standardized error handling with consistent error message format and exception mappers for common exceptions.
207
208
```java { .api }
209
public class ErrorMessage {
210
public ErrorMessage(String message);
211
public ErrorMessage(int code, String message);
212
public ErrorMessage(int code, String message, String details);
213
public Integer getCode();
214
public String getMessage();
215
public String getDetails();
216
}
217
218
public class LoggingExceptionMapper<E extends Throwable> implements ExceptionMapper<E> {
219
public Response toResponse(E exception);
220
}
221
222
public class IllegalStateExceptionMapper implements ExceptionMapper<IllegalStateException> {
223
public Response toResponse(IllegalStateException exception);
224
}
225
```
226
227
[Error Handling](./error-handling.md)
228
229
### Validation
230
231
Hibernate Validator integration providing comprehensive validation support for JAX-RS resources with custom parameter extractors.
232
233
```java { .api }
234
public class Validators {
235
public static Validator newValidator();
236
public static ValidatorFactory newValidatorFactory();
237
public static HibernateValidatorConfiguration newConfiguration();
238
}
239
240
public class JerseyViolationException extends ValidationException {
241
public JerseyViolationException(Set<ConstraintViolation<?>> violations);
242
public Set<ConstraintViolation<?>> getConstraintViolations();
243
}
244
245
public class ValidationErrorMessage {
246
public List<String> getErrors();
247
public ValidationErrorMessage(Collection<String> errors);
248
}
249
```
250
251
[Validation](./validation.md)
252
253
### Optional Handling
254
255
Support for Java 8 Optional and Guava Optional types with automatic serialization and 404 responses for empty values.
256
257
```java { .api }
258
public class OptionalMessageBodyWriter implements MessageBodyWriter<Optional<?>> {
259
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType);
260
public void writeTo(Optional<?> entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream);
261
}
262
263
public class EmptyOptionalException extends WebApplicationException {
264
public EmptyOptionalException();
265
public EmptyOptionalException(String message);
266
}
267
268
public class OptionalIntMessageBodyWriter implements MessageBodyWriter<OptionalInt> {
269
public void writeTo(OptionalInt entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream);
270
}
271
```
272
273
[Optional Handling](./optional-handling.md)
274
275
### HTTP Caching
276
277
HTTP caching support through annotations with comprehensive Cache-Control header configuration for optimizing web service performance.
278
279
```java { .api }
280
@Target(ElementType.METHOD)
281
@Retention(RetentionPolicy.RUNTIME)
282
public @interface CacheControl {
283
boolean immutable() default false;
284
boolean isPrivate() default false;
285
boolean noCache() default false;
286
boolean noStore() default false;
287
boolean noTransform() default true;
288
boolean mustRevalidate() default false;
289
boolean proxyRevalidate() default false;
290
int maxAge() default -1;
291
TimeUnit maxAgeUnit() default TimeUnit.SECONDS;
292
int staleWhileRevalidate() default -1;
293
TimeUnit staleWhileRevalidateUnit() default TimeUnit.SECONDS;
294
int sharedMaxAge() default -1;
295
TimeUnit sharedMaxAgeUnit() default TimeUnit.SECONDS;
296
}
297
298
public class CacheControlledResponseFeature implements Feature {
299
public boolean configure(FeatureContext context);
300
}
301
```
302
303
[HTTP Caching](./http-caching.md)
304
305
### JSR310 Date/Time Parameters
306
307
Parameter converters for Java 8 date/time API types providing type-safe parsing of date and time values from HTTP requests.
308
309
```java { .api }
310
public class InstantParam extends AbstractParam<Instant> {
311
public InstantParam(String input);
312
public InstantParam(String input, String parameterName);
313
}
314
315
public class LocalDateParam extends AbstractParam<LocalDate> {
316
public LocalDateParam(String input);
317
public LocalDateParam(String input, String parameterName);
318
}
319
320
public class LocalDateTimeParam extends AbstractParam<LocalDateTime> {
321
public LocalDateTimeParam(String input);
322
public LocalDateTimeParam(String input, String parameterName);
323
}
324
325
public class ZonedDateTimeParam extends AbstractParam<ZonedDateTime> {
326
public ZonedDateTimeParam(String input);
327
public ZonedDateTimeParam(String input, String parameterName);
328
}
329
```
330
331
[JSR310 Date/Time Parameters](./jsr310-parameters.md)
332
333
## Types
334
335
```java { .api }
336
// Common interfaces
337
public interface Factory<T> {
338
T provide();
339
}
340
341
// Exception types
342
public class WebApplicationException extends RuntimeException {
343
public WebApplicationException(String message, int status);
344
public WebApplicationException(String message, Response.Status status);
345
}
346
347
// Validation types
348
public interface ConstraintViolation<T> {
349
String getMessage();
350
String getPropertyPath();
351
T getRootBean();
352
Object getInvalidValue();
353
}
354
355
// Time units for caching
356
public enum TimeUnit {
357
NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS;
358
}
359
360
// HTTP method annotation
361
@Target({ElementType.METHOD})
362
@Retention(RetentionPolicy.RUNTIME)
363
@HttpMethod("PATCH")
364
public @interface PATCH {
365
}
366
```