Java Servlet/JSP - 无法访问会话属性

Java Servlet/JSP - can't access session attribiutes

在做家庭作业时,第一个任务严格是关于 servlet,然后在 servlet 之间传递值时,session.setAttribiutesession.getAttribiute 工作正常。但是自从使用 servlets 和 jsp 我有空值的问题。这是有问题的代码。
小服务程序:

@WebServlet(name = "SubmitLoginServlet", value = "/submitLogin")
public class SubmitLogin extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            Connection con = DatabaseConnection.initDatabase();
            Statement statement = con.createStatement();
            String sql = "SELECT * FROM users";
            ResultSet resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                String DBusername = resultSet.getString("name");
                String DBpassword = resultSet.getString("password");
                if(DBusername.equals(username) && DBpassword.equals(password)) {
                    request.getSession().setAttribute("username", "test");
//                  I USED "TEST" JUST FOR TESTING, STILL THE VALUE ON 'INDEX.JSP' IS EMPTY
                    request.getRequestDispatcher("/index.jsp").forward(request,response);
//                    response.sendRedirect("index.jsp");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// INDEX.JSP - pasted in this block because of bug with code formatting, sorry
// on top of the file I have <%@ page session = "false" %>

<div class="column is-one-fifth is-offset-two-fifths">
            <%
                HttpSession session = request.getSession(true);
                if(session.getAttribute("username") == "" || session.getAttribute("username") == null) {
            %>
            <form action="register.jsp">
                <button type="submit" class="button is-info is-fullwidth">Signup</button>
            </form>
            <form action="login.jsp" method="get">
                <button type="submit" class="button is-success is-fullwidth">Login</button>
            </form>

            <% } else { %>
            <h1 class="title"> Welcome <% request.getSession().getAttribute("username"); %></h1>
            <button class="button is-danger">Logout</button>
            <% } %>
        </div>

然后在登录并重定向到 index.jsp 后,我有 Welcome,但 space 和注销按钮是空的。有帮助吗?

对不起各位,我只是不擅长 Java 仅此而已。我不知道当你想在 JSP 中 输出 值时,你需要使用 <%= %> 标签而不是用于逻辑的 <% %> .