Ray
Ray

Reputation: 145

Confused about the warning "Cannot resolve variable"

In login.java I am using req.setAttribute("username", req.getParameter("username")); and in welcome.jsp I am using Hello ${username} but Intellij gives me the warning:

Cannot resolve variable 'username'

The variable works. Why do I get this warning?

login.java

package ch.yourclick.zt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("username", req.getParameter("username"));
        req.setAttribute("password", req.getParameter("password"));
        req.getRequestDispatcher("/welcome.jsp").forward(req, resp);
    }
}

Upvotes: 0

Views: 4139

Answers (2)

Reza Saadati
Reza Saadati

Reputation: 5439

You have 2 options:

Option 1

<% String username = (String) request.getAttribute("username"); %>
<%= username %>

Option 2

${requestScope.username}

Upvotes: 1

Hien Nguyen
Hien Nguyen

Reputation: 18973

May be your login.java you use sendRedirect to welcome.jsp page and it lost request scope variable.

response.sendRedirect("welcome.jsp"); 

In login.java you need change to this to keep username variable

RequestDispatcher requestDispatcher = request.getRequestDispatcher("welcome.jsp");
requestDispatcher.forward(request, response);

For prevent warning you can update setting for Intellij > Setting > Code Inspection

https://www.jetbrains.com/help/idea/code-inspection.html

Upvotes: 1

Related Questions