java 如何在 servlet 中获取消息资源对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1592902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I obtain the message resources object in a servlet?
提问by Carlos Pastor
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.
我正在使用 Struts 开发一个项目,我想知道是否可以在包含在同一个项目中的 servlet 中获取消息资源对象。
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?
getResources(HTTPServletRequest)因为 servlet 没有扩展 Action 类,所以不可能使用该方法获取该对象。有没有办法做到这一点?
Thanks in advance.
提前致谢。
回答by Carlos Pastor
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.
嗯,我终于找到了怎么做。如果有人遇到同样的问题,这里是解决方案:在您的 servlet 中使用 java.util.ResourceBundle 类。
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 并传递属性类的名称和要使用的语言环境,如下所示:
ResourceBundle rb = new ResourceBundle("com.foo.package.theClass", myLocale);
//And then get the messages from the rb object
rb.getMessage("myPropertiesKey");
回答by Horia Chiorean
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.
获得操作后,您可以使用 TextProvider 接口获取该操作所需的任何资源。
回答by D. Wroblewski
MessageResources-object is stored in the request scope with the key Globals.MESSAGES_KEY ("org.apache.struts.action.MESSAGE").
MessageResources-object 存储在请求范围内,键为 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"));
}

