Get current filename in JSP

随声附和 提交于 2019-11-29 00:58:01

问题


Is there a way to get which JSP is currently rendered, with JSTL or Struts (or without)? like _ _ file _ _ in Python and PHP?


回答1:


Well ... yes ... in a way

String __jspName = this.getClass().getSimpleName().replaceAll("_", ".");

I'm using a JSP called pre.jsp for that which I include at the top of each JSP in my webapp:

<%@page import="org.apache.log4j.Logger"%>
<%
    String __jspName = this.getClass().getSimpleName().replaceAll("_", ".");

    Logger log = Logger.getLogger(this.getClass().getName());
    log.info("BEGIN JSP "+__jspName);
%>
<!-- BEGIN <%=__jspName %> -->

Plus I put this at the end of each JSP:

<!-- END <%=__jspName %> --><% log.info("END JSP "+__jspName); %>

That gives me a consistend log. To make sure each JSP is "correct", I have a check in my build script which just looks for the two strings "/pre.jsp" and ``END <%=__jspName`.

Note: There are many characters which are allowed in file names but not in Java class names. If you use them, your class names might look weird. If that's the case, I suggest to create a static helper function which converts class names to File names and call that, i.e.

String __jspName = MyJspUtils.getFileName(this.getClass());

Each JSP compiler has it's own rules; here is one example: http://itdoc.hitachi.co.jp/manuals/3020/30203Y0510e/EY050044.HTM

Kudos go to Marcus Junius Brutus for pointing that out.




回答2:


The more convenient way is to use: <%= request.getRequestURI() %>

<%= request.getRequestURI() %> For example, in all of my jsp files, I always do put this line:

Rendering JSP File: '<%= request.getRequestURI() %>'

This puts a comented html line in to the rendered html. This way one cannot see it in the browser, but for debugging purposes, I can always see it inf I do "View source".




回答3:


I succeeded using JSTL as following :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<!-- <c:out value="${pageScope['javax.servlet.jsp.jspPage']}"></c:out> -->
...

And now, you should see as an HTML comment the name of the servlet produced by the container to render your JSP file, which name is very close to the JSP source file.




回答4:


This is a simple copy-paste solution:

<%=this.getClass().getSimpleName().replaceFirst("_jsp","")%>


来源:https://stackoverflow.com/questions/863248/get-current-filename-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!