Java Servlet如何通过会话获取UserId

时间:2020-05-24 17:27:20

标签: java

我正在尝试编写用户控制脚本。

用户添加一些任务,我希望用户看到自己的任务。在登录页面中,这是会话部分:

        HttpSession session = request.getSession();
        session.setAttribute("username", uname);
        response.sendRedirect("welcome.jsp");

这是任务发送部分:

Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/covid?useUnicode=true&characterEncoding=utf8","root","");


                 PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert 
                into gorevler(gorevtext,baslik) values(?,?)");
                 pst.setString(1, output);
                 pst.setString(2, output);
                 pst.executeUpdate();

我想将用户ID发送到数据库。因此,用户可以列出自己的任务。我该怎么办?

2 个答案:

答案 0 :(得分:0)

您只需从会话中获取username属性,即可像使用其他任何变量一样使用它。

// Contrived example based on your posted example
HttpSession session = request.getSession();
String userName = session.getAttribute("username");
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert 
            into gorevler(gorevtext,baslik, username) values(?,?, ?)");
pst.setString(1, output);
pst.setString(2, output);
pst.setString(3, userName);
pst.executeUpdate();

答案 1 :(得分:0)

用户隐式会话对象以读取会话...

String userName=(String)session.getAttribute("username"); 
...
pst.setString(1, userName);