or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

http-abstractions.mdhttp-clients.mdindex.mdmessage-conversion.mdreactive-web.mdweb-binding.mdweb-utilities.md

web-utilities.mddocs/

0

# Web Utilities and Additional Features

1

2

Utility classes and additional features for web applications including URI building, HTML escaping, pattern matching, CORS support, web service client abstractions, and other web-related helper functionality.

3

4

## Capabilities

5

6

### URI Building and Components

7

8

Comprehensive URI building and parsing utilities for constructing URLs with proper encoding and parameter handling.

9

10

```java { .api }

11

/**

12

* Builder-style methods to prepare and expand a URI template with variables

13

*/

14

interface UriBuilder {

15

/** Set the URI scheme (protocol) */

16

UriBuilder scheme(String scheme);

17

/** Set the user info portion of the URI */

18

UriBuilder userInfo(String userInfo);

19

/** Set the host name */

20

UriBuilder host(String host);

21

/** Set the port number */

22

UriBuilder port(int port);

23

/** Set the port from string */

24

UriBuilder port(String port);

25

/** Append to the path */

26

UriBuilder path(String path);

27

/** Add path segments (automatically URL-encoded) */

28

UriBuilder pathSegment(String... pathSegments);

29

/** Replace the entire path */

30

UriBuilder replacePath(String path);

31

/** Set the query string */

32

UriBuilder query(String query);

33

/** Replace the entire query string */

34

UriBuilder replaceQuery(String query);

35

/** Add query parameter with values */

36

UriBuilder queryParam(String name, Object... values);

37

/** Add query parameter with collection values */

38

UriBuilder queryParam(String name, Collection<?> values);

39

/** Add query parameter if Optional value is present */

40

UriBuilder queryParamIfPresent(String name, Optional<?> value);

41

/** Add multiple query parameters from map */

42

UriBuilder queryParams(MultiValueMap<String, String> params);

43

/** Replace existing query parameter */

44

UriBuilder replaceQueryParam(String name, Object... values);

45

/** Replace existing query parameter with collection */

46

UriBuilder replaceQueryParam(String name, Collection<?> values);

47

/** Replace all query parameters */

48

UriBuilder replaceQueryParams(MultiValueMap<String, String> params);

49

/** Set the URI fragment */

50

UriBuilder fragment(String fragment);

51

/** Build URI with positional variables */

52

URI build(Object... uriVariables);

53

/** Build URI with named variables */

54

URI build(Map<String, ?> uriVariables);

55

}

56

57

/**

58

* Builder for UriComponents with fluent API

59

*/

60

class UriComponentsBuilder implements UriBuilder, Cloneable {

61

/** Create new empty builder */

62

static UriComponentsBuilder newInstance();

63

/** Create builder from path */

64

static UriComponentsBuilder fromPath(String path);

65

/** Create builder from existing URI */

66

static UriComponentsBuilder fromUri(URI uri);

67

/** Create builder from URI string */

68

static UriComponentsBuilder fromUriString(String uri);

69

/** Create builder from HTTP URL string */

70

static UriComponentsBuilder fromHttpUrl(String httpUrl);

71

/** Create builder from HTTP request */

72

static UriComponentsBuilder fromHttpRequest(HttpRequest request);

73

74

/** Build UriComponents instance */

75

UriComponents build();

76

/** Build with encoding flag */

77

UriComponents build(boolean encoded);

78

/** Build and expand with positional variables */

79

UriComponents buildAndExpand(Object... uriVariableValues);

80

/** Build and expand with named variables */

81

UriComponents buildAndExpand(Map<String, ?> uriVariables);

82

/** Convert to URI string directly */

83

String toUriString();

84

}

85

86

/**

87

* Immutable collection of URI components

88

*/

89

abstract class UriComponents {

90

/** Get the scheme (protocol) */

91

String getScheme();

92

/** Get the fragment identifier */

93

String getFragment();

94

/** Get scheme-specific part */

95

String getSchemeSpecificPart();

96

/** Get user information */

97

String getUserInfo();

98

/** Get host name */

99

String getHost();

100

/** Get port number */

101

int getPort();

102

/** Get path */

103

String getPath();

104

/** Get path segments as list */

105

List<String> getPathSegments();

106

/** Get query string */

107

String getQuery();

108

/** Get query parameters as map */

109

MultiValueMap<String, String> getQueryParams();

110

111

/** Encode all URI components */

112

UriComponents encode();

113

/** Encode with specific charset */

114

UriComponents encode(Charset charset);

115

/** Expand template variables with positional args */

116

UriComponents expand(Object... uriVariableValues);

117

/** Expand template variables with named args */

118

UriComponents expand(Map<String, ?> uriVariables);

119

/** Normalize the URI (remove redundant segments) */

120

UriComponents normalize();

121

/** Convert to java.net.URI */

122

URI toUri();

123

/** Convert to URI string */

124

String toUriString();

125

}

126

```

127

128

**Usage Examples:**

129

130

```java

131

import org.springframework.web.util.UriComponentsBuilder;

132

133

// Basic URI building

134

URI uri = UriComponentsBuilder

135

.fromHttpUrl("https://api.example.com")

136

.path("/users/{id}")

137

.queryParam("include", "profile", "settings")

138

.buildAndExpand(123)

139

.toUri();

140

// Result: https://api.example.com/users/123?include=profile&include=settings

141

142

// Query parameter building

143

String url = UriComponentsBuilder

144

.fromPath("/search")

145

.queryParam("q", "spring framework")

146

.queryParam("page", 1)

147

.queryParam("size", 20)

148

.toUriString();

149

// Result: /search?q=spring+framework&page=1&size=20

150

```

151

152

### HTML and JavaScript Escaping

153

154

Utility methods for safely escaping HTML content and JavaScript strings to prevent XSS attacks.

155

156

```java { .api }

157

/**

158

* Utility class for HTML escaping and unescaping

159

*/

160

class HtmlUtils {

161

/** Escape HTML characters using HTML entities */

162

static String htmlEscape(String input);

163

/** Escape HTML characters with specific encoding */

164

static String htmlEscape(String input, String encoding);

165

/** Escape HTML characters using decimal entities */

166

static String htmlEscapeDecimal(String input);

167

/** Escape HTML characters using decimal entities with encoding */

168

static String htmlEscapeDecimal(String input, String encoding);

169

/** Escape HTML characters using hexadecimal entities */

170

static String htmlEscapeHex(String input);

171

/** Escape HTML characters using hexadecimal entities with encoding */

172

static String htmlEscapeHex(String input, String encoding);

173

/** Unescape HTML entities back to characters */

174

static String htmlUnescape(String input);

175

}

176

177

/**

178

* Utility class for JavaScript escaping

179

*/

180

class JavaScriptUtils {

181

/** Escape JavaScript special characters */

182

static String javaScriptEscape(String input);

183

}

184

```

185

186

**Usage Examples:**

187

188

```java

189

import org.springframework.web.util.HtmlUtils;

190

import org.springframework.web.util.JavaScriptUtils;

191

192

// HTML escaping

193

String userInput = "<script>alert('xss')</script>";

194

String safe = HtmlUtils.htmlEscape(userInput);

195

// Result: "&lt;script&gt;alert('xss')&lt;/script&gt;"

196

197

// JavaScript escaping

198

String jsString = "Don't break \"my\" JavaScript!";

199

String escaped = JavaScriptUtils.javaScriptEscape(jsString);

200

// Result: "Don\\'t break \\\"my\\\" JavaScript!"

201

```

202

203

### Path Pattern Matching

204

205

Advanced pattern matching for URI paths with support for wildcards, path variables, and flexible matching options.

206

207

```java { .api }

208

/**

209

* Representation of a parsed path pattern for matching against paths

210

*/

211

class PathPattern implements Comparable<PathPattern> {

212

/** Get the original pattern string */

213

String getPatternString();

214

/** Test if this pattern matches the given path */

215

boolean matches(PathContainer pathContainer);

216

/** Match and extract path variables */

217

PathPattern.PathMatchInfo matchAndExtract(PathContainer pathContainer);

218

/** Match start of path for partial matching */

219

PathPattern.PathRemainingMatchInfo matchStartOfPath(PathContainer pathContainer);

220

/** Combine this pattern with another */

221

PathPattern combine(PathPattern pattern2);

222

/** Compare patterns for specificity ordering */

223

int compareTo(PathPattern otherPattern);

224

225

/** Path match information with extracted variables */

226

class PathMatchInfo {

227

/** Get extracted URI template variables */

228

Map<String, String> getUriVariables();

229

/** Get the matched path portion */

230

PathContainer getMatchedPath();

231

}

232

233

/** Partial path match information */

234

class PathRemainingMatchInfo extends PathMatchInfo {

235

/** Get the remaining unmatched path portion */

236

PathContainer getRemainingPath();

237

}

238

}

239

240

/**

241

* Parser for URI path patterns into PathPattern instances

242

*/

243

class PathPatternParser {

244

PathPatternParser();

245

246

/** Configure matching of optional trailing separator */

247

void setMatchOptionalTrailingSeparator(boolean matchOptionalTrailingSeparator);

248

boolean isMatchOptionalTrailingSeparator();

249

250

/** Configure case sensitivity */

251

void setCaseSensitive(boolean caseSensitive);

252

boolean isCaseSensitive();

253

254

/** Parse a path pattern string */

255

PathPattern parse(String pathPattern);

256

}

257

258

/**

259

* Structured representation of a URI path

260

*/

261

interface PathContainer {

262

/** Get the full path as string */

263

String value();

264

/** Get path elements */

265

List<Element> elements();

266

/** Extract subpath from index */

267

PathContainer subPath(int index);

268

/** Extract subpath from range */

269

PathContainer subPath(int fromIndex, int toIndex);

270

271

/** Parse path string into PathContainer */

272

static PathContainer parsePath(String path);

273

274

/** Individual path element */

275

interface Element {

276

String value();

277

}

278

279

/** Path separator element */

280

interface Separator extends Element {

281

}

282

283

/** Path segment element */

284

interface PathSegment extends Element {

285

String valueToMatch();

286

char[] valueToMatchAsChars();

287

Map<String, String> parameters();

288

}

289

}

290

```

291

292

**Usage Examples:**

293

294

```java

295

import org.springframework.web.util.pattern.*;

296

297

// Pattern parsing and matching

298

PathPatternParser parser = new PathPatternParser();

299

PathPattern pattern = parser.parse("/api/users/{id}/posts/{postId}");

300

301

PathContainer path = PathContainer.parsePath("/api/users/123/posts/456");

302

boolean matches = pattern.matches(path);

303

// Result: true

304

305

PathPattern.PathMatchInfo matchInfo = pattern.matchAndExtract(path);

306

Map<String, String> variables = matchInfo.getUriVariables();

307

// Result: {id=123, postId=456}

308

```

309

310

### Web Service Client Support

311

312

Declarative HTTP service client abstractions for creating type-safe API clients from annotated interfaces.

313

314

```java { .api }

315

/**

316

* Factory to create client proxies from HTTP service interfaces

317

*/

318

class HttpServiceProxyFactory {

319

/** Create builder for configuring the factory */

320

static HttpServiceProxyFactory.Builder builder();

321

/** Create builder with WebClient */

322

static HttpServiceProxyFactory.Builder builderFor(WebClient webClient);

323

/** Create builder with RestTemplate */

324

static HttpServiceProxyFactory.Builder builderFor(RestTemplate restTemplate);

325

/** Create builder with RestClient */

326

static HttpServiceProxyFactory.Builder builderFor(RestClient restClient);

327

328

/** Create client proxy for service interface */

329

<S> S createClient(Class<S> serviceType);

330

331

/** Builder for HttpServiceProxyFactory */

332

interface Builder {

333

Builder customArgumentResolver(HttpServiceArgumentResolver argumentResolver);

334

Builder embeddedValueResolver(StringValueResolver embeddedValueResolver);

335

Builder conversionService(ConversionService conversionService);

336

HttpServiceProxyFactory build();

337

}

338

}

339

340

/**

341

* Declares an HTTP service interface method as an HTTP endpoint

342

*/

343

@Target({ElementType.TYPE, ElementType.METHOD})

344

@Retention(RetentionPolicy.RUNTIME)

345

@Documented

346

@interface HttpExchange {

347

/** URL for the request */

348

String value() default "";

349

/** Alias for value */

350

String url() default "";

351

/** HTTP method for the request */

352

String method() default "";

353

/** Content-Type header value */

354

String contentType() default "";

355

/** Accept header values */

356

String[] accept() default {};

357

}

358

359

/**

360

* Shortcut annotations for specific HTTP methods

361

*/

362

@HttpExchange(method = "GET")

363

@interface GetExchange {

364

String value() default "";

365

String url() default "";

366

}

367

368

@HttpExchange(method = "POST")

369

@interface PostExchange {

370

String value() default "";

371

String url() default "";

372

}

373

374

@HttpExchange(method = "PUT")

375

@interface PutExchange {

376

String value() default "";

377

String url() default "";

378

}

379

380

@HttpExchange(method = "DELETE")

381

@interface DeleteExchange {

382

String value() default "";

383

String url() default "";

384

}

385

386

@HttpExchange(method = "PATCH")

387

@interface PatchExchange {

388

String value() default "";

389

String url() default "";

390

}

391

```

392

393

**Usage Examples:**

394

395

```java

396

import org.springframework.web.service.annotation.*;

397

398

// Define HTTP service interface

399

@HttpExchange(url = "/api/users")

400

interface UserService {

401

402

@GetExchange

403

List<User> getAllUsers();

404

405

@GetExchange("/{id}")

406

User getUser(@PathVariable Long id);

407

408

@PostExchange

409

User createUser(@RequestBody User user);

410

411

@PutExchange("/{id}")

412

User updateUser(@PathVariable Long id, @RequestBody User user);

413

414

@DeleteExchange("/{id}")

415

void deleteUser(@PathVariable Long id);

416

}

417

418

// Create client proxy

419

RestClient restClient = RestClient.create("https://api.example.com");

420

HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(restClient).build();

421

UserService userService = factory.createClient(UserService.class);

422

423

// Use the client

424

List<User> users = userService.getAllUsers();

425

User user = userService.getUser(123L);

426

```

427

428

### Web Application Utilities

429

430

General-purpose utility methods for common web application tasks including servlet operations and parameter handling.

431

432

```java { .api }

433

/**

434

* Miscellaneous utilities for web applications

435

*/

436

class WebUtils {

437

/** Get the real filesystem path for a web application path */

438

static String getRealPath(ServletContext servletContext, String path);

439

/** Get temporary directory for the web application */

440

static File getTempDir(ServletContext servletContext);

441

442

/** Get session attribute value */

443

static Object getSessionAttribute(HttpServletRequest request, String name);

444

/** Get required session attribute (throws exception if missing) */

445

static Object getRequiredSessionAttribute(HttpServletRequest request, String name);

446

/** Set session attribute */

447

static void setSessionAttribute(HttpServletRequest request, String name, Object value);

448

/** Get or create session attribute with class instantiation */

449

static Object getOrCreateSessionAttribute(HttpSession session, String name, Class<?> clazz);

450

451

/** Find parameter value in request */

452

static String findParameterValue(ServletRequest request, String name);

453

/** Get parameters starting with prefix as map */

454

static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix);

455

456

/** Get cookie by name */

457

static Cookie getCookie(HttpServletRequest request, String name);

458

459

/** Check if request has submit parameter */

460

static boolean hasSubmitParameter(ServletRequest request, String name);

461

/** Get submit parameter value */

462

static String getSubmitParameter(ServletRequest request, String name);

463

}

464

```

465

466

### CORS Support

467

468

Cross-Origin Resource Sharing (CORS) configuration and processing for handling cross-domain requests.

469

470

```java { .api }

471

/**

472

* CORS configuration for cross-origin requests

473

*/

474

class CorsConfiguration {

475

CorsConfiguration();

476

477

/** Set allowed origins */

478

void setAllowedOrigins(List<String> allowedOrigins);

479

List<String> getAllowedOrigins();

480

/** Add allowed origin */

481

void addAllowedOrigin(String origin);

482

483

/** Set allowed origin patterns */

484

void setAllowedOriginPatterns(List<String> allowedOriginPatterns);

485

List<String> getAllowedOriginPatterns();

486

/** Add allowed origin pattern */

487

void addAllowedOriginPattern(String originPattern);

488

489

/** Set allowed HTTP methods */

490

void setAllowedMethods(List<String> allowedMethods);

491

List<String> getAllowedMethods();

492

/** Add allowed method */

493

void addAllowedMethod(HttpMethod method);

494

495

/** Set allowed headers */

496

void setAllowedHeaders(List<String> allowedHeaders);

497

List<String> getAllowedHeaders();

498

/** Add allowed header */

499

void addAllowedHeader(String allowedHeader);

500

501

/** Set exposed headers */

502

void setExposedHeaders(List<String> exposedHeaders);

503

List<String> getExposedHeaders();

504

/** Add exposed header */

505

void addExposedHeader(String exposedHeader);

506

507

/** Set allow credentials flag */

508

void setAllowCredentials(Boolean allowCredentials);

509

Boolean getAllowCredentials();

510

511

/** Set max age for preflight cache */

512

void setMaxAge(Long maxAge);

513

Long getMaxAge();

514

515

/** Check if origin is allowed */

516

String checkOrigin(String requestOrigin);

517

/** Check if HTTP method is allowed */

518

List<HttpMethod> checkHttpMethod(HttpMethod requestMethod);

519

/** Check if headers are allowed */

520

List<String> checkHeaders(List<String> requestHeaders);

521

}

522

523

/**

524

* CORS processor for handling CORS requests

525

*/

526

class CorsProcessor {

527

/** Process CORS request with configuration */

528

boolean processRequest(CorsConfiguration config, ServerHttpRequest request, ServerHttpResponse response);

529

}

530

```

531

532

### Content Negotiation

533

534

Content type negotiation and cache control utilities for optimizing HTTP responses.

535

536

```java { .api }

537

/**

538

* Builder for Cache-Control HTTP header values

539

*/

540

class CacheControl {

541

/** Create empty cache control */

542

static CacheControl empty();

543

/** Create with max-age directive */

544

static CacheControl maxAge(Duration maxAge);

545

/** Create no-cache directive */

546

static CacheControl noCache();

547

/** Create no-store directive */

548

static CacheControl noStore();

549

550

/** Add must-revalidate directive */

551

CacheControl mustRevalidate();

552

/** Add no-transform directive */

553

CacheControl noTransform();

554

/** Add public directive */

555

CacheControl cachePublic();

556

/** Add private directive */

557

CacheControl cachePrivate();

558

/** Add s-maxage directive */

559

CacheControl sMaxAge(Duration sMaxAge);

560

/** Add stale-while-revalidate directive */

561

CacheControl staleWhileRevalidate(Duration staleWhileRevalidate);

562

/** Add stale-if-error directive */

563

CacheControl staleIfError(Duration staleIfError);

564

565

/** Get the header value string */

566

String getHeaderValue();

567

}

568

569

/**

570

* Represents Content-Disposition header value

571

*/

572

class ContentDisposition {

573

/** Check if disposition type is attachment */

574

boolean isAttachment();

575

/** Check if disposition type is form-data */

576

boolean isFormData();

577

/** Check if disposition type is inline */

578

boolean isInline();

579

580

/** Get disposition type */

581

String getType();

582

/** Get name parameter */

583

String getName();

584

/** Get filename parameter */

585

String getFilename();

586

/** Get charset parameter */

587

Charset getCharset();

588

/** Get creation date parameter */

589

ZonedDateTime getCreationDate();

590

/** Get modification date parameter */

591

ZonedDateTime getModificationDate();

592

/** Get read date parameter */

593

ZonedDateTime getReadDate();

594

/** Get size parameter */

595

Long getSize();

596

597

/** Create builder for attachment disposition */

598

static ContentDisposition.Builder attachment();

599

/** Create builder for form-data disposition */

600

static ContentDisposition.Builder formData();

601

/** Create builder for inline disposition */

602

static ContentDisposition.Builder inline();

603

604

/** Builder for ContentDisposition */

605

interface Builder {

606

Builder name(String name);

607

Builder filename(String filename);

608

Builder filename(String filename, Charset charset);

609

Builder size(Long size);

610

Builder creationDate(ZonedDateTime creationDate);

611

Builder modificationDate(ZonedDateTime modificationDate);

612

Builder readDate(ZonedDateTime readDate);

613

ContentDisposition build();

614

}

615

}

616

617

/**

618

* RFC 7807 Problem Detail for HTTP APIs

619

*/

620

class ProblemDetail {

621

ProblemDetail(int status);

622

623

/** Get problem type URI */

624

URI getType();

625

void setType(URI type);

626

627

/** Get human-readable title */

628

String getTitle();

629

void setTitle(String title);

630

631

/** Get HTTP status code */

632

int getStatus();

633

634

/** Get detailed explanation */

635

String getDetail();

636

void setDetail(String detail);

637

638

/** Get problem instance URI */

639

URI getInstance();

640

void setInstance(URI instance);

641

642

/** Get additional properties */

643

Map<String, Object> getProperties();

644

void setProperty(String name, Object value);

645

Object getProperty(String name);

646

647

/** Factory method for status code */

648

static ProblemDetail forStatus(HttpStatusCode status);

649

/** Factory method for status and detail */

650

static ProblemDetail forStatusAndDetail(HttpStatusCode status, String detail);

651

}

652

```

653

654

**Usage Examples:**

655

656

```java

657

import org.springframework.http.CacheControl;

658

import org.springframework.http.ContentDisposition;

659

import org.springframework.http.ProblemDetail;

660

661

// Cache control

662

CacheControl cacheControl = CacheControl

663

.maxAge(Duration.ofHours(1))

664

.mustRevalidate()

665

.cachePublic();

666

String headerValue = cacheControl.getHeaderValue();

667

// Result: "max-age=3600, must-revalidate, public"

668

669

// Content disposition for file downloads

670

ContentDisposition disposition = ContentDisposition

671

.attachment()

672

.filename("report.pdf")

673

.build();

674

675

// Problem detail for error responses

676

ProblemDetail problem = ProblemDetail.forStatusAndDetail(

677

HttpStatus.BAD_REQUEST,

678

"Invalid user input"

679

);

680

problem.setTitle("Validation Error");

681

problem.setProperty("field", "email");

682

```