当我在15年前尝试切换到基于XML的JSP时,这是一个问题,看起来它仍然是一个问题.
使用Tomcat 9,如果我有一个简单的JSP页面,输出格式很好.
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8"/>
<title>Example</title>
</head>
<body>
<p>Example</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
输出看起来与源几乎相同.但是如果我使用JSP文档(JSPX):
<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.3">
<jsp:directive.page contentType="text/html; charset=UTF-8" />
<jsp:text><!DOCTYPE html></jsp:text>
<html lang="en-US">
<head>
<meta charset="UTF-8"/>
<title>Example</title>
</head>
<body>
<p>Example</p>
</body>
</html>
</jsp:root>
Run Code Online (Sandbox Code Playgroud)
那么输出就变成了一条长线:
<!DOCTYPE html><html lang="en-US"><head><meta charset="UTF-8"/><title>Example</title></head><body><p>Example</p></body></html>
Run Code Online (Sandbox Code Playgroud)
是的,我理解这背后的原因:解析XML文档模型,操纵树,重新序列化等等.但实际上:它很难看,我不喜欢它,可能没有人喜欢它.在输出中获得合理的换行符和缩进的最简单,最实用的方法是什么?
浏览器不关心的事实是不重要的.作为开发人员,我们必须使用它.这很丑陋而且妨碍了.(是的,我知道可能没有人使用JSPX甚至JSP,但我想我还是会问.)
复制自从 jsp 输出中去除空格
有一个trimWhiteSpaces功能可能是您的问题:
在您的 JSP 中可能有:
<%@ page trimDirectiveWhitespaces="true" %>
Run Code Online (Sandbox Code Playgroud)
您应该将其设置为 false 并在 jsp-config 部分中设置您的 web.xml:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<trim-directive-whitespaces>false</trim-directive-whitespaces>
</jsp-property-group>
</jsp-config>
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看可在 Tomcat 9 服务器中调整的进一步配置。