无法获取会话属性(在JSP中创建新会话)为什么?

时间:2015-03-25 07:04:34

标签: java html jsp session

的Login.jsp

    <%
        /* Getting Database connection*/
        Connection connection = ConnectionFactory.getInstance()
                .getConnection();
        if (connection == null) {
            System.out.print("Error in getting DB connection");
        }

        /* requesting user login credentials*/
        String login_name = request.getParameter("username");
        String login_pass = request.getParameter("password");

        if ((login_name != null && login_name.trim() != "")
                || (login_pass != null && login_pass.trim() != "")) {

            String query = "SELECT USER_NAME,PASSWORD from MEMBERS where USER_NAME='"
                    + login_name + "'";
            PreparedStatement ps = connection.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            String USER_NAME = null;
            String PASSWORD = null;
            while (rs.next()) {
                USER_NAME = rs.getString("USER_NAME");
                PASSWORD = rs.getString("PASSWORD");
            }

            //verifying with database 
            if ((USER_NAME.equals(login_name) && PASSWORD
                    .equals(login_pass))) {
                //starting session
                session.setAttribute("UserName", USER_NAME);

                System.out.println(session.getCreationTime());
                out.print("<head> <meta http-equiv=\"Refresh\" content=\"0;url=./home.jsp\" > </head>");

            } else {
                out.println("Login Failed");
            }
        } else {
            out.println("Please Enter Your Credentials");
            %>
    <jsp:include page="./login.html"></jsp:include>
    <%

        }
%>

回到Home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
    Hi, <%= session.getAttribute("UserName") %>


<% System.out.println(session.getCreationTime());%>
</body>
</html>

Home.jsp显示Hi,null为什么? 我明白家庭.jsp正在创建新会话,但如何利用现有会话?任何人都可以帮忙解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

尝试将此声明添加到您的页面:

<%@ page session="false" %>

这将阻止在提供JSP时创建会话。此外,我认为它不是关于会话,而是关于USER_NAME的价值。 尝试调试在login.jsp中设置的USER_NAME的值

答案 1 :(得分:0)

我没有看到会议声明, 尝试获得&amp;使用请求设置会话如下:

的Login.jsp

request.getSession().setAttribute("name", yourStringObject);

回到Home.jsp

yourStringObject = (String) request.getSession().getAttribute("name");

并且不要忘记从会话中删除对象:

request.getSession().removeAttribute("name");

答案 2 :(得分:0)

首先做

session=request.getSession();

然后从会话中设置或获取属性