【问题标题】:How to access input value from one jsp page to another jsp page using sessions?如何使用会话将输入值从一个 jsp 页面访问到另一个 jsp 页面?
【发布时间】:2019-11-25 02:41:11
【问题描述】:

在我的 login.jsp 中,我使用了以下代码。我创建了一个会话并打算传递用户将插入的用户名和电子邮件。

<%
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","");
        Statement st=con.createStatement();
        %>
        hai
        <%
        String username=request.getParameter("username");
        String email=request.getParameter("email");
        String password=request.getParameter("password");
        ResultSet rs=st.executeQuery("Select * from user3");
        HttpSession sess = request.getSession(); 
        sess.setAttribute("username","username");
        sess.setAttribute("email","email");

        while(rs.next())
        {
            String username=rs.getString(1);
            String email1=rs.getString(2);
            String password1=rs.getString(3);

            if((email1.equals(email)) && (password1.equals(password)))
            {
                response.sendRedirect("book.html");
            }
            else
            {
                response.sendRedirect("register.html");
            }

        }

    }
    catch(Exception e)
{

}

%>

在另一个 jsp 页面中,我需要访问这些值,即用户名和电子邮件,以便我可以将其插入数据库。

<body>


<%
HttpSession sess = request.getSession(false); 
String username=sess.getAttribute("username").toString();
String email=sess.getAttribute("email").toString();

try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "");
Statement st=conn.createStatement();

int i=st.executeUpdate("insert into busA(username,email)values('"+username+"','"+email+"')");
out.println("Data is successfully inserted!");
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
%>

这些是我当前的代码,但没有按我的意愿将值插入到我的数据库中。

【问题讨论】:

    标签: java html jsp session-variables backend


    【解决方案1】:

    在第一个 jsp 中,您将会话变量的值设置为字符串,而不是传递用户名和密码变量。

    所以不是:

    sess.setAttribute("username","username");
    sess.setAttribute("email","email");
    

    试试

    sess.setAttribute("username",username);
    sess.setAttribute("email",email);
    

    此外,此问题可能与未激活会话有关,tomcat 中会话的默认行为是使用带有键 JSESSIONID 的 cookie,如果该 cookie 正在设置并与第二个 jsp 一起发送,您可以使用浏览器开发工具检查打电话

    在代码里面你可以使用

    request.getSession().getId()
    

    查看两次通话之间的会话是否相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 2014-04-17
      • 2012-01-30
      相关资源
      最近更新 更多