通过会话变量存储数据
storing data through session variables
我的应用程序允许用户执行某些操作
我想在他连接时记住他的名字然后将其插入数据库(以便知道是谁做了这个动作)而不是强迫他写
这是我的 servlet 的代码
String name = request.getParameter("name");
User userName= new User(name);
request.getSession().setAttribute("user_name", userName);
response.sendRedirect("next.jsp");
由于您已将属性存储在当前会话中,因此您可以在任何您想要的 servlet 中调用该属性并将其存储在您使用的数据库中 JDBC。
例子:
这是我的数据库架构:
Table 用户
|id |name |password|
|01 |John due |xxxxxxx |
Table 产品
|id |name |price |
|07 |coca-cola |03 |
table 交易
|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 |
我的应用程序允许用户执行某些操作 我想在他连接时记住他的名字然后将其插入数据库(以便知道是谁做了这个动作)而不是强迫他写
这是我的 servlet 的代码
String name = request.getParameter("name");
User userName= new User(name);
request.getSession().setAttribute("user_name", userName);
response.sendRedirect("next.jsp");
由于您已将属性存储在当前会话中,因此您可以在任何您想要的 servlet 中调用该属性并将其存储在您使用的数据库中 JDBC。
例子: 这是我的数据库架构:
Table 用户
|id |name |password|
|01 |John due |xxxxxxx |
Table 产品
|id |name |price |
|07 |coca-cola |03 |
table 交易
|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 |