【发布时间】:2020-07-05 11:23:15
【问题描述】:
当我在 Postman 中输入以下 URL http://localhost:8080/hello-world-internationalized 时收到 400 bad request 如果我指定不需要的“Accept-Language”,情况并非如此 事实上我得到以下异常
2020-07-05 12:02:43.617 WARN 7744 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver:已解决 [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:无法转换键入“java.lang.String”到所需类型“java.util.Locale”;嵌套异常是 java.lang.IllegalArgumentException: Locale part "en-US,en;q=0.9" contains invalid characters]
这是我的控制器
package com.in28minutes.rest.webservices.restfulwebservices.helloworld;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@Autowired
private MessageSource messageSource;
@GetMapping(path ="/hello-world")
public String helloWorld() {
return "Hello World!";
}
@GetMapping(path ="/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World!");
}
@GetMapping(path ="/hello-world-bean/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello, %s", name));
}
@GetMapping(path ="/hello-world-internationalized")
public String helloWorldInternationalized(@RequestHeader(name = "Accept-Language", required = false) Locale locale) {
return messageSource.getMessage("good.morning.message", null, locale);
}
}
和
package com.in28minutes.rest.webservices.restfulwebservices;
import java.util.Locale;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
@SpringBootApplication
public class RestfulWebServicesApplication {
public static void main(String[] args) {
SpringApplication.run(RestfulWebServicesApplication.class, args);
}
@Bean
public LocaleResolver localeResolver() {
AcceptHeaderLocaleResolver localeResolver= new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(Locale.US);
return localeResolver;
}
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource= new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
我在选择 Spring Boot 2.1.15、Java、Maven 项目和 Web、DevTools、JPA 和 H2 等依赖项时使用 Spring Intializr 创建了项目。
【问题讨论】:
标签: spring spring-boot internationalization