我正在开发一个项目,我需要在jsp页面中动态添加文本框。文本框的数量将等于数据库表中的行数。对于不同的用户,这可能会有所不同。如何我是用Java Servlets做的吗?
答案 0 :(得分:0)
select count(*) will give you number of rows
使用preparedStatement / Statement。 在
里面while(resultSet.next())
{
your html codes for creating textboxes//
}
答案 1 :(得分:0)
假设您正在尝试填充servlet类中的文本框,下面是动态填充文本框的示例代码。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
out = response.getWriter();
response.setContentType("text/html");
// JDBC driver name and database URL
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://hostname:port/test";
// Database credentials
final String USER = "username";
final String PASS = "password";
java.sql.Connection conn = null;
java.sql.Statement stmt = null;
//STEP 2: Register JDBC driver
try {
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt =conn.createStatement();
String sql = "SELECT name FROM table1";
ResultSet rs = null;
rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String name = rs.getString("name");
//Display values
System.out.print("Name: " + name);
out.println("<input type=\"text\" name=\"last_name\" value = "+name+">"+"</input>");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
您可以根据您的请求类型(GET或POST)将代码粘贴到doGet()或doPost()方法中。
如果您使用jsp填充文本框,则还有其他方法可以执行此操作。
干杯:-)