2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Is there an easy way to compare two strings in JSP?

I have the below snippet where I want the easiest way to compare the string using JSTL

    <c:forEach items="${languages}" var="lang">
            <c:when test="${lang}.equals(${pageLang})">
                <option value="${lang}" selected>${lang}</option>
                <option value="${lang}">${lang}</option>

.equals doesn"t appear to exist in JSPs. Having had a look here it"s suggested I write my own function and then import and use that. As this is a one off tiny thing just for this page I don"t want to have to start creating libraries etc just for this. Nor do I want to start creating specialist objects for the servlet to return with this extra info in them.

Only thing I can think to do is to return the actual html for the whole option line from the servlet rather than just the language string, but that strikes me as ugly so I"m hoping there"s a more elegant solution.

What is the best plan for a quick fix to comparing two strings in a JSP?


Yes there is some ways by using EL (Expression Language),

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as


If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as

Answer is