使用JSP和XML编写的消息 [英] Composed messages using JSP and XML

查看:53
本文介绍了使用JSP和XML编写的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有消息的XML,例如:

I have a XML with messages, for example:

<?xml version="1.0" ?>
<messages>
    <hello>Hi {1} welcome to {2}</hello>
</messages>

所以我想用一些JSP变量替换{1}和{2}并打印结果:

So I want to replace the {1} and {2} with some JSP variables and print the result:

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/xml" prefix="x" %>

/* set vars */
<c:set var="name" value="John Doe" />
<c:set var="location" value="Internet" />

/* import and parse xml */
<c:import url="messages.xml" var="messages" />
<x:parse xml="${messages}" var="xml" />

/* print message */
<x:out select="$xml/messages/hello" var="name" var="location"  />

最后一行的结果应该是:

The result of the last line should be:

Hi John Doe welcome to Internet

我正在尝试使其正常工作,但我完全迷失了.您能帮我解决这个问题还是给我这个技术"的名称,以便不断寻找信息?

I'm trying to get this working but I'm completely lost. Can you help me to solve this or give me the name of this "technique" to keep looking for information?

谢谢!

推荐答案

这类任务通常称为"国际化"或"模板化".

This kind of tasks are generally referred as "Internationalization" or "Templating".

这是使用现有代码执行此操作的简单方法:

This is a simple approach of how you can do this with your existing code:

<c:set var="helloTemplate">
    <x:out select="$xml/messages/hello" />
</c:set>

<c:out value="<%= java.text.MessageFormat.format(helloTemplate, 
                                pageContext.getAttribute("name"), 
                                pageContext.getAttribute("location")) %>" />

在JSP中使用scriptlet (<%= .. %>)并不是最好的处理方式,而是可以创建一个在内部使用MessageFormat的函数/标记.创建自定义标签的示例: https://sites.google .com/a/pintailconsultingllc.com/java/custom-jsp-tag-libraries

Using scriptlets (<%= .. %>) in JSP is not the best way of doing things, instead you can create a function/tag that uses the MessageFormat internally. Example of creating custom tag: https://sites.google.com/a/pintailconsultingllc.com/java/custom-jsp-tag-libraries

或者,如果您可以控制消息文件,则可以使用属性文件来代替XML格式(例如messages.properties),该文件将包含:

Alternatively, If you have control over the message file, you can use properties file instead of the xml format (e.g. messages.properties) which will contain:

hello=Hi {1} welcome to {2}

然后可以按以下方式使用它:

This can then be used as follows:

<fmt:message key="hello">
    <fmt:param value="${name}" />
    <fmt:param value="${location}" />
</fmt:message> 

这通常称为"国际化"-更多信息:

This is generally referred to as "Internationalization" - more info: http://docs.oracle.com/cd/E19159-01/819-3669/bnaxu/index.html

这篇关于使用JSP和XML编写的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆