开发者

How can I obtain the message resources object in a servlet?

开发者 https://www.devze.com 2022-12-08 18:39 出处:网络
I\'m developing a project with Struts and I was wondering if it\'s possible to get the message resources object in a servlet, which is included in the same project.

I'm developing a project with Struts and I was wondering if it's possible to get the message resources object in a servlet, which is included in the same project.

There's no possibility to get that object with the method getResources(HTTPServletRequest) because the servl开发者_开发问答et does not extends an Action class. Is there a way to do it?

Thanks in advance.


Well, I finally found how to do it. Just if somebody gets stuck in the same issue, here's the solution: use the java.util.ResourceBundle class in your servlet.

You just have to create the ResourceBundle passing along the name of the properties class and the locale you want to use, like you can see below:

ResourceBundle rb = new ResourceBundle("com.foo.package.theClass", myLocale);
//And then get the messages from the rb object
rb.getMessage("myPropertiesKey");


You can also do something like this:

ActionContext.getContext().getActionInvocation().getAction() //the action context is threadlocal

Once you have the action, you can use the TextProvider interface to get whatever resource you need for that action.


MessageResources-object is stored in the request scope with the key Globals.MESSAGES_KEY ("org.apache.struts.action.MESSAGE").

PropertyMessageResources p = (PropertyMessageResources) request.getAttribute(Globals.MESSAGES_KEY);
String messageValue = null;
if (p != null) {
  // Value for key errors.notempty
  messageValue = p.getMessage("errors.notempty"));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号