如果请求是同步发送的(例如表单提交按钮),那么你不一定需要JS来完成这项工作。只需让JSP/EL立即将它们打印为基于由servlet预先填充的数据的输入值。例如,假设${user}
是由小服务程序制备的典型的Javabean:
<input type="text" name="name" value="${fn:escapeXml(user.name)}" />
<input type="text" name="city" value="${fn:escapeXml(user.city)}" />
<input type="text" name="country" value="${fn:escapeXml(user.country)}" />
(该fn:escapeXml()
只是为了防止跨站脚本攻击)
如果请求被异步地发送(使用AJAX例如),那么你只需要让该servlet以JS可以轻松解析的格式返回数据,例如JSON。
{
"username": "Bauke Scholtz",
"city": "Willemstad",
"country": "Curaçao"
}
然后可以使用作为Ajax响应回调函数如下(其中user
是获得JSON对象):
document.getElementById("name").value = user.name;
document.getElementById("city").value = user.city;
document.getElementById("country").value = user.country;
jQuery让这样的事情要容易得多。另请参阅How to use Servlets and Ajax?
Psssh ... http://w3fools.com – BalusC