Spring Web module providing web application infrastructure including HTTP integration, servlet filters, Spring web MVC framework, and reactive web stack support
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.
Comprehensive URI building and parsing utilities for constructing URLs with proper encoding and parameter handling.
/**
* Builder-style methods to prepare and expand a URI template with variables
*/
interface UriBuilder {
/** Set the URI scheme (protocol) */
UriBuilder scheme(String scheme);
/** Set the user info portion of the URI */
UriBuilder userInfo(String userInfo);
/** Set the host name */
UriBuilder host(String host);
/** Set the port number */
UriBuilder port(int port);
/** Set the port from string */
UriBuilder port(String port);
/** Append to the path */
UriBuilder path(String path);
/** Add path segments (automatically URL-encoded) */
UriBuilder pathSegment(String... pathSegments);
/** Replace the entire path */
UriBuilder replacePath(String path);
/** Set the query string */
UriBuilder query(String query);
/** Replace the entire query string */
UriBuilder replaceQuery(String query);
/** Add query parameter with values */
UriBuilder queryParam(String name, Object... values);
/** Add query parameter with collection values */
UriBuilder queryParam(String name, Collection<?> values);
/** Add query parameter if Optional value is present */
UriBuilder queryParamIfPresent(String name, Optional<?> value);
/** Add multiple query parameters from map */
UriBuilder queryParams(MultiValueMap<String, String> params);
/** Replace existing query parameter */
UriBuilder replaceQueryParam(String name, Object... values);
/** Replace existing query parameter with collection */
UriBuilder replaceQueryParam(String name, Collection<?> values);
/** Replace all query parameters */
UriBuilder replaceQueryParams(MultiValueMap<String, String> params);
/** Set the URI fragment */
UriBuilder fragment(String fragment);
/** Build URI with positional variables */
URI build(Object... uriVariables);
/** Build URI with named variables */
URI build(Map<String, ?> uriVariables);
}
/**
* Builder for UriComponents with fluent API
*/
class UriComponentsBuilder implements UriBuilder, Cloneable {
/** Create new empty builder */
static UriComponentsBuilder newInstance();
/** Create builder from path */
static UriComponentsBuilder fromPath(String path);
/** Create builder from existing URI */
static UriComponentsBuilder fromUri(URI uri);
/** Create builder from URI string */
static UriComponentsBuilder fromUriString(String uri);
/** Create builder from HTTP URL string */
static UriComponentsBuilder fromHttpUrl(String httpUrl);
/** Create builder from HTTP request */
static UriComponentsBuilder fromHttpRequest(HttpRequest request);
/** Build UriComponents instance */
UriComponents build();
/** Build with encoding flag */
UriComponents build(boolean encoded);
/** Build and expand with positional variables */
UriComponents buildAndExpand(Object... uriVariableValues);
/** Build and expand with named variables */
UriComponents buildAndExpand(Map<String, ?> uriVariables);
/** Convert to URI string directly */
String toUriString();
}
/**
* Immutable collection of URI components
*/
abstract class UriComponents {
/** Get the scheme (protocol) */
String getScheme();
/** Get the fragment identifier */
String getFragment();
/** Get scheme-specific part */
String getSchemeSpecificPart();
/** Get user information */
String getUserInfo();
/** Get host name */
String getHost();
/** Get port number */
int getPort();
/** Get path */
String getPath();
/** Get path segments as list */
List<String> getPathSegments();
/** Get query string */
String getQuery();
/** Get query parameters as map */
MultiValueMap<String, String> getQueryParams();
/** Encode all URI components */
UriComponents encode();
/** Encode with specific charset */
UriComponents encode(Charset charset);
/** Expand template variables with positional args */
UriComponents expand(Object... uriVariableValues);
/** Expand template variables with named args */
UriComponents expand(Map<String, ?> uriVariables);
/** Normalize the URI (remove redundant segments) */
UriComponents normalize();
/** Convert to java.net.URI */
URI toUri();
/** Convert to URI string */
String toUriString();
}Usage Examples:
import org.springframework.web.util.UriComponentsBuilder;
// Basic URI building
URI uri = UriComponentsBuilder
.fromHttpUrl("https://api.example.com")
.path("/users/{id}")
.queryParam("include", "profile", "settings")
.buildAndExpand(123)
.toUri();
// Result: https://api.example.com/users/123?include=profile&include=settings
// Query parameter building
String url = UriComponentsBuilder
.fromPath("/search")
.queryParam("q", "spring framework")
.queryParam("page", 1)
.queryParam("size", 20)
.toUriString();
// Result: /search?q=spring+framework&page=1&size=20Utility methods for safely escaping HTML content and JavaScript strings to prevent XSS attacks.
/**
* Utility class for HTML escaping and unescaping
*/
class HtmlUtils {
/** Escape HTML characters using HTML entities */
static String htmlEscape(String input);
/** Escape HTML characters with specific encoding */
static String htmlEscape(String input, String encoding);
/** Escape HTML characters using decimal entities */
static String htmlEscapeDecimal(String input);
/** Escape HTML characters using decimal entities with encoding */
static String htmlEscapeDecimal(String input, String encoding);
/** Escape HTML characters using hexadecimal entities */
static String htmlEscapeHex(String input);
/** Escape HTML characters using hexadecimal entities with encoding */
static String htmlEscapeHex(String input, String encoding);
/** Unescape HTML entities back to characters */
static String htmlUnescape(String input);
}
/**
* Utility class for JavaScript escaping
*/
class JavaScriptUtils {
/** Escape JavaScript special characters */
static String javaScriptEscape(String input);
}Usage Examples:
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;
// HTML escaping
String userInput = "<script>alert('xss')</script>";
String safe = HtmlUtils.htmlEscape(userInput);
// Result: "<script>alert('xss')</script>"
// JavaScript escaping
String jsString = "Don't break \"my\" JavaScript!";
String escaped = JavaScriptUtils.javaScriptEscape(jsString);
// Result: "Don\\'t break \\\"my\\\" JavaScript!"Advanced pattern matching for URI paths with support for wildcards, path variables, and flexible matching options.
/**
* Representation of a parsed path pattern for matching against paths
*/
class PathPattern implements Comparable<PathPattern> {
/** Get the original pattern string */
String getPatternString();
/** Test if this pattern matches the given path */
boolean matches(PathContainer pathContainer);
/** Match and extract path variables */
PathPattern.PathMatchInfo matchAndExtract(PathContainer pathContainer);
/** Match start of path for partial matching */
PathPattern.PathRemainingMatchInfo matchStartOfPath(PathContainer pathContainer);
/** Combine this pattern with another */
PathPattern combine(PathPattern pattern2);
/** Compare patterns for specificity ordering */
int compareTo(PathPattern otherPattern);
/** Path match information with extracted variables */
class PathMatchInfo {
/** Get extracted URI template variables */
Map<String, String> getUriVariables();
/** Get the matched path portion */
PathContainer getMatchedPath();
}
/** Partial path match information */
class PathRemainingMatchInfo extends PathMatchInfo {
/** Get the remaining unmatched path portion */
PathContainer getRemainingPath();
}
}
/**
* Parser for URI path patterns into PathPattern instances
*/
class PathPatternParser {
PathPatternParser();
/** Configure matching of optional trailing separator */
void setMatchOptionalTrailingSeparator(boolean matchOptionalTrailingSeparator);
boolean isMatchOptionalTrailingSeparator();
/** Configure case sensitivity */
void setCaseSensitive(boolean caseSensitive);
boolean isCaseSensitive();
/** Parse a path pattern string */
PathPattern parse(String pathPattern);
}
/**
* Structured representation of a URI path
*/
interface PathContainer {
/** Get the full path as string */
String value();
/** Get path elements */
List<Element> elements();
/** Extract subpath from index */
PathContainer subPath(int index);
/** Extract subpath from range */
PathContainer subPath(int fromIndex, int toIndex);
/** Parse path string into PathContainer */
static PathContainer parsePath(String path);
/** Individual path element */
interface Element {
String value();
}
/** Path separator element */
interface Separator extends Element {
}
/** Path segment element */
interface PathSegment extends Element {
String valueToMatch();
char[] valueToMatchAsChars();
Map<String, String> parameters();
}
}Usage Examples:
import org.springframework.web.util.pattern.*;
// Pattern parsing and matching
PathPatternParser parser = new PathPatternParser();
PathPattern pattern = parser.parse("/api/users/{id}/posts/{postId}");
PathContainer path = PathContainer.parsePath("/api/users/123/posts/456");
boolean matches = pattern.matches(path);
// Result: true
PathPattern.PathMatchInfo matchInfo = pattern.matchAndExtract(path);
Map<String, String> variables = matchInfo.getUriVariables();
// Result: {id=123, postId=456}Declarative HTTP service client abstractions for creating type-safe API clients from annotated interfaces.
/**
* Factory to create client proxies from HTTP service interfaces
*/
class HttpServiceProxyFactory {
/** Create builder for configuring the factory */
static HttpServiceProxyFactory.Builder builder();
/** Create builder with WebClient */
static HttpServiceProxyFactory.Builder builderFor(WebClient webClient);
/** Create builder with RestTemplate */
static HttpServiceProxyFactory.Builder builderFor(RestTemplate restTemplate);
/** Create builder with RestClient */
static HttpServiceProxyFactory.Builder builderFor(RestClient restClient);
/** Create client proxy for service interface */
<S> S createClient(Class<S> serviceType);
/** Builder for HttpServiceProxyFactory */
interface Builder {
Builder customArgumentResolver(HttpServiceArgumentResolver argumentResolver);
Builder embeddedValueResolver(StringValueResolver embeddedValueResolver);
Builder conversionService(ConversionService conversionService);
HttpServiceProxyFactory build();
}
}
/**
* Declares an HTTP service interface method as an HTTP endpoint
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface HttpExchange {
/** URL for the request */
String value() default "";
/** Alias for value */
String url() default "";
/** HTTP method for the request */
String method() default "";
/** Content-Type header value */
String contentType() default "";
/** Accept header values */
String[] accept() default {};
}
/**
* Shortcut annotations for specific HTTP methods
*/
@HttpExchange(method = "GET")
@interface GetExchange {
String value() default "";
String url() default "";
}
@HttpExchange(method = "POST")
@interface PostExchange {
String value() default "";
String url() default "";
}
@HttpExchange(method = "PUT")
@interface PutExchange {
String value() default "";
String url() default "";
}
@HttpExchange(method = "DELETE")
@interface DeleteExchange {
String value() default "";
String url() default "";
}
@HttpExchange(method = "PATCH")
@interface PatchExchange {
String value() default "";
String url() default "";
}Usage Examples:
import org.springframework.web.service.annotation.*;
// Define HTTP service interface
@HttpExchange(url = "/api/users")
interface UserService {
@GetExchange
List<User> getAllUsers();
@GetExchange("/{id}")
User getUser(@PathVariable Long id);
@PostExchange
User createUser(@RequestBody User user);
@PutExchange("/{id}")
User updateUser(@PathVariable Long id, @RequestBody User user);
@DeleteExchange("/{id}")
void deleteUser(@PathVariable Long id);
}
// Create client proxy
RestClient restClient = RestClient.create("https://api.example.com");
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(restClient).build();
UserService userService = factory.createClient(UserService.class);
// Use the client
List<User> users = userService.getAllUsers();
User user = userService.getUser(123L);General-purpose utility methods for common web application tasks including servlet operations and parameter handling.
/**
* Miscellaneous utilities for web applications
*/
class WebUtils {
/** Get the real filesystem path for a web application path */
static String getRealPath(ServletContext servletContext, String path);
/** Get temporary directory for the web application */
static File getTempDir(ServletContext servletContext);
/** Get session attribute value */
static Object getSessionAttribute(HttpServletRequest request, String name);
/** Get required session attribute (throws exception if missing) */
static Object getRequiredSessionAttribute(HttpServletRequest request, String name);
/** Set session attribute */
static void setSessionAttribute(HttpServletRequest request, String name, Object value);
/** Get or create session attribute with class instantiation */
static Object getOrCreateSessionAttribute(HttpSession session, String name, Class<?> clazz);
/** Find parameter value in request */
static String findParameterValue(ServletRequest request, String name);
/** Get parameters starting with prefix as map */
static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix);
/** Get cookie by name */
static Cookie getCookie(HttpServletRequest request, String name);
/** Check if request has submit parameter */
static boolean hasSubmitParameter(ServletRequest request, String name);
/** Get submit parameter value */
static String getSubmitParameter(ServletRequest request, String name);
}Cross-Origin Resource Sharing (CORS) configuration and processing for handling cross-domain requests.
/**
* CORS configuration for cross-origin requests
*/
class CorsConfiguration {
CorsConfiguration();
/** Set allowed origins */
void setAllowedOrigins(List<String> allowedOrigins);
List<String> getAllowedOrigins();
/** Add allowed origin */
void addAllowedOrigin(String origin);
/** Set allowed origin patterns */
void setAllowedOriginPatterns(List<String> allowedOriginPatterns);
List<String> getAllowedOriginPatterns();
/** Add allowed origin pattern */
void addAllowedOriginPattern(String originPattern);
/** Set allowed HTTP methods */
void setAllowedMethods(List<String> allowedMethods);
List<String> getAllowedMethods();
/** Add allowed method */
void addAllowedMethod(HttpMethod method);
/** Set allowed headers */
void setAllowedHeaders(List<String> allowedHeaders);
List<String> getAllowedHeaders();
/** Add allowed header */
void addAllowedHeader(String allowedHeader);
/** Set exposed headers */
void setExposedHeaders(List<String> exposedHeaders);
List<String> getExposedHeaders();
/** Add exposed header */
void addExposedHeader(String exposedHeader);
/** Set allow credentials flag */
void setAllowCredentials(Boolean allowCredentials);
Boolean getAllowCredentials();
/** Set max age for preflight cache */
void setMaxAge(Long maxAge);
Long getMaxAge();
/** Check if origin is allowed */
String checkOrigin(String requestOrigin);
/** Check if HTTP method is allowed */
List<HttpMethod> checkHttpMethod(HttpMethod requestMethod);
/** Check if headers are allowed */
List<String> checkHeaders(List<String> requestHeaders);
}
/**
* CORS processor for handling CORS requests
*/
class CorsProcessor {
/** Process CORS request with configuration */
boolean processRequest(CorsConfiguration config, ServerHttpRequest request, ServerHttpResponse response);
}Content type negotiation and cache control utilities for optimizing HTTP responses.
/**
* Builder for Cache-Control HTTP header values
*/
class CacheControl {
/** Create empty cache control */
static CacheControl empty();
/** Create with max-age directive */
static CacheControl maxAge(Duration maxAge);
/** Create no-cache directive */
static CacheControl noCache();
/** Create no-store directive */
static CacheControl noStore();
/** Add must-revalidate directive */
CacheControl mustRevalidate();
/** Add no-transform directive */
CacheControl noTransform();
/** Add public directive */
CacheControl cachePublic();
/** Add private directive */
CacheControl cachePrivate();
/** Add s-maxage directive */
CacheControl sMaxAge(Duration sMaxAge);
/** Add stale-while-revalidate directive */
CacheControl staleWhileRevalidate(Duration staleWhileRevalidate);
/** Add stale-if-error directive */
CacheControl staleIfError(Duration staleIfError);
/** Get the header value string */
String getHeaderValue();
}
/**
* Represents Content-Disposition header value
*/
class ContentDisposition {
/** Check if disposition type is attachment */
boolean isAttachment();
/** Check if disposition type is form-data */
boolean isFormData();
/** Check if disposition type is inline */
boolean isInline();
/** Get disposition type */
String getType();
/** Get name parameter */
String getName();
/** Get filename parameter */
String getFilename();
/** Get charset parameter */
Charset getCharset();
/** Get creation date parameter */
ZonedDateTime getCreationDate();
/** Get modification date parameter */
ZonedDateTime getModificationDate();
/** Get read date parameter */
ZonedDateTime getReadDate();
/** Get size parameter */
Long getSize();
/** Create builder for attachment disposition */
static ContentDisposition.Builder attachment();
/** Create builder for form-data disposition */
static ContentDisposition.Builder formData();
/** Create builder for inline disposition */
static ContentDisposition.Builder inline();
/** Builder for ContentDisposition */
interface Builder {
Builder name(String name);
Builder filename(String filename);
Builder filename(String filename, Charset charset);
Builder size(Long size);
Builder creationDate(ZonedDateTime creationDate);
Builder modificationDate(ZonedDateTime modificationDate);
Builder readDate(ZonedDateTime readDate);
ContentDisposition build();
}
}
/**
* RFC 7807 Problem Detail for HTTP APIs
*/
class ProblemDetail {
ProblemDetail(int status);
/** Get problem type URI */
URI getType();
void setType(URI type);
/** Get human-readable title */
String getTitle();
void setTitle(String title);
/** Get HTTP status code */
int getStatus();
/** Get detailed explanation */
String getDetail();
void setDetail(String detail);
/** Get problem instance URI */
URI getInstance();
void setInstance(URI instance);
/** Get additional properties */
Map<String, Object> getProperties();
void setProperty(String name, Object value);
Object getProperty(String name);
/** Factory method for status code */
static ProblemDetail forStatus(HttpStatusCode status);
/** Factory method for status and detail */
static ProblemDetail forStatusAndDetail(HttpStatusCode status, String detail);
}Usage Examples:
import org.springframework.http.CacheControl;
import org.springframework.http.ContentDisposition;
import org.springframework.http.ProblemDetail;
// Cache control
CacheControl cacheControl = CacheControl
.maxAge(Duration.ofHours(1))
.mustRevalidate()
.cachePublic();
String headerValue = cacheControl.getHeaderValue();
// Result: "max-age=3600, must-revalidate, public"
// Content disposition for file downloads
ContentDisposition disposition = ContentDisposition
.attachment()
.filename("report.pdf")
.build();
// Problem detail for error responses
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"Invalid user input"
);
problem.setTitle("Validation Error");
problem.setProperty("field", "email");Install with Tessl CLI
npx tessl i tessl/maven-org-springframework--spring-web