【问题标题】:storing data through session variables通过会话变量存储数据
【发布时间】:2019-09-11 05:32:09
【问题描述】:

我的应用程序允许用户执行某些操作 我想在他连接时记住他的名字,然后将其插入数据库(以便知道谁做了这个动作)而不强迫他写

这是我的servlet的代码

String name = request.getParameter("name");
User userName= new User(name);
request.getSession().setAttribute("user_name", userName);
response.sendRedirect("next.jsp");

【问题讨论】:

    标签: java mysql session jakarta-ee


    【解决方案1】:

    由于您已经在当前会话中存储了该属性,您可以在任何您想要的 servlet 中调用该属性并将其存储在您使用 JDBC 的数据库中。

    示例: 这是我的数据库架构:

    表用户

    |id |name      |password|
    |01 |John due  |xxxxxxx |
    

    餐桌产品

    |id |name      |price   |
    |07 |coca-cola |03      |
    

    表交易

    |id |user_id | product_id |
    

    在你写的代码中

     Connection conn = DriverManager.getConnection(url,user,password);
    
    User user = request.getSession().getAttribute(ATT_USER);
    Product product = request.getSession().getAttribute(ATT_PRODUCT);
    
    int userId = user.getId();
    int productId = product.getId();
    
    String query = "insert into transaction(user_id,product_id) values (?,?)";
    
    PreparedStatement prep = conn.preparestatement(query);
            try {
                prep = conn.prepareStatement(query);
    
                prep.setInt(1,userId);
                prep.setInt(2,productId);
    
                prep.executeUpdate();
    
            } catch (SQLException e) {
                e.printStackTrace();
            }
    

    那么你的数据库中应该有

    |id |user_id | product_id |
    |01 |01      |07          |
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 2014-02-07
      • 2016-04-25
      • 1970-01-01
      • 2021-02-01
      相关资源
      最近更新 更多