Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if request URL is for the current page, so that a menu link can be enabled/disabled

Tags:

url

jsp

menu

How can I check if I'm on a specific URL? I have a menu with many links and I'd like to disable the link for the current page. How can I achieve that?

like image 794
Victor Avatar asked Jul 12 '11 01:07

Victor


2 Answers

You can use HttpServletRequest#getRequestURI() to obtain the request URI. The getServletPath() as suggested by the other answer is not necessarily helpful as it represents the servlet path (the matching part in the JSP/Servlet URL pattern), not the request URI (as the enduser sees in the browser address bar). If the JSP was been forwarded by some front controller servlet, you would get the JSP's own path instead of the virtual path as in the browser address bar.

Assuming that you have a menu which is represented by a List<Page> in the application scope where the Page class has url and name properties, here's a kickoff example with help of JSTL:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<ul id="menu">
    <c:forEach items="${menu}" var="page">
        <c:set var="active" value="${fn:endsWith(pageContext.request.requestURI, page.url)}" />
        <li class="${active ? 'active' : 'none'}"><a href="${page.url}">${page.name}</a></li>
    </c:forEach>
</ul>

You can then define the menu item style by the .active class. E.g. giving it a black color, some highlighting background, etc.

ul#menu li {
    background: white;
}

ul#menu li.active {
    background: pink; 
}
like image 138
BalusC Avatar answered Oct 22 '22 16:10

BalusC


To get the current URL of the page, you can use:

Relative Path: <%= request.getServletPath() %>

Can you elaborate how you want to disable some links?

like image 30
Raptor Avatar answered Oct 22 '22 18:10

Raptor