【发布时间】:2014-09-18 04:06:53
【问题描述】:
我想将getGneratedKeys(也称为last_generated_id)从当前Java 类传递到下一个类。但是,我对如何存储和收集 ID 到下一个 Java 类以供此类使用。
场景是insert.jsp 将插入所有字符串和int到我的mysql数据库中。第二页UserImage.jsp 将将图像上传到与insert.jsp 相同的表和相同的记录中。
这意味着 UserImage 查询将是 update 查询而不是插入查询。
Save.java(insert.jsp 的关联类):
public String execute()
{
int i = 0; //SELECT LAST_INSERT_ID();
try{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull","root","8899");
String s = "insert into usertable(userNRIC, userName, userEmail, userPW, userContact, userAddress, catID, catTypeID, sectionID, status"
+ ") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ";
PreparedStatement ps=con.prepareStatement(s, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, mb.getUserNRIC());
ps.setString(2, mb.getUserName());
ps.setString(3, mb.getUserEmail());
ps.setString(4, mb.getUserPW());
ps.setInt(5, mb.getUserContact());
ps.setString(6, mb.getUserAddress());
ps.setInt(7, mb.getCatID());
ps.setInt(8, mb.getCatTypeID());
ps.setInt(9, mb.getSectionID());
ps.setString(10, mb.getStatus());
ps.executeUpdate();
con.commit();
ResultSet rs = ps.getGeneratedKeys();
if (rs != null && rs.next()) {
i = rs.getInt(1);
//ps.setInt(i, mb.getUserID("UserID"));
}
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
}
return SUCCESS;
}
FileUploadAction.java(UserImage.jsp 的关联类):
public String execute(){
int i = 0;
connection = getConnection();
String query = "update usertable set userPhoto=? where userID=?";
try {
String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
System.out.println("Server path:" + filePath);
File fileToCreate = new File(filePath, this.userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);
//String uniqueFileName = fileToCreate.getPath();
pst = connection.prepareStatement(query);
pst.setString(1, this.userImageFileName);
i = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
【问题讨论】:
-
什么是用户旅程?页面是如何导航的?
-
@Braj
用户提交insert.jsp后,如果成功,会跳转到UserImage.jsp/Student/UserImage.jsp /Student/error.jsp
标签: java mysql jsp jdbc struts2