I'm trying to get my application work according to the OS locale of the client machine. For now it works with the locale of server machine. I'm using string frmae work. Apache Tomcat 7 is used as the server. Here is the configuration I used. Any help would be appriciated.
<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>
<!-- Register the welcome.properties -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>i18n.api/api</value>
<value>i18n.exceptions/exceptions</value>
<value>i18n.common/common</value>
<value>i18n.login/login</value>
<value>i18n.plan/plan</value>
<value>i18n.customer/customer</value>
<value>org.springframework.security.messages</value>
<value>org.hibernate.validator.ValidationMessages</value>
</list>
</property>
</bean>
Please see supported handler method argument types on Spring doc. You can inject the user's Locale on your handler method like this:
#RequestMapping("/home")
public String home(Locale userLocale) {
// do something with userLocale
return "home";
}
Locale is of type java.util.Locale.
Also have a look at getLocale() method of ServletRequest. The client has to provide Accept-Language header on their request, otherwise server's locale is used. I'm assuming Spring behave in the same fashion as this
Related
I'm extending a complete product called Hippo CMS with my own REST interface. Hippo CMS is using Apache CXF for rest and acquires resources definitions from a spring bean defined somewhere in Hippo CMS sources. This definition look like this:
<bean id="jaxrsRestPlainResourceProviders" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.apache.commons.collections.ListUtils" />
<property name="targetMethod" value="union" />
<property name="arguments">
<list>
<ref bean="customRestPlainResourceProviders" />
<ref bean="defaultRestPlainResourceProviders" />
</list>
</property>
</bean>
<bean id="defaultRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
</list>
</property>
</bean>
<!-- Default empty list of custom plain resource providers to be overriden. -->
<bean id="customRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
</list>
</property>
</bean>
I need to override customRestPlainResourceProviders bean with my own bean. It works fine from XML configuration looking like this:
<bean id="customRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
<bean class="org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider">
<constructor-arg>
<bean class="com.xxx.rest.FolderStructureResource"/>
</constructor-arg>
</bean>
</list>
</property>
</bean>
But it doesn't work if I define a bean in Java configuration class (which in the case of other beans works completely fine):
#Bean(name = "customRestPlainResourceProviders")
public ListFactoryBean customRestPlainResourceProviders() {
ListFactoryBean listFactoryBean = new ListFactoryBean();
listFactoryBean.setSourceList(
Lists.newArrayList(
new SingletonResourceProvider(
new FolderStructureResource(repository())
)
)
);
return listFactoryBean;
}
Is there a way to override a bean defined in XML configuration with a bean created in Java configuration class?
What version of spring are you using? I believe this issues is addressed in 4.2.
I have been having problem with my DateFormat. en_US, en_UK, en_IN are all same for my webapp. The only thing that matters is dateformat to be used throughout the webapp.
First i tried to override the dateformat of en locale, apparently i failed to find any good solution on how to do that.
Hence i planned to change the default locale to en_IN, because we use the date format as dd/mm/yy
No effect, then en_GB... but no luck.
Please note that i did restart tomcat after making changes but no luck.
my dispatcher-servlet.xml in WEB-INF sets it as follows.
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="request_locale" />
</bean>
<!-- <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/locale*"/>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" >
<property name="paramName" value="request_locale" />
</bean>
</mvc:interceptor>
</mvc:interceptors>
-->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="mappingHandler" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
Adding
<constant name="struts.locale" value="en_GB" />
to struts.xml did the job.
If there are any possible side-effects, please let me know
I am using Spring MVC 3. I have message bundles in following format :
message_en_US.properties
message_en.properties
message_USA.properties
In my JSP I am using :
Now, the order of finding the values should be en_US, then en then USA property files.
how can i customize this ?
You should use configuration below. So, if you want to set default language you can use the second one.
In my src/main/resources I have mymessages_en_US.properties and mymessages_es_ES.properties
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<array>
<value>classpath:mymessages</value>
</array>
</property>
<property name="defaultEncoding" value="UTF-8" />
<property name="cacheSeconds" value="0" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="es_ES" />
</bean>
I am trying to return json and xml response using ResponseBody, and it does work fine for xml but doesnt return json. My request uri for xml is '../home.xml' and for json is '../home.json' from controller method:
#RequestMapping("home.*")
public #ResponseBody Message homeOther(HttpServletRequest request, HttpServletResponse response, ModelMap mv){
Message msg = new Message();
msg.setDetail("I am here at home");
msg.setUploadDate(new Date());
mv.addAttribute("message", msg);
return msg;
}
And here is the dispatcher servlet:
<context:component-scan base-package="com.ym"/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="alwaysUseFullPath" value="true"/>
</bean>
<bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/views"/>
</bean>
<!-- Simple ViewResolver for Velocity, appending ".vm" to logical view names -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="order" value="2" />
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".vm"/>
<property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"/>
<!-- if you want to use the Spring Velocity macros, set this property to true -->
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="contentType" value="text/html; charset=UTF-8" />
</bean>
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller" />
<bean id="xmlView" class="org.springframework.web.servlet.view.xml.MarshallingView"
>
<constructor-arg ref="xstreamMarshaller" />
</bean>
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter" />
<ref bean="marshallingHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="xstreamMarshaller"/>
<property name="unmarshaller" ref="xstreamMarshaller"/>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
</bean>
<ref bean="xmlView" />
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
</bean>
Here is XML response:
<com.ym.mongodb.model.Message>
<messageId>0</messageId>
<detail>I am here at home</detail>
<uploadDate>2013-03-09 09:56:46.606 UTC</uploadDate>
</com.ym.mongodb.model.Message>
My problems are:
1. what is worng with the configuration? why it doesnt return a json response.?
2. Why the xml it returns, display fullyqualified name of Message?
i am using Spring 3.1.
Edit:
Interestingly, it does create json n xml correctly when request type is set properly. But still the 2nd problem does exists.
I don't know what you try to achieve in detail so I don't know if I can help but I'll give it a shot.
First of all you can try and add accept headers. Below is an example.
#RequestMapping(value = "/home/yourpath", method = RequestMethod.GET,
headers = "Accept=application/xml, application/json")
By adding the accept header json and xml requests will be accepted when invoking your method and parsing data as for example with a curl client. Also maybe you should consider to set a request method explicitly.
When you send the request to the client make sure that you have "Content-Type: application/json" or "Content-Type: application/xml" added to the header of your request depending on the content you send. Otherwise you'll get an unsupported content type error because you maybe send the wrong content type.
There are two ways of actually displaying the correct content type in Spring.
1: Through parsing/accepting the right content-type in the header of your request (by condiguring accept headers in the client).
2: Through configuring file extensions (there are certain default file extensions that should work out of the box. xml and json are covered.). Try to add .xml or .json to the end of your uri.
Have a look here: http://static.springsource.org/spring/docs/3.1.0.RELEASE/reference/htmlsingle/#mvc-multiple-representations
Look at following example:
http://www.mkyong.com/spring-mvc/spring-3-mvc-contentnegotiatingviewresolver-example/
I can't help you with your second problem.
I hope this helps. Good luck.
Kind regards,
Chris
I am using session locale resolver for my application. I am showing the languages in dropdown. if the user selects on any of the language then repopulates all values from that language.
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="languageCode" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
But its is not reading it from the session. Always it considers the defaultlanguage from browser setting.
Please help on this.
You need to obtain the locale in this way:
Locale loc=RequestContextUtils.getLocale(request);
In Spring 4.0 we can Also use LocaleContextResolver.getLocale() method as well.