Search code examples
javajspscriptlet

Displaying Java Property in JSP


I have a class with a property called title and I have a getter/setter that gets and sets the property. If the property is P I need to print the word "Peer" on the page, and if it's T I need to print "Team" on the page. Can I do this in a JSP without using a scriplets? I tried using

<jsp:getProperty name="value" class"classname"  />

but from there I have no idea how to use a conditional in a JSP. Please help.


Solution

  • Use JSTL, as @CoolBeans says. It would look something like this:

    In the servlet,

    // where myBean is an instance of the class with [get|set]Title
    request.setAttribute("myFoo", myBean);
    

    Then, in the JSP,

    <c:choose>
        <c:when test="${myBean.title eq 'P'}">Peer</c:when>
        <c:when test="${myBean.title eq 'T'}">Team</c:when>
    </c:choose>
    

    If you're not familiar with JSTL, I'd recommend reading through the JSP section of the Java EE 5 Tutorial, or picking up a copy of Head First Servlets and JSP (it's quite good).