views:

382

answers:

3

Hi everyone,

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 servlet does not extends an Action class. Is there a way to do it?

Thanks in advance.

A: 

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"));
}
D. Wroblewski
Thanks for your help but I can't make it work.request.getAttribute(Globals.MESSAGES_KEY); returns null.I forgot to say some more info about it. I'm making use of the library Struts 1.3.10 and the servlet is defined in the web.xml as you can see below:<servlet> <description> </description> <display-name> PvsInterface </display-name> <servlet-name>PvsInterface</servlet-name> <servlet-class>com.ford.ads.rapid.pvsw.pvs.PvsInterface</servlet-class> <load-on-startup>1</load-on-startup></servlet>Am I missing something else? Thanks in advance
Carlos Pastor
how do you configure your message resources? Does your struts-config.xml contain something like this:<message-resources parameter="StrutsMessages" />And if you do, is your message-resources properties file in your classpath?
D. Wroblewski
Thanks for answering. Yes, I have the message resources configured in the struts-config.xml file. And the resources files are where the code is, in a package called resources.
Carlos Pastor
+1  A: 

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");
Carlos Pastor
A: 

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.

Horia Chiorean