I want to localize the exception messages thrown from POJO classes using Spring. I have a Spring MVC application through which I can add books. If the added book's title is null the implementation class throws an Exception. I want to localize this.
I know I can use the localeResolvers in the JSP pages and I have done that already. Can I leverage this to pick up localized error messages in the POJO? If so how do I inject the locale resolver (Cookie or Session) or locale which was set on the Cookie/Session into the POJO class?
addBook method throwing exception
public void addBook(IBook book) throws Exception {
if (book.getTitle() == null || book.getTitle() == "") {
throw new Exception("Title is null");
}
I want the throw new Exception("Title is null")
; to be something like
String msg = rBundle.getMessage(propKey)
throw new Exception(msg);
where rBundle is a bundle object which knows its locale and the properties file from which it should pick the value for propKey
my controller class method which receives the form submission
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(
@RequestParam("siteLanguage") String siteLanguage,
@ModelAttribute("book") Book book, BindingResult result,
SessionStatus status, HttpServletRequest arg0) {
logger.debug("Adding a Book");
Locale loc = RequestContextUtils.getLocale(arg0);
if (result.hasErrors()) {
return "error.htm";
} else {
try {
Author author = new Author("Gabriel Garcia Marquez");
book.setAuthor(author);
library.addBook(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:home.htm";
}
}
Is this possible? Or is it better I control the loading of java ResourceBundle for the respective locale.
Thanks
As Chapter 10 pointed out, exceptions should be caught and localized messages should be displayed to the user. This can be accomplished by using the Struts message resource bundle and the ActionError class. You should never display a Java exception to the end user.
The getLocalizedMessage() method of Throwable class is used to get a locale-specific description of the Throwable object when an Exception Occurred. It helps us to modify the description of the Throwable object according to the local Specific message.
Why do you want to localize Exception?: I guess the exceptions are stored in a log file, the administrator should be able to read them, without knowledge of all the languages the users speak.
If you are talking about form validation, then have a look at spring form validation and jsr303 bean validation, both include concepts of localisation. (But both does not work with exceptions.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With