Search code examples
javajspjstljsp-tags

Using Eq (JSTL) violates MVC principles in case choosing type menu for logined user


I faced with next problem. I use 2 kind menu( for Tutors and Students). And I decided to include menu in dependence on role logined user. All things are OK. But I use next construction:

<div class="left"> 
    <c:if test="${role eq 'TUTOR'}">
        <c:import url="/page/tutor/menuForTutor.jsp" charEncoding="UTF-8"/>
    </c:if>

    <c:if test="${role eq 'STUDENT'}">
        <c:import url="/page/student/menuForStudent.jsp" charEncoding="UTF-8"/>
    </c:if>
</div>

People say that using 'eq' is a bad style. I tried to escape this situation: I created user's tag. but when I do next

if (Role.TUTOR.equals(role)) {
            try {
                pageContext.getOut().write("<c:import url=\"/page/tutor/menuForTutor.jsp\" charEncoding=\"UTF-8\"/>");
            } catch (IOException ex) {
                Logger.getLogger(MenuTag.class.getName()).log(Level.SEVERE, null, ex);
            }

I cannot get that I expect because as I understand transform jsp in html occurs before creation user's tag.

Can you advice me other ways to do that I want? Thanks

P.S. And also I use localization in my jsp files for menu (fmt)

<fmt:bundle basename="by.bsuir.testing.resource.content" prefix="content.">
    <fmt:message key="menu" var="Menu"/>
    <fmt:message key="startPage" var="StartPage"/>
    <fmt:message key="menuitem.editInfoAboutTest" var="MenuItemEditInfoAboutTest"/>
</fmt:bundle>
<h1>${Menu}</h1>
<ul>    
    <li>
        <a href="${pageContext.servletContext.contextPath}/page/common/login.jsp">
            ${StartPage}
        </a>
    </li>            
    <li>
        <a href="controller?command=all_Subject_Edit">
            ${MenuItemEditInfoAboutTest}
        </a>
    </li>  
</ul>

Solution

  • I don't know why 'eq' is a bad style (or '==' which is the same).

    But your tag won't work, because you cannot write JSP directives to the out and expect it will work:

    pageContext.getOut().write(
       "<c:import url=\"/page/tutor/menuForTutor.jsp\" charEncoding=\"UTF-8\"/>");
    

    You can only write HTML - as it's output sent to browser, not for compiling to the web-container.

    You can try to directly call ImportTagImportTag instead:

    ImportTag tag = new ImportTag();
    tag.setUrl("/page/tutor/menuForTutor.jsp");
    tag.setCharEncoding("UTF-8");
    tag.setContext(pageContext);
    tag.doStartTag();
    

    P.S. But I would have just used 'eq' or '==' instead.