我从java类返回一个json数组作为返回类型并尝试在jsp页面上显示数据。一切都好(正如调试所说)。但是不知道jsp / html页面的方法(代码/语法)。 上课
JSONArray jsonArray = new JSONArray();
public JSONArray get_user() {
String sql = "SELECT * FROM USER_INFO";
try {
con = new connection.connect().getConnection();
smt = con.createStatement();
rset = smt.executeQuery(sql);
while (rset.next()) {
JSONObject obj = new JSONObject();
obj.put("Email", rset.getString(2));
obj.put("Password", rset.getString(3));
jsonArray.put(obj);
}
} catch (Exception ex) {
ex.getMessage();
}
return jsonArray;
}
JSP
<%
controller.fetch_user obj = new controller.fetch_user();
obj.get_user();
%>
<table>
<tr><td>Email</td><td>Password</td></tr>
*** here i want to display all the records ****
</table>
答案 0 :(得分:1)
最好的解决方案,它返回一个json,你可以返回pojo
创建你喜欢的
class UserInfo{
private String email;
private String Password;
//setter and getter
}
然后重新生成userInfo列表
所以你的方法将是
public List<UserInfo> get_user() {
List<UserInfo> userInfoList = new AraayList<UserInfo>()
String sql = "SELECT * FROM USER_INFO";
try {
con = new connection.connect().getConnection();
smt = con.createStatement();
rset = smt.executeQuery(sql);
while (rset.next()) {
UserInfo obj = new UserInfo();
obj.setEmail(rset.getString(2))
obj.setPassword(rset.getString(3))
userInfoList.add(obj);
}
} catch (Exception ex) {
ex.getMessage();
}
return userInfoList;
}
// for json object
JSONArray jsonArray = new JSONArray();
public JSONArray get_user() {
String sql = "SELECT * FROM USER_INFO";
try {
con = new connection.connect().getConnection();
smt = con.createStatement();
rset = smt.executeQuery(sql);
while (rset.next()) {
JSONObject obj = new JSONObject();
obj.put("Email", rset.getString(2));
obj.put("Password", rset.getString(3));
jsonArray.put(obj);
}
} catch (Exception ex) {
ex.getMessage();
}
return jsonArray;
}
你的jsp代码是
<%
controller.fetch_user obj = new controller.fetch_user();
obj.get_user();
%>
<table>
<tr><td>Email</td><td>Password</td></tr>
for(UserInfo userInfo:obj){
<%
%>
<tr>
<td><%=userInfo.getEmail()%><td>
<td><%=userInfo.getPassword()%><td>
</tr>
<%
}
%>
</table>
如果你的方法仍然返回jsonAraay,代码将是
<%
controller.fetch_user obj = new controller.fetch_user();
JSONArray getArray = obj.get_user();
%>
<table>
<tr><td>Email</td><td>Password</td></tr>
<%
for(int i = 0; i < getArray.size(); i++){
JSONObject userInfo = getArray.getJSONObject(i);
%>
<tr>
<td><%=userInfo.get("Email")%><td>
<td><%=userInfo.get("Password")%><td>
</tr>
<%
}
%>
</table>
并且在jsp代码中,您可以像访问它一样访问它
可能会对你有很大的帮助