Is it possible to have multiple locale resolver inside spring ?
I want to have multiple Locale Resolver inside my application like :
CookieLocaleResolver for user permanent language.
Http request Based LocaleResolver for just seeing a particular
page in another language.
Don't see problem to write your own LocaleResolver and register it as bean with name DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME.
The logic of resolveLocale implementation may be really based on the request, when you can determine to use CookieLocaleResolver or provide someother locale from request attributes
Related
I configured my web application as indicated in https://www.baeldung.com/spring-boot-internationalization#localeresolver
with setting Locale.ITALIAN as default locale for LocaleResolver bean.
I have two message files:
message.properties with italian messages
message_en.properties with messages in english
However, labels defined in messages_en.properties, when exists. For example with setting locale via lang=es request parameter, messages in english are shown.
The expected behaviour, if I understand, should be that if lang=en, message_en.properties should be used, where as for all other languages messages in message.properties should be used.
Suggestions?
If you use the latest version of Spring Boot (2.5.3 at the moment), the tutorial isn't as up-to-date. For example, with the latest Spring you must do additional, but simple config to override LocaleResolver bean.
Depending of your implementation, you may need to add in the application.properties file the line spring.messages.fallback-to-system-locale=false or if you overridden the "messageSource" bean, you must set messageSource.setFallbackToSystemLocale(false); in your own bean.
This way the app should work as expected, with all languages except EN using message.properties.
I'm following this guide and it says to name the default messages file as messages.properties. Why can't I name it messages_en.properties and set the default locale to English?
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.ENGLISH);
return slr;
}
This doesn't work (have to hard stop and restart the server each time message.properties is renamed - dynamic reload fails to pick up the changes). It will print out default text with a tag like <spring:message code="oops" text="default"/> because it can't find messages_en.properties.
In fact, when I set my browser default language to French and have messages_fr.properties, and restart the server, it is also failing to find the keys for French as well.
Not using Thymeleaf. No need to allow user-selectable language.
Reference: https://docs.spring.io/spring-boot/docs/1.5.17.RELEASE/reference/htmlsingle/ (Only one instance of the world 'internationalization', and only regarding application properties).
I fixed it by using AcceptHeaderLocaleResolver instead.
#Bean
public LocaleResolver localeResolver() {
AcceptHeaderLocaleResolver ahlr = new AcceptHeaderLocaleResolver();
ahlr.setDefaultLocale(Locale.ENGLISH);
return ahlr;
}
I thought the guide said it will search for the locale in the session, cookie, or header, but they were only saying that different sub-classes implement those features separately.
The LocaleResolver interface has implementations that determine the current locale based on the session, cookies, the Accept-Language header, or a fixed value.
I fixed the live reload problem by setting this application property, at least for debugging:
spring.messages.cache-seconds=1
I also set this property so as not to clutter up my src/main/resources folder, so I could move all the message files into the locales/ sub-directory.
spring.messages.basename=locales/messages
The default implementation of InvalidSessionStrategy i.e. SimpleRedirectInvalidSessionStrategy in Spring security redirects the request to a default url. This default url comes from a final variable.
I would like to override the behavior by not redirecting all the time to the same url. How could I achieve that ? If I create a custom implementation of InvalidSessionStrategy, how can I use that ?
This is my configuration right now
and()
.addFilterAfter(mySpringSecurityConfig.forceLogoutFilter(), PreAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("http://xxx/login.jsp")
.sessionAuthenticationErrorUrl(PropertyMgr.getCarnivalURL("http://xxx/login.jsp"))
But I don't want to use "http://xxx/login.jsp" for all invalid sessions. Thanks for the help.
Please post your entire configuration and the Spring Security version, so that we can have the whole picture.
However, to override InvalidSessionStrategy, simply define your class implementing this interface.
Then find a way to put your implementation into SessionManagementFilter.
One way can be via SessionManagementConfigurer.
In the worst case you can always extend SessionManagementFilter, put your InvalidSessionStrategy there, and substitute the default sesssion filter.
Some one please me to find out the spring mvc examples,
Because usually, once we log in into the application we will create a session and put some objects into session . we will access later point of time , request scope as well. but spring MVC3 is difficult to understand even documentation also confusing, but every one giving example is basic examples only.
You can access these objects in a JSP/JSTL:
applicationScope
cookie
header
headerValues
initParam
pageContext
pageScope
param
paramValues
requestScope
sessionScope
As well as any request attributes that you add, including model attributes (who's default name is command).
More info here: http://www.informit.com/articles/article.aspx?p=30946&seqNum=7
If you want to access HttpRequest, HttpResponse, HttpSession, add them as arguments to a Spring Controller Handler Method . Spring will pass them in for you.
I am trying to access a resource bundle using Spring framework (WebFlow). A messages.properties file and accordingly messages_ar_AE.properties file are kept in the classpath from where the Spring Framework access the resource bundle.
The code in invoked from a xhtml file using the JSTL resourceBundle attribute.
<myCustom:includedInSetValidator set="5.0, 5.0.1, 5.1"
validationMessage="#{resourceBundle['jboss.version.error']}" />
But irrespective of locale, the "#{resourceBundle['jboss.version.error']}" always fetches the default text, i.e; from English;
As I learned from some forums I got an hint that I need to handle this using LocaleChangeInterceptor or some other predefined classes. Once the Spring Locale is set, the proper resource bundle will be loaded by default, and hence solving my problem.
I need a way to change the Spring Framework Locale programatically to set the Locale. How do I achieve this programatically ?
Thanks.
Reached the solution for the problem.
Continuing from my question, when Spring Framework encounters a JSTL expression like "#{resourceBundle['jboss.version.error']}" by default it looks for message.properties file in the classpath, unless a resource bundle is defined explicitly.
When trying to fetch the proper resource bundle, the framework looks at the at the locale it is set to. As the locale of Spring Framework was not set in my case, it was not fetching me the expected resource bundle. Out of available options i chose Spring LocaleResolver
I modified existing JSF Custom ViewHandler in my application, where I added code to set the locale of Spring Framework.
public Locale calculateLocale(FacesContext arg0) {
HttpServletRequest request = (HttpServletRequest)arg0.getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse)arg0.getExternalContext().getResponse();
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
localeResolver.setLocale(request, response, **setYourLocaleHere**);
}
The story just doesn't end here, setting the locale in locale resolver this way would throw the error:
Cannot change HTTP accept header – use a different locale resolution strategy
Refer Cannot change HTTP accept header error
To overcome this, one should include
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
in the Spring configuration file.
And now the desired locale of the Spring Framework is set.
There could possibly a better solution than what I did. One can also suggest their solutions if any.
Thanks.
You could do this multiple ways as outlined here in the doc.