Spring multi-language - java

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());
}
...
}

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.

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

Adding a second datasource - SpringBoot RepositoryRestService PersistenceConfig

I'm trying to find the best approach to adding a second datasource to our application. The main purpose is to expose CRUD ops against the db via rest, & need to bounce against a 2nd db for authentication and role management. We are not using XML configs.
Is there a way to simply add a second datasource bean in the existing PersistenceConfig.java file, or do we need to replicate the whole config class for the second db instance?
The application:
package foo;
import foo.config.PersistenceConfig;
import foo.config.RepositoryRestConfig;
import foo.config.WebConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#ComponentScan
#EnableJpaRepositories
#Import({PersistenceConfig.class, WebConfig.class, RepositoryRestConfig.class})
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
The Repo:
package foo.repository;
import foo.Widget;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
#RepositoryRestResource(collectionResourceRel = "widgets", path = "widgets")
public interface WidgetsRepository extends CrudRepository<Widget, Long> {
List<Widget> findByWidgetId(#Param("widgetid") long widgetId);
}
The persistence config :
package foo.config;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
#Configuration
#Import(RepositoryRestMvcConfiguration.class)
#EnableJpaRepositories
#EnableTransactionManagement
public class PersistenceConfig {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.SQL_SERVER);
vendorAdapter.setShowSql(true);
final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("foo.model");
factory.setDataSource(dataSource());
return factory;
}
#Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dataSource.setUrl("jdbc:sqlserver://127.0.0.1:1433;databaseName=fooDB");
dataSource.setUsername("sa");
dataSource.setPassword("*******");
dataSource.setTestOnBorrow(true);
dataSource.setTestOnReturn(true);
dataSource.setTestWhileIdle(true);
dataSource.setTimeBetweenEvictionRunsMillis(1800000L);
dataSource.setNumTestsPerEvictionRun(3);
dataSource.setMinEvictableIdleTimeMillis(1800000L);
dataSource.setValidationQuery("SELECT 1");
return dataSource;
}
#Bean
public JpaDialect jpaDialect() {
return new HibernateJpaDialect();
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}
}
Thank you for your assistance...
Take a look at #Qualifier annotation. With this annotation you are able to define various beans of the same type and assign them names. It is equivalent of id parameter in bean XML tag.
This is relevant part of Spring documentation.
First of all, it's worth noting that almost all of the configuration in PersistenceConfig is redundant as Spring Boot will automatically configure it for you. Pretty much the only thing that is non-default and you need to specify is your DataSource configuration, for example the SQLServer URL.
There's a section in the documentation that describes how to configure two DataSources using #Primary and application.properties:
Creating more than one data source works the same as creating the first one. You might want to mark one of them as #Primary if you are using the default auto-configuration for JDBC or JPA (then that one will be picked up by any #Autowired injections)."
#Bean
#Primary
#ConfigurationProperties(prefix="datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
#ConfigurationProperties(prefix="datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
You'd then configure these two DataSources using application.properties and the datasource.primary and datasource.secondary prefixes:
For example:
datasource.primary.jdbcUrl=jdbc:sqlserver://127.0.0.1:1433;databaseName=fooDB
datasource.primary.user=sa
datasource.primary.password=secret
datasource.primary.jdbcUrl=jdbc:sqlserver://127.0.0.1:1433;databaseName=barDB
datasource.primary.user=sa
datasource.primary.password=secret

Spring MVC LocaleChangeInterceptor annotation based doesn't work

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;
}
}

Categories

Resources