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.getM开发者_JS百科essage(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
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.)
精彩评论