There isn't. Since I don't do Spring, I'll leave it out of the context in this answer. For the Spring-targeted answer, see @skaffman. You can create a class which extends
ResourceBundle
, manage the loading yourself with help of a Filter
(based on request path?) and store it in the session scope. The ResourceBundle
is accessible the usual JSP EL way. You can access it as if it's a Map
. The handleGetObject()
method will be invoked on every access.
Here's a kickoff example:
package com.example;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.http.HttpServletRequest;
public class Text extends ResourceBundle {
private static final String TEXT_ATTRIBUTE_NAME = "text";
private static final String TEXT_BASE_NAME = "com.example.i18n.text";
private Text(Locale locale) {
setLocale(locale);
}
public static void setFor(HttpServletRequest request) {
if (request.getSession().getAttribute(TEXT_ATTRIBUTE_NAME) == null) {
request.getSession().setAttribute(TEXT_ATTRIBUTE_NAME, new Text(request.getLocale()));
}
}
public static Text getCurrentInstance(HttpServletRequest request) {
return (Text) request.getSession().getAttribute(TEXT_ATTRIBUTE_NAME);
}
public void setLocale(Locale locale) {
if (parent == null || !parent.getLocale().equals(locale)) {
setParent(getBundle(TEXT_BASE_NAME, locale));
}
}
@Override
public Enumeration<String> getKeys() {
return parent.getKeys();
}
@Override
protected Object handleGetObject(String key) {
return parent.getObject(key);
}
}
The Filter
:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Text.setFor((HttpServletRequest) request);
chain.doFilter(request, response);
}
JSP:
<p>${text['home.paragraph']}</p>
If you want to change the locale from inside some servlet or filter:
Text.getCurrentInstance(request).setLocale(newLocale);
Related/interesting-to-know: