Spring has its strategy to make the internationalisation in our spring project by declaring its beans. to access the messages from jsp files we use
<spring:message code="messages.field">
Thats ok for jsp files but what about extjs(javascript) files ?
for example I have login.js must use the i18n messages:
items: [ {
fieldLabel: **// here I must get the field messages.username//**,
name: 'j_username',
allowBlank: false,
listeners: {
specialkey: function(field, e) {
if (e.getKey() == e.ENTER) {
submitForm();
}
}
}
},
Temporarily, I created my own solution without using spring i18n beans and may it will be helpfully as a solution if we don't have an approch to implement i18n with spring from extjs.however it's not to say that my solution don't present some disadvantages that I will list them at the end of this post.
first create a controller I18nController.java, this controller will be the target of the incoming requests that have the pattern /i18n.js, its responsibility to create a javascript variable i18n and return the response as a contentType = javascript.
@RequestMapping(value = "/i18n.js", method = RequestMethod.GET)
public void i18n(HttpServletResponse response, Locale locale) throws JsonGenerationException, JsonMappingException,
IOException {
response.setContentType("application/javascript;charset=UTF-8");
byte[] output = buildResponse(locale);
response.setContentLength(output.length);
ServletOutputStream out = response.getOutputStream();
out.write(output);
out.flush();
}
private byte[] buildResponse(Locale locale) {
ResourceBundle rb = ResourceBundle.getBundle("i18n/messages", locale);
Map<String, String> messages = Maps.newHashMap();
Enumeration<String> e = rb.getKeys();
while (e.hasMoreElements()) {
String key = e.nextElement();
messages.put(key, rb.getString(key));
}
String output = "var i18n = "+ jsonHandler.writeValueAsString(messages) + ";";
Second, in any jsp/html files I just use :
<script src ="i18n.js"></script>
So by that I can access to my variable from any extjs files and resolve the i18n messages:
items: [ {
fieldLabel: i18n.user_username,
name: 'j_username',
allowBlank: false,
listeners: {
specialkey: function(field, e) {
if (e.getKey() == e.ENTER) {
submitForm();
}
}
}
}
return output.getBytes(StandardCharsets.UTF_8);
}
disadvantages:
- why using my own solution whereas spring give the classes to implements the same solution(make the project totally spring)
- If my propoerties file messages_en.preoperties has a huge entries and lets say that the js file will use only 2 fields, here, i loaded the full entries :( ==> bad performance.
So then, how can I resolve i18n messages from extjs and using spring without using my solution ?
Thanks.
thanks to javaScriptEscape too lol :) – Sayros Mar 24 '16 at 22:17