Spring MVC LocaleChangeInterceptor annotation based doesn't work - java

import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;
#Configuration
public class Config {
#Bean
public LocaleResolver localeResolver() {
final CookieLocaleResolver ret = new CookieLocaleResolver();
ret.setDefaultLocale(new Locale("en_US"));
return ret;
}
#Bean
public MessageSource messageSource() {
final ReloadableResourceBundleMessageSource ret = new ReloadableResourceBundleMessageSource();
ret.setBasename("classpath:lang");
ret.setDefaultEncoding("UTF-8");
return ret;
}
#Bean
public HandlerMapping handlerMapping() {
final LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("language");
final DefaultAnnotationHandlerMapping ret = new DefaultAnnotationHandlerMapping();
ret.setInterceptors(new Object[] { interceptor });
return ret;
}
}
The above is my annotation configuration. I've basically translated this tutorial's XML.
Strangely it doesn't work when I go to ...?language=fr.
However, the following does work (in app-servlet.xml) (notice here it's using locale):
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="locale" />
</bean>
</mvc:interceptors>
Another important thing to note is that when I put breakpoints on the above methods, all of the three of them, every breakpoint does break, which implies that "someone" is reading the values.
So, why wouldn't my annotation based interceptor doesn't work?

Extending config class by WebMvcConfigurerAdapter may help.
to add interceptor entry override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
method.
also add bean entry for LocaleChangeInterceptor
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}

In addition to what swap says, you need to add:
#Bean(name = "localeResolver")
public LocaleResolver getLocaleResolver(){
return new CookieLocaleResolver();
}
The bean name is important. That's the way spring will resolve the correct locale resolver.
Alternatively you can return the SessionLocaleResolver.
If you do not add this you will get the following error:
Cannot change HTTP accept header - use a different locale resolution strategy

The full example of Spring MVC 4.1.4.RELEASE localization is posted.
Also you can use MKYong's example (but unfortunately its config is based on XML) to solve the problems with project structure.
package com.pizza.config;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(value = "com.pizza")
public class WebConfig extends WebMvcConfigurerAdapter {
/* Resolvers and other MVC needs */
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
/* Localization section is started */
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}
#Bean(name = "localeResolver")
public LocaleResolver getLocaleResolver(){
return new CookieLocaleResolver();
}
#Bean
public MessageSource messageSource() {
final ReloadableResourceBundleMessageSource ret = new ReloadableResourceBundleMessageSource();
ret.setBasename("classpath:languages");
ret.setDefaultEncoding("UTF-8");
return ret;
}
}

Related

The problem with Internationalization in Spring Boot do not work in Configuration file

I'm currently working on a Web-App using Spring boot (including spring security). At the moment i'm trying to integrate internationalization support for the defult language russian as a start.
This is a configuration file where I write to get messages in the Russian language, if the user writed wrong data or e.t but this code returns me In English
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
#Configuration
public class ConfigForAuth {
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(new Locale("ru"));
return slr;
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource rs = new ReloadableResourceBundleMessageSource();
rs.addBasenames("classpath:i18n/messages");
rs.addBasenames("classpath:/org/springframework/security/messages_ru.properties:1");
rs.setDefaultEncoding("UTF-8");
rs.setUseCodeAsDefaultMessage(true);
return rs;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("locale");
return localeChangeInterceptor;
}
}
But if I will write this same code in Application file this code works fine and returns to me in RU
Application file:
#SpringBootApplication
#ComponentScan("--.--.--")//conf
#EnableCaching
#PropertySources({
#PropertySource("classpath:application.properties"),
#PropertySource("classpath:clients.properties")
})
public class OneBpmAuthApiApplication {
public static void main(String[] args) {
SpringApplication.run(OneBpmAuthApiApplication.class, args);
}
I think previous advice was more or less right just you need to set ParamName to "lang" like so:
#Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new
LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
also please do remember to extend WebMvcConfigurer.
Try extending from WebMvcConfigurerAdapter and adding the interceptors.
#Configuration
public class ConfigForAuth extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}

Exception while creating TileConfigurer Bean SpringMvc

We are using spring mvc with java configuration.
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesView;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
#Configuration
#EnableWebMvc
#EnableAspectJAutoProxy
#ComponentScan(basePackages = {"com.anonymous"})
public class WebConfig extends WebMvcConfigurerAdapter {
#Value("${webCachePeriod}")
private int cachePeriod;
#Value("${maxUploadSize}")
private long maxUploadSize;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app/**").addResourceLocations("/app/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(cachePeriod);
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(cachePeriod);
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
}
private MappingJackson2HttpMessageConverter converter() {
ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false)
.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false)
.setTimeZone(TimeZone.getTimeZone("GMT"))
.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"));
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper);
return converter;
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setDefinitions(new String[] {"/WEB-INF/views/tiles.xml"});
tilesConfigurer.setCheckRefresh(true);
return tilesConfigurer;
}
#Bean
public UrlBasedViewResolver viewResolver() {
UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
viewResolver.setViewClass(TilesView.class);
return viewResolver;
}
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(maxUploadSize);
return multipartResolver;
}
}
While deploying the war we are getting the exception.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in class path resource [com/expedia/risk/cm/config/WebConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No URL for ServletContext resource [/WEB-INF/views/tiles.xml]
Please see what is the problem with this thing, I tried but this looks okay to me.

Unable to run Spring Boot WebMVC with Thymeleaf support

I have search a lot but I did not find answer to my question, So I am posting my question here. Please look and suggest me the solution where I am mistaken.
I have created spring boot web mvc project with thymeleaf support using Spring Tool Suite(STS). When I run it give me "Whitelabel Error Page" page. Which means mapping not found.
Efforts:
WebConfig.java
package com.springthymeleaf.config;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
#Configuration
#ComponentScan("com.springthymeleaf")
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
ServletRegistrationBean servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean();
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
//start Thymeleaf specific configuration
#Bean(name ="templateResolver")
public ServletContextTemplateResolver getTemplateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
// templateResolver.setPrefix("/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("XHTML");
return templateResolver;
}
#Bean(name ="templateEngine")
public SpringTemplateEngine getTemplateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(getTemplateResolver());
return templateEngine;
}
#Bean(name="viewResolver")
public ThymeleafViewResolver getViewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(getTemplateEngine());
return viewResolver;
}
//end Thymeleaf specific configuration
#Bean(name ="messageSource")
public MessageSource getMessageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/i18/thymeleafResource");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}
SecurityConfiguration.java
package com.springthymeleaf.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll();
}
}
ServletInitializer.java
package com.springthymeleaf;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringThymeLeafApplication.class);
}
}
SpringThymeLeafApplication.java
package com.springthymeleaf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringThymeLeafApplication {
public static void main(String[] args) {
SpringApplication.run(SpringThymeLeafApplication.class, args);
}
}
IndexController.java
package com.springthymeleaf.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class IndexController {
#RequestMapping("/")
public String index(){
return "index";
}
}
I have created index.html file in resources/templates folder. Still I am getting that error. I have searched a lot on web, but did not get clue. Please somebody help me.
Actually Spring Boot configures Thymeleaf out of the box. It should work with the following setup:
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll() // http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#jc-form
.and()
.logout().permitAll(); // http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#jc-logout
}
#Override
public void configure(WebSecurity web) throws Exception
{
web
.ignoring()
.antMatchers("/resources/**"/*, ... */);
}
}
#Controller
public class LoginController
{
#RequestMapping("/login")
static String login(Model model)
{
return "login";
}
}
Spring Boot already configures Thymeleaf for you, so no need to configure that manually. Remove all Thymeleaf related configuration, also remove #EnableWebMvc as that interferes with the Spring Boot auto configuration. The #ComponentScan is also redundant.
Spring Boot also registered a MessageSource for you so no need to configure that. Not sure what the servlet registration is you do but that is the only thing you need.
Also I suggest to remove your controller and use a view controller which you can configure in your WebConfig class. Saves you a controller.
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
ServletRegistrationBean servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean();
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
}
To let the auto configured message source pickup your custom bundles add the following to src/main/resources/application.properties.
spring.messages.basename=/WEB-INF/i18/thymeleafResource
I would also suggest to simply let the SpringThymeLeafApplication extend the SpringBootServletInitializer.
#SpringBootApplication
public class SpringThymeLeafApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringThymeLeafApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringThymeLeafApplication.class);
}
}
Also make sure that your templates are in src/main/resources/templates and not in src/main/resources/resources/templates else those will not be found.
Spring boot does all the automatic configuration when you add the thymeleaf dependency. then you should do the following.
Remove all the thymeleaf configuration you have on your WebConfig.java
Make sure you have the following dependency your pom.xml if you are using Maven, otherwise check the spring website for the equivalent if you are using gradle:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
thirdly you make sure that you scanning where your controllers are, add the following on your SpringThymeLeafApplication.java:
#ComponentScan(basePackages = "your.path.to.controllers")
Finally you have to add your .html files to resources/templates

Spring MVC: message source doesnt seem to point to the properties

I have been stuck for several days now on this.
Here is my WebMvcConfig class:
package utils;
import Beans.Users;
import com.mycompany.fanalweb.backingbeans.Roles;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;
#ComponentScan({"com.mycompany.fanalweb.controllers", "com.mycompany.fanalweb.backingbeans", "utils", "Utils"})
#ImportResource({"classpath:SpringConfig.xml", "WEB-INF/webflow-config.xml", "WEB-INF/aop-config.xml"})
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public ViewResolver viewResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setCacheable(false);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".xhtml");
templateResolver.setTemplateMode("HTML5");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setOrder(1);
ServletContextTemplateResolver flowResolver = new ServletContextTemplateResolver();
flowResolver.setCacheable(false);
flowResolver.setPrefix("/WEB-INF/flows/");
flowResolver.setSuffix(".xhtml");
flowResolver.setTemplateMode("HTML5");
flowResolver.setCharacterEncoding("UTF-8");
flowResolver.setOrder(0);
Set<TemplateResolver> set = new HashSet<>();
set.add(flowResolver);
set.add(templateResolver);
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolvers(set);
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setContentType("text/html; charset=UTF-8");
viewResolver.setOrder(1);
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
//session users and roles
#Bean
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Users sessionUser() {
Users u = new Users();
return u;
}
#Bean
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Roles sessionRoles() {
Roles u = new Roles();
return u;
}
//internationalization
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.ENGLISH);
return localeResolver;
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/international/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
Here is my WebAppInitializer :
package utils;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{
SecurityConfig.class,
WebMvcConfig.class
};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
The application is launching well but on my login page, my "international texts" are not translated.
For instance, I have: ??user.mail_en?? , ??user.password_en??
My properties files are located in : src/main/resources/international
They are called: messages.properties and messages_fr.properties
I already tried:
to put them in WEB-INF but without success.
to change messageSource.setBasename("/international/messages"); to messageSource.setBasename("international/messages"); => no success
No errors are displayed and the page is rendered correctly ( pictures, CSS,...) except for those "international messages".
Thank you for you help.
Just guess: From javadoc:
Note that the base names set as "basenames" property are treated in a
slightly different fashion than the "basenames" property of
ResourceBundleMessageSource. It follows the basic ResourceBundle rule
of not specifying file extension or language codes, but can refer to
any Spring resource location (instead of being restricted to classpath
resources). With a "classpath:" prefix, resources can still be loaded
from the classpath, but "cacheSeconds" values other than "-1" (caching
forever) will not work in this case.
so maybe just try: classpath:/international/messages
If you are using ReloadableResourceBundleMessageSource you have to prefix your basename with the classpath:. So in your case:
classpath:/international/messages
Here is the solution:
Spring 4 with thymeleaf Internationalization not identify message from resource properties file
To make a summary: you need to define 3 distinct beans for viewResolver, templateResolver and templateEngine. You cannot define all in the viewresolver definition.
It seems that Spring demands the 3 distinct beans to work properly

Spring multi-language

I'm new working with Spring MVC and I have some problems to add multi language to my application.
I dont' use xml configuration. I have a #Configuration class
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages="com.springexamples.basic.controller")
public class BasicServletConfig extends BaseConfig {
#Bean
ViewResolver viewResolver() {
return getViewResolver("views/basic/", ".jsp");
}
#Bean
MessageSource messageSource() {
return getMessageSource("/messages/messages");
}
#Bean
LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang");
return interceptor;
}
#Bean
LocaleResolver localeResolver() {
return new SessionLocaleResolver();
}
#Bean
HandlerMapping handlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setInterceptors(new HandlerInterceptor[] { localeChangeInterceptor() });
return mapping;
}
}
When I test de application always I see the default language (spanish). I send the request with the parameter 'lang=en' or 'lang=EN' but I still see it in default language.
¿Anyone knows the solution?.
Thanks,
I'm not sure how HandlerMapping declared this way will play with #EnableWebMvc. A more idiomatic way to configure interceptors with #EnableWebMvc is to use WebMvcConfigurer:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages="com.springexamples.basic.controller")
public class BasicServletConfig extends BaseConfig implements WebMvcConfigurer {
...
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
...
}

Categories

Resources