我刚刚从不同的 Servlet/JSP 引擎切换到 Tomcat 6.0.26。以前,空值将作为空字符串打印出来。但是,Tomcat 将空值打印为“null”。
<% String str = null; %>
The value of str is <%= str %>.
这输出
The value of str is null.
如何让 Tomcat 将空字符串替换为空字符串?
最佳答案
这是默认和预期的行为。显然,以前的服务器为此有一些专有配置设置。 Tomcat 中没有想到。
无论如何,scriptlet 是一种古老的技术,十多年来不鼓励使用它。它已被 taglibs(如 JSTL)和 Expression Language (EL) 继承。结合 Servlet 作为 Controller 。
例如在 Servlet 的 doGet()
:
String str = null;
request.setAttribute("str", str);
request.getRequestDispatcher("page.jsp").forward(request, response);
并在page.jsp
:
The value of str is ${str}
如果值等于 null
,EL 默认不打印任何内容而 scriptlet 表达式 ( <%= %>
) 默认打印任何 String#valueOf()
返回。
另见:
关于jsp - 如何让 Tomcat 输出空字符串而不是 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3095419/