需要写一个POJO类(Employee类),在JSP检索DB数据。
public class Employee {
String id;
String name;
String mobileNo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
}
JSP下面提供:
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
String id = request.getParameter("userId");
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String dbName = "dbname";
String userId = "root";
String password = "password";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<h2 align="center"><font><strong>Retrieve data from database in jsp</strong></font></h2>
<table align="center" cellpadding="5" cellspacing="5" border="1">
<%
try{
connection = DriverManager.getConnection(connectionUrl+dbName, userId, password);
statement=connection.createStatement();
String sql ="select `id`,`first_name`,`mobile_no` from `user_info` where `first_name` like '%Chettupalli%'";
List<Employee> empList = new ArrayList<Employee>();
Employee emp;
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
emp = new Employee();
emp.setId(resultSet.getString("id"));
emp.setName(resultSet.getString("first_name"));
emp.setMobileNo(resultSet.getString("mobile_no"));
empList.add(emp);
}
} catch (Exception e) {
e.printStackTrace();
}
%>
<form>
<!-- You can prepare your form based on your requirement-->
</form>
</table>
empList将被呈现在这个JSP的时间准备。 因此,您只需在empList对象上进行中继,以使用动态员工数据准备您的表单。
我认为这将符合您的要求。
你好。 2017年的Java EE开发人员不使用JSP。给你的代码尝试,而不是故事 –
我只是开发一个小应用程序。 我只想找到关于如何进行此操作的想法。 我应该使用Ajax还是其他任何类似的东西来重新获取数据? –
很难理解你(没有细节和代码)。可能“未提交刷新”是最简单的JSP案例(以我的理解)。 SO需要你的尝试 –