对警告“无法解析变量”感到困惑

时间:2019-05-04 20:39:36

标签: java jsp intellij-idea

login.java 中,我使用req.setAttribute("username", req.getParameter("username"));;在 welcome.jsp 中,我使用Hello ${username},但是Intellij给我警告:< / p>

  

无法解析变量“用户名”

该变量有效。为什么会收到此警告?

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);
    }
}

2 个答案:

答案 0 :(得分:1)

可能是您的login.java,您使用sendRedirect来访问welcome.jsp页面,它丢失了请求范围变量。

response.sendRedirect("welcome.jsp"); 

在login.java中,您需要对此进行更改以保持用户名可变

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

为防止警告,您可以更新Intellij>设置>代码检查

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

答案 1 :(得分:1)

您有2个选择:

选项1

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

选项2

${requestScope.username}