How to get page name in JSP or JSTL?
Asked Answered
D

4

9

I want to get current page name (something like "myPage") using JSP or JSTL. How can I achieve this?

Dissected answered 15/5, 2011 at 9:53 Comment(0)
U
19

You can get it by HttpServletRequest#getServletPath().

${pageContext.request.servletPath}

You can use the JSTL functions taglib to extract the extension whenever necessary.

Underworld answered 15/5, 2011 at 12:8 Comment(3)
it gives me something like /webinf/views/myPage.jsp , can you please give me a little help how to extract the name onlyDissected
Ah OK, you're using a controlling servlet which forwards to JSPs in /WEB-INF folder. Use ${requestScope['javax.servlet.forward.servlet_path']} instead to get the servlet path of the URL as it appears in browser address bar.Underworld
i was able to do it in the following way too: request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1,request.getRequestURI().lastIndexOf("."));Dissected
L
0

To get the page:

<% String pageName = com.kireego.utils.Utils.extractPageNameFromURLString(request.getRequestURI()); %>

and this helper code:

public static String extractPageNameFromURLString(String urlString){
        if (urlString==null) return null;
        int lastSlash = urlString.lastIndexOf("/");
        //if (lastSlash==-1) lastSlash = 0;
        String pageAndExtensions = urlString.substring(lastSlash+1);
        int lastQuestion = pageAndExtensions.lastIndexOf("?");
        if (lastQuestion==-1) lastQuestion = pageAndExtensions.length();
        String result = pageAndExtensions.substring(0,lastQuestion);
        return result;
    }
Logwood answered 2/11, 2012 at 14:55 Comment(0)
K
0

This line will get you the correct JSP name, it's working also when the page includes multiple pages

<%= this.getClass().getSimpleName().replaceAll("_5F", "").replaceFirst("_", "") %>.jsp<BR> 
Kalmick answered 13/10, 2021 at 14:44 Comment(2)
Not working when invoked from a tagAutonomy
@Autonomy need to be in the jsp bodyKalmick
G
-3

maybe you can get it thought javascript way, like:

var url = window.location.href;

then use string methods to get current page name.

Gregg answered 15/5, 2011 at 12:10 Comment(1)
JavaScript is neither JSP nor JSTL.Humanize

© 2022 - 2024 — McMap. All rights reserved.