|
FixedLocaleResolver always uses a default locale and, optionally, a default time zone. It doesn't allow changing either of them once set. In this tutorial we will focus only on the locale feature. We can set its fixed default locale at construction time. If none is set, the system locale is used.
public FixedLocaleResolver() {
setDefaultLocale(Locale.getDefault());
}
|
FixedLocaleResolver is usually needed when we want to turn off the default behavior of AcceptHeaderLocaleResolver, or when we want to switch an existing LocaleResolver to a fixed locale for some reason.
Let's see a quick example of how we can use it.
Example
Registering FixedLocaleResolver
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.i18n.FixedLocaleResolver;
import java.util.Locale;
@EnableWebMvc
@Configuration
@ComponentScan
public class WebConfig {
@Bean
LocaleResolver localeResolver() {
FixedLocaleResolver l = new FixedLocaleResolver();
l.setDefaultLocale(Locale.JAPAN);
return l;
}
}
The Controller
package com.logicbig.example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Locale;
@Controller
public class TheController {
@GetMapping("/")
@ResponseBody
public String handleRequest (Locale locale) {
return String.format("Request received. Locale: %s%n",
locale);
}
}
Running Example
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
Curl Output $ curl -s "http://localhost:8080/" Request received. Locale: ja_JP
Curl Output $ curl -s -H "Accept-Language: fr-FR" "http://localhost:8080/" Request received. Locale: ja_JP
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 3.2.9.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- spring-test 7.0.6 (Spring TestContext Framework)
- junit-jupiter-engine 6.0.3 (Module "junit-jupiter-engine" of JUnit)
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- hamcrest 3.0 (Core API and libraries of hamcrest matcher framework)
- JDK 25
- Maven 3.9.11
|