How to obtain the current language in a controller? - java

Here is my locale configuration
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
When I try to call locale in a controller using
#RequestMapping(value = "customers/customer-{idCustomer:[0-9]+}/detail", method = RequestMethod.GET)
public ModelAndView detail(Map<String, Object> map, #PathVariable Integer idCustomer, Locale locale) {
logger.info(locale.toString());
logger.info(request.getLocale().toString());
...
}
It returns different values. But when I switch a language on a site using GET param in URL ?lang=en, it change nothing in mentioned controller's calls. i18n works fine, it loads a labels from correct file. But I want to obtain changed language in my controllers. I want to obtain choosed language independently on opened page (with/without request param lang in URL).

You can use LocaleContextHolder class that Spring provides for this purpose. From documentation:
Used as a central holder for the current Locale in Spring, wherever
necessary: for example, in MessageSourceAccessor. DispatcherServlet
automatically exposes its current Locale here. Other applications can
expose theirs too, to make classes like MessageSourceAccessor
automatically use that Locale.
Then in your controller just call:
LocaleContextHolder.getLocale();
to retrieve the locale using Spring.
LocaleContextHolder.getLocale() javadoc.

Related

Configuring locale switching with Spring MVC

First of all I have to say, that I am an absolute beginner in developing Spring Application. What I try to do is to switch the locale from 'en' to 'de'. For this I found the configuration below witch I put in my mvc-dispatcher-servlet.xml
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="Messages" />
</bean>
<!-- Localization Start -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
After that I expect that I can change the locale by adding '?language=de' behind a existing URL. So the request 'http://localhost:8080/?language=de' should switch the locale. This didn’t work. The website is shown in the defined default language
My property files are located in /src/main/resources. The names are “Messages_en.propperties” and “Messages_de.propperties”. If I switch the default language to “de”, the correct language file is loaded and the website is shown in german.
Has someone an idea what’s wrong in my configuration?
I believe you have to register the LocaleChangeInterceptor with an interceptor in Spring
<!-- Declare the Interceptor -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
p:paramName="locale" />
</mvc:interceptors>
The LocaleChangeInterceptor is configured to look for the parameter name 'locale' to indicate a change of the user's locale, and is registered as an interceptor using the Spring MVC Namespace. For example, adding 'locale=es' to a URL would change the locale to Spanish.

Spring date datatype [duplicate]

Consider this simple example -
public class Person
{
private String name;
private Date dateOfBirth;
// getters and setters here...
}
In order to initialize Person as a Spring bean, I can write the following.
<bean id = "Michael" class = "com.sampleDomainName.Person">
<property name = "name" value = "Michael" />
</bean>
But in the above bean definition, how can I set the dateOfBirth?
For eg. I want to set the dateOfBirth as
1998-05-07
Treat it like any other POJO (which is is)
<property name="dateOfBirth">
<bean class="java.util.Date" />
</property>
If you need to use an explicit value (such as 1975-04-10), then simply call one of the other constructors (although those which take year-month-day are deprecated). You could also use an explicit java.beans.PropertyEditor which Spring rolls with already (see section 6.4.2; note that you can write your own editors and register them for your own types). You need to register the CustomEditorConfigurer in your config:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date"
value="org.springframework.beans.propertyeditors.CustomDateEditor"/>
</map>
</property>
</bean>
Then your data looks like:
<property name="dateOfBirth" value="1975-04-10" />
I might add that Date is not an appropriate data type to store a date-of-birth because Date is really an instant-in-time. You might like to look at Joda and use the LocalDate class.
One of the answers mentioned here is useful, but it needs additional information. The constructor arguments for the CustomDateEditor need to be supplied.
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date"> <ref local = "customDateEditor" />
</entry>
</map>
</property>
</bean>
<bean id = "customDateEditor" class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
Now we can do
<property name="dateOfBirth" value="1998-05-07" />
Spring inject Date into bean property – CustomDateEditor
This paper give two suggestions:
Factory bean
CustomDateEditor
I suggest the "Factory Bean" because the CustomDateEditor is not supported in Spring 4.0+ and the Factory Bean is easy enough to use.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="customer" class="com.mkyong.common.Customer">
<property name="date">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-01-31" />
</bean>
</property>
</bean>
</beans>
Use a CustomDateEditor. It's been in Spring since the early days.

How to read properties file according to the language just set by the user (in a spring application)

I'm creating a little web application in Spring. I created 2 properties files, italian and english.
With links like IT the user can select the language.
In my file-servlet.xml I have this
......
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" >
<property name="defaultLocale" value="en"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
........
I have no problem getting the right value when using <spring:message code="XXX"/>, but i dont understand how to get the right value, according to the language set by the user, when I'm "inside" a class.
I was trying to do something like this :
ApplicationContext context = new ClassPathXmlApplicationContext("messages.xml");
String s = context.getMessage("intestazione",null, Locale.getDefault()));
The problem is that with Locale.getDefault() iI get the Locale of the JVM and not the language set by the user.
You can have the current Locale injected into a controller method by simply declaring it as a parameter. Alternatively you could use LocaleContextHolder.getLocale().
If you can access HttpServletRequest form class, try like this
String s = context.getMessage("intestazione",null, request.getLocale()));

Retrieving locale information using a java program

Is it possible to store locale information in a spring bean and retrieve it in a java application?
Scenario...
I am passing the locale parameter along with the url as follows:
url?lang=fr
Spring context.xml configuration looks like below:
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName" value="myAppLocaleCookie"/>
<property name="defaultLocale" value="fr" />
<property name="cookieMaxAge" value="604800"/>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang"/>
</bean>
</mvc:interceptors>
Need to fetch locale data from the applicationcontext.xml in my java application.
Is there a way to store current locale to a bean in .xml file and retrieve it in java application.
I am not able to retrieve the changed locale into my java application.
How can I get the locale information in my java application whenever it is changed?

Spring REST API and i18n

In my REST API I want to allow the user to set the locale using a lang parameter, i.e.
http://somehost/resource?param1=value1&lang=fr
If the lang parameter is not present in the URL then the Accept-Language header should be used and set as the Locale.
I'm using Spring's i18n features in my REST API. I have looked through the documentation and configured the necessary beans. If I send a request with the Accept-Language header it seems to work OK, when I call LocaleContextHolder.getLocale() it returns the locale I set in my header.
If I use the lang URL parameter it does not work.
How can I configure Spring to use the locale parameter too?
<bean id="localeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeInterceptor" />
</list>
</property>
</bean>
<bean id="sessionLocaleResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
<bean id="messages" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
</list>
</property>
</bean>
I have two suggestions to try out. First, are you certain that the LocaleChangeInterceptor is getting invoked? Most of the configurations I've seen have an id of handlerMapping for the HandlerMapping. The other suggestion is concerning another id, namely sessionLocaleResolver, I think it should be localeResolver. I'm not sure if Spring relies on those id values or the class types by default for wiring all of this together, but it is worth a shot.

Categories