or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

api-versioning.mdasync.mdconfiguration.mdcontent-negotiation.mdcontroller-annotations.mdcore-framework.mdcors.mddata-binding.mdexception-handling.mdflash-attributes.mdfunctional-endpoints.mdi18n.mdindex.mdinterceptors.mdmultipart.mdrequest-binding.mdresource-handling.mdresponse-handling.mduri-building.mdview-resolution.md
tile.json

content-negotiation.mddocs/

Content Negotiation

Content negotiation for determining the best representation format (JSON, XML, HTML, etc.) based on request headers, parameters, or file extensions.

Capabilities

ContentNegotiationManager

Central class for content negotiation that delegates to ContentNegotiationStrategy implementations.

/**
 * Central class to determine requested media types for a request. This is done by
 * delegating to a list of configured ContentNegotiationStrategy instances.
 */
public class ContentNegotiationManager implements ContentNegotiationStrategy {
    /**
     * Create an instance with the given ContentNegotiationStrategy instances.
     *
     * @param strategies the strategies to use
     */
    public ContentNegotiationManager(ContentNegotiationStrategy... strategies) {}

    /**
     * Create an instance with the given ContentNegotiationStrategy instances.
     *
     * @param strategies the strategies to use
     */
    public ContentNegotiationManager(Collection<ContentNegotiationStrategy> strategies) {}

    /**
     * Return the configured ContentNegotiationStrategy instances.
     *
     * @return the strategies
     */
    public List<ContentNegotiationStrategy> getStrategies() {}

    /**
     * Resolve the given request to a list of media types. The returned list is
     * ordered by specificity first and by quality parameter second.
     *
     * @param webRequest the current request
     * @return the list of requested media types
     * @throws HttpMediaTypeNotAcceptableException if no acceptable media type is found
     */
    @Override
    public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest)
            throws HttpMediaTypeNotAcceptableException {}
}

ContentNegotiationStrategy

Strategy for resolving the requested media types for a request.

/**
 * A strategy for resolving the requested media types for a request.
 */
@FunctionalInterface
public interface ContentNegotiationStrategy {
    /**
     * A singleton list with MediaType.ALL that is returned when no specific
     * media types are requested.
     */
    List<MediaType> MEDIA_TYPE_ALL_LIST = Collections.singletonList(MediaType.ALL);

    /**
     * Resolve the given request to a list of media types.
     * The returned list is ordered by specificity first and by quality parameter second.
     *
     * @param webRequest the current request
     * @return the requested media types, or an empty list if none requested
     * @throws HttpMediaTypeNotAcceptableException if no acceptable media type can be found
     */
    List<MediaType> resolveMediaTypes(NativeWebRequest webRequest)
            throws HttpMediaTypeNotAcceptableException;
}

ContentNegotiationConfigurer

Configuration builder for content negotiation.

/**
 * Creates a ContentNegotiationManager and configures it with one or more
 * ContentNegotiationStrategy instances.
 */
public class ContentNegotiationConfigurer {
    /**
     * Whether a request parameter ("format" by default) should be used to determine
     * the requested media type. Default is false.
     *
     * @param favorParameter whether to enable parameter-based content negotiation
     * @return this configurer for chaining
     */
    public ContentNegotiationConfigurer favorParameter(boolean favorParameter) {}

    /**
     * Set the query parameter name to use when favorParameter is on.
     * Default is "format".
     *
     * @param parameterName the parameter name
     * @return this configurer for chaining
     */
    public ContentNegotiationConfigurer parameterName(String parameterName) {}

    /**
     * Whether to disable checking the Accept request header. Default is false.
     *
     * @param ignoreAcceptHeader whether to ignore the Accept header
     * @return this configurer for chaining
     */
    public ContentNegotiationConfigurer ignoreAcceptHeader(boolean ignoreAcceptHeader) {}

    /**
     * Set the default content type(s) to use when no content type is requested.
     *
     * @param defaultContentTypes one or more default content types
     * @return this configurer for chaining
     */
    public ContentNegotiationConfigurer defaultContentType(MediaType... defaultContentTypes) {}

    /**
     * Set the default content type to use when no content type is requested
     * and the Accept header is set to '*/*'.
     *
     * @param defaultContentType the default content type
     * @return this configurer for chaining
     */
    public ContentNegotiationConfigurer defaultContentTypeStrategy(
            ContentNegotiationStrategy defaultContentType) {}

    /**
     * Add a mapping from a file extension to a media type.
     *
     * @param extension the file extension (no leading dot)
     * @param mediaType the media type
     * @return this configurer for chaining
     */
    public ContentNegotiationConfigurer mediaType(String extension, MediaType mediaType) {}

    /**
     * Add mappings from file extensions to media types.
     *
     * @param mediaTypes the mappings
     * @return this configurer for chaining
     */
    public ContentNegotiationConfigurer mediaTypes(Map<String, MediaType> mediaTypes) {}

    /**
     * When favorParameter is enabled, this property determines whether to use
     * only registered media type mappings to resolve the requested media type.
     * Default is false.
     *
     * @param useOnly whether to use only registered media types
     * @return this configurer for chaining
     */
    public ContentNegotiationConfigurer useRegisteredExtensionsOnly(boolean useOnly) {}
}

Usage Example:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
            // Enable parameter-based negotiation
            .favorParameter(true)
            .parameterName("mediaType")
            // Don't ignore Accept header
            .ignoreAcceptHeader(false)
            // Set default content type
            .defaultContentType(MediaType.APPLICATION_JSON)
            // Register media type mappings
            .mediaType("json", MediaType.APPLICATION_JSON)
            .mediaType("xml", MediaType.APPLICATION_XML)
            .mediaType("html", MediaType.TEXT_HTML);
    }
}

// Controller supporting multiple content types
@RestController
@RequestMapping("/api/products")
public class ProductController {

    @GetMapping(value = "/{id}", produces = {
        MediaType.APPLICATION_JSON_VALUE,
        MediaType.APPLICATION_XML_VALUE
    })
    public Product getProduct(@PathVariable Long id) {
        return productService.findById(id);
    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Product> getProductsJson() {
        return productService.findAll();
    }

    @GetMapping(produces = MediaType.APPLICATION_XML_VALUE)
    public List<Product> getProductsXml() {
        return productService.findAll();
    }
}

Types

MediaType

Represents an HTTP media type.

public class MediaType implements Comparable<MediaType> {
    public static final MediaType ALL = new MediaType("*", "*");
    public static final MediaType APPLICATION_JSON = new MediaType("application", "json");
    public static final MediaType APPLICATION_XML = new MediaType("application", "xml");
    public static final MediaType TEXT_HTML = new MediaType("text", "html");
    public static final MediaType TEXT_PLAIN = new MediaType("text", "plain");
    public static final MediaType MULTIPART_FORM_DATA = new MediaType("multipart", "form-data");

    public String getType() {}
    public String getSubtype() {}
    public Map<String, String> getParameters() {}
    public boolean isWildcardType() {}
    public boolean isWildcardSubtype() {}
    public boolean isCompatibleWith(MediaType other) {}
    public boolean includes(MediaType other) {}
}