对于那些像我一样学习并仍在苦苦挣扎的人,我想与您分享并补充@ddekany的答案,可以在servlet中做到:
public class FW {
String contextPath0;
String contextPath;
FW(HttpServletRequest request) {
contextPath0 = request.getContextPath();
contextPath = contextPath0 + "/";
}
public String getContextPath() {
return contextPath0;
}
public String url(String path) {
if (path.startsWith("/")) return contextPath0 + path;
return contextPath + path;
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("fw", new FW(request));
request.getRequestDispatcher("/template-00.ftl").forward(request, response);
}
之后,在 .ftl 模板中
<pre style="border: 1px solid black; padding: 1em 1em 1em 1em;">
fw.context path: "${fw.contextPath}"
fw.url 1: "${fw.url('/my/safe/absolute/path')}"
fw.url 2: "${fw.url('my/safe/relative/path')}"
</pre>