CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-springframework-boot--spring-boot-autoconfigure

Spring Boot AutoConfigure provides auto-configuration capabilities that automatically configure Spring applications based on jar dependencies present on the classpath

Pending
Overview
Eval results
Files

web-configuration.mddocs/reference/

Web Configuration

Spring Boot AutoConfigure provides configuration properties for web applications including error handling, resource management, locale resolution, and web resource hints.

Imports

import org.springframework.boot.autoconfigure.web.*;
import org.springframework.boot.autoconfigure.web.format.*;

Error Handling

ErrorProperties

Configuration properties for web error handling and error page customization.

@ConfigurationProperties(prefix = "server.error")
public class ErrorProperties {
    /**
     * Path of the error controller.
     * Default is "/error".
     */
    public String getPath();
    public void setPath(String path);

    /**
     * Include the "exception" attribute in the error response.
     * Default is false.
     */
    public boolean isIncludeException();
    public void setIncludeException(boolean includeException);

    /**
     * When to include the "stacktrace" attribute in the error response.
     */
    public IncludeAttribute getIncludeStacktrace();
    public void setIncludeStacktrace(IncludeAttribute includeStacktrace);

    /**
     * When to include the "message" attribute in the error response.
     */
    public IncludeAttribute getIncludeMessage();
    public void setIncludeMessage(IncludeAttribute includeMessage);

    /**
     * When to include the "errors" attribute (binding errors) in the error response.
     */
    public IncludeAttribute getIncludeBindingErrors();
    public void setIncludeBindingErrors(IncludeAttribute includeBindingErrors);

    /**
     * When to include the "path" attribute in the error response.
     */
    public IncludeAttribute getIncludePath();
    public void setIncludePath(IncludeAttribute includePath);

    /**
     * Get whitelabel error page configuration.
     */
    public Whitelabel getWhitelabel();

    public static class Whitelabel {
        /**
         * Whether to enable the default error page.
         * Default is true.
         */
        public boolean isEnabled();
        public void setEnabled(boolean enabled);
    }

    /**
     * Enum for controlling when attributes are included in error responses.
     */
    public enum IncludeAttribute {
        NEVER,      // Never include the attribute
        ALWAYS,     // Always include the attribute
        ON_PARAM    // Include only when request parameter is present
    }
}

Web Resources

WebProperties

Configuration properties for general web concerns including resource handling and locale resolution.

@ConfigurationProperties("spring.web")
public class WebProperties {
    /**
     * Get the fixed locale.
     * Null means use Accept-Language header.
     */
    public Locale getLocale();

    /**
     * Set the fixed locale.
     * Null means use Accept-Language header.
     */
    public void setLocale(Locale locale);

    /**
     * Get the locale resolver strategy.
     */
    public LocaleResolver getLocaleResolver();
    public void setLocaleResolver(LocaleResolver localeResolver);

    /**
     * Get error handling configuration.
     */
    public ErrorProperties getError();

    /**
     * Get resource handling configuration.
     */
    public Resources getResources();

    /**
     * Resource handling configuration.
     */
    public static class Resources {
        /**
         * Get static resource locations.
         * Default includes classpath:/META-INF/resources/,
         * classpath:/resources/, classpath:/static/, classpath:/public/
         */
        public String[] getStaticLocations();
        public void setStaticLocations(String[] staticLocations);

        /**
         * Whether to enable default resource handling.
         * Default is true.
         */
        public boolean isAddMappings();
        public void setAddMappings(boolean addMappings);

        /**
         * Get resource chain configuration.
         */
        public Chain getChain();

        /**
         * Get cache configuration.
         */
        public Cache getCache();

        /**
         * Check if the resource locations have been customized.
         */
        public boolean hasBeenCustomized();

        public static class Chain {
            /**
             * Get whether resource chain is enabled.
             */
            public Boolean getEnabled();

            /**
             * Whether to enable resource chain.
             * Can be auto-enabled if certain dependencies are present.
             */
            public void setEnabled(Boolean enabled);

            /**
             * Whether to enable caching for the resource chain.
             * Default is true.
             */
            public boolean isCache();
            public void setCache(boolean cache);

            /**
             * Get resource chain strategy configuration.
             */
            public Strategy getStrategy();

            /**
             * Whether to compress resources.
             */
            public boolean isCompressed();
            public void setCompressed(boolean compressed);
        }

        /**
         * Resource chain strategy configuration.
         */
        public static class Strategy {
            /**
             * Get fixed version strategy configuration.
             */
            public Fixed getFixed();

            /**
             * Get content-based version strategy configuration.
             */
            public Content getContent();
        }

        /**
         * Content-based versioning strategy.
         */
        public static class Content {
            /**
             * Whether to enable content-based versioning.
             */
            public boolean isEnabled();
            public void setEnabled(boolean enabled);

            /**
             * Patterns for resources to apply content-based versioning.
             */
            public String[] getPaths();
            public void setPaths(String[] paths);
        }

        /**
         * Fixed version strategy.
         */
        public static class Fixed {
            /**
             * Whether to enable fixed versioning.
             */
            public boolean isEnabled();
            public void setEnabled(boolean enabled);

            /**
             * Patterns for resources to apply fixed versioning.
             */
            public String[] getPaths();
            public void setPaths(String[] paths);

            /**
             * Version string to use for fixed versioning.
             */
            public String getVersion();
            public void setVersion(String version);
        }

        public static class Cache {
            /**
             * Cache period for resources.
             */
            public Duration getPeriod();
            public void setPeriod(Duration period);

            /**
             * Cache control HTTP header settings.
             */
            public Cachecontrol getCachecontrol();

            /**
             * Whether to use last modified header for caching.
             * Default is true.
             */
            public boolean isUseLastModified();
            public void setUseLastModified(boolean useLastModified);
        }

        /**
         * Cache-Control HTTP header configuration.
         */
        public static class Cachecontrol {
            /**
             * Maximum time a response can be cached (max-age directive).
             */
            public Duration getMaxAge();
            public void setMaxAge(Duration maxAge);

            /**
             * Indicate that the cached response can be reused only if there is no
             * fresh response from the origin server (no-cache directive).
             */
            public Boolean getNoCache();
            public void setNoCache(Boolean noCache);

            /**
             * Indicate that the response must not be stored (no-store directive).
             */
            public Boolean getNoStore();
            public void setNoStore(Boolean noStore);

            /**
             * Indicate that once the response becomes stale, it must be revalidated (must-revalidate directive).
             */
            public Boolean getMustRevalidate();
            public void setMustRevalidate(Boolean mustRevalidate);

            /**
             * Indicate that transformations should not be applied (no-transform directive).
             */
            public Boolean getNoTransform();
            public void setNoTransform(Boolean noTransform);

            /**
             * Indicate that the response is cacheable by any cache (public directive).
             */
            public Boolean getCachePublic();
            public void setCachePublic(Boolean cachePublic);

            /**
             * Indicate that the response is intended for a single user (private directive).
             */
            public Boolean getCachePrivate();
            public void setCachePrivate(Boolean cachePrivate);

            /**
             * Indicate that once the response becomes stale, a shared cache must revalidate (proxy-revalidate directive).
             */
            public Boolean getProxyRevalidate();
            public void setProxyRevalidate(Boolean proxyRevalidate);

            /**
             * Maximum time a stale response can be used while revalidating (stale-while-revalidate directive).
             */
            public Duration getStaleWhileRevalidate();
            public void setStaleWhileRevalidate(Duration staleWhileRevalidate);

            /**
             * Maximum time a stale response can be used when errors occur (stale-if-error directive).
             */
            public Duration getStaleIfError();
            public void setStaleIfError(Duration staleIfError);

            /**
             * Maximum time a shared cache can store the response (s-maxage directive).
             */
            public Duration getSMaxAge();
            public void setSMaxAge(Duration sMaxAge);

            /**
             * Convert this configuration to Spring's CacheControl object.
             */
            public org.springframework.http.CacheControl toHttpCacheControl();
        }
    }

    /**
     * Locale resolver strategies.
     */
    public enum LocaleResolver {
        FIXED,           // Use fixed locale
        ACCEPT_HEADER    // Use Accept-Language header
    }
}

ConditionalOnEnabledResourceChain

Conditional annotation that checks whether the Spring resource handling chain is enabled.

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnEnabledResourceChainCondition.class)
public @interface ConditionalOnEnabledResourceChain {
}

WebResourcesRuntimeHints

RuntimeHintsRegistrar for default locations of web resources, used with GraalVM native images.

public class WebResourcesRuntimeHints implements RuntimeHintsRegistrar {
    /**
     * Register runtime hints for web resources.
     */
    @Override
    public void registerHints(RuntimeHints hints, ClassLoader classLoader);
}

Web Formatting

DateTimeFormatters

Formatters for dates, times, and date-times with customizable patterns.

public class DateTimeFormatters {
    /**
     * Create formatters with default patterns.
     */
    public DateTimeFormatters();

    /**
     * Create new formatters with custom date format pattern.
     *
     * @param pattern the date format pattern or null for ISO format
     * @return new DateTimeFormatters instance
     */
    public DateTimeFormatters dateFormat(String pattern);

    /**
     * Create new formatters with custom time format pattern.
     *
     * @param pattern the time format pattern or null for ISO format
     * @return new DateTimeFormatters instance
     */
    public DateTimeFormatters timeFormat(String pattern);

    /**
     * Create new formatters with custom date-time format pattern.
     *
     * @param pattern the date-time format pattern or null for ISO format
     * @return new DateTimeFormatters instance
     */
    public DateTimeFormatters dateTimeFormat(String pattern);
}

WebConversionService

FormattingConversionService dedicated to web applications for formatting and converting values to/from the web.

public class WebConversionService extends DefaultFormattingConversionService {
    /**
     * Create a new WebConversionService with custom date/time formatters.
     *
     * @param dateTimeFormatters the date/time formatters to use
     */
    public WebConversionService(DateTimeFormatters dateTimeFormatters);
}

Configuration Examples

Error Handling Configuration

server:
  error:
    path: /error
    include-exception: false
    include-stacktrace: never  # or 'always', 'on_param'
    include-message: always
    include-binding-errors: always
    include-path: on_param
    whitelabel:
      enabled: true

Resource Handling Configuration

spring:
  web:
    resources:
      static-locations:
        - classpath:/static/
        - classpath:/public/
        - file:/var/www/
      add-mappings: true
      cache:
        period: 1h
        cachecontrol:
          max-age: 3600
          must-revalidate: true
      chain:
        enabled: true
        cache: true

Locale Configuration

spring:
  web:
    locale: en_US
    locale-resolver: fixed  # or 'accept-header'

Usage Examples

Custom Error Controller

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class CustomErrorController implements ErrorController {
    private final ErrorProperties errorProperties;

    public CustomErrorController(ErrorProperties errorProperties) {
        this.errorProperties = errorProperties;
    }

    @RequestMapping("${server.error.path:/error}")
    public String handleError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute(
            "jakarta.servlet.error.status_code"
        );

        if (statusCode == 404) {
            return "error/404";
        } else if (statusCode == 500) {
            return "error/500";
        }

        return "error/generic";
    }
}

Resource Handler Customization

import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebResourceConfiguration implements WebMvcConfigurer {
    private final WebProperties webProperties;

    public WebResourceConfiguration(WebProperties webProperties) {
        this.webProperties = webProperties;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (webProperties.getResources().isAddMappings()) {
            registry.addResourceHandler("/custom/**")
                .addResourceLocations("classpath:/custom-static/")
                .setCachePeriod(3600);
        }
    }
}

Date/Time Formatting

import org.springframework.boot.autoconfigure.web.format.DateTimeFormatters;
import org.springframework.boot.autoconfigure.web.format.WebConversionService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.support.FormattingConversionService;

@Configuration
public class FormattingConfiguration {

    @Bean
    public FormattingConversionService conversionService() {
        DateTimeFormatters formatters = new DateTimeFormatters()
            .dateFormat("yyyy-MM-dd")
            .timeFormat("HH:mm:ss")
            .dateTimeFormat("yyyy-MM-dd'T'HH:mm:ss");

        return new WebConversionService(formatters);
    }
}

Locale Resolution

import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import java.util.Locale;

@Configuration
public class LocaleConfiguration {
    private final WebProperties webProperties;

    public LocaleConfiguration(WebProperties webProperties) {
        this.webProperties = webProperties;
    }

    @Bean
    public LocaleResolver localeResolver() {
        if (webProperties.getLocaleResolver() ==
                WebProperties.LocaleResolver.FIXED) {
            SessionLocaleResolver resolver = new SessionLocaleResolver();
            resolver.setDefaultLocale(Locale.US);
            return resolver;
        } else {
            AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
            resolver.setDefaultLocale(Locale.US);
            return resolver;
        }
    }
}

Best Practices

  1. Error Handling: Use ON_PARAM for sensitive information in production
  2. Resource Caching: Enable caching in production for performance
  3. Static Locations: Order locations by lookup frequency
  4. Locale Resolution: Use ACCEPT_HEADER for international applications
  5. Error Pages: Provide custom error pages for common status codes
  6. Resource Chain: Enable for better performance with versioned resources

Install with Tessl CLI

npx tessl i tessl/maven-org-springframework-boot--spring-boot-autoconfigure@4.0.1

docs

index.md

tile.json