开发者

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

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 开发者_JS百科link for the current page. How can I achieve that?


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; 
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜