spring-requesturi-locale-interceptor

Handling Locale as first part of RequestURI in Spring MVC

Stars
1
Committers
1

RequestURI Locale Interceptor for Spring

Handling Locale as first part of RequestURI.

Example:

HTTP Request                                 RequestURI

https://foo.bar/{locale}/some/path.html  ->  /{locale}/some/path.html
https://foo.bar/{locale}/a.html          ->  /{locale}/a.html
https://foo.bar/{locale}/xyz?a=b         ->  /{locale}/xyz

An example in action can be seen here.

Versions

Version Description
0.3.0 Release notes
0.2.0 Release notes / Breaking Change
0.1.0 Release notes

Dependency

Maven

<dependency>
    <groupId>io.github.alaugks</groupId>
    <artifactId>spring-requesturi-locale-interceptor</artifactId>
    <version>0.3.0</version>
</dependency>

Gradle

implementation group: 'io.github.alaugks', name: 'spring-requesturi-locale-interceptor', version: '0.3.0'

Configuration

Options

Spring Configuration

import io.github.alaugks.spring.requesturilocaleinterceptor.RequestURILocaleInterceptor;
import io.github.alaugks.spring.requesturilocaleinterceptor.RequestURILocaleResolver;
import java.util.List;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfigurerConfig implements WebMvcConfigurer {

    private final Locale defaultLocale = Locale.forLanguageTag("en");

    private final List<Locale> supportedLocales = List.of(
        Locale.forLanguageTag("en"),
        Locale.forLanguageTag("de"),
        Locale.forLanguageTag("en-US")
    );

    @Bean
    public LocaleResolver localeResolver() {
        RequestURILocaleResolver resolver = new RequestURILocaleResolver();
        resolver.setDefaultLocale(this.defaultLocale);
        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        RequestURILocaleInterceptor interceptor = RequestURILocaleInterceptor
            .builder(this.defaultLocale)
            .supportedLocales(this.supportedLocales)
            .defaultRequestURI("/en/home")
            .build();
        
        registry.addInterceptor(urlInterceptor)
            .addPathPatterns("/**")
            // Exclude from Interceptor
            .excludePathPatterns("/static/**", "/error");
    }
}
Badges
Extracted from project README
Quality Gate Status Maven Central
Related Projects