How to call a variable with JSP?

Ray :

In JSP I have created a simple variable like this:

<%
    if (request.getSession().getAttribute("user") != null) {
        String status = "online";
    }
    else {
        String status = "offline";
    }
%>

In HTML I call the variable like this: ${status}

So the string "offline" or "online" would just be a CSS class, as you see in the code below:

<img class="profile-pic" src="../assets/img/reza.png" alt="Chin"> <i class="status ${status}"></i>Reza

So the whole code looks like this:

<%
    if (request.getSession().getAttribute("user") != null) {
        String status = "online";
    }
    else {
        String status = "offline";
    }
%>
    <div class="user-section">
        <img class="profile-pic" src="../assets/img/reza.png" alt="Chin"> <i class="status ${status}"></i>Reza
    </div>

but from Intellij I get the warning:

Cannot resolve variable 'status'

How can I fix this?

YCF_L :

You have a problem with scopes, when you declare a variable inside an if or else block you can use this variable just in that scope, you can solve your issue like so :

<%
    String status = "offline"; // declare the variable outside the if else
    if (request.getSession().getAttribute("user") != null) {
        status = "online"; // if the condition is correct then assign "online"
    }
%>

After your edit

It seems you are using the variable name with a wrong way, instead you have to use :

<i class="status <%=status%>">

Instead of :

<i class="status ${status}">

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326977&siteId=1