我的任务要求我们将信息从 java servlet 发送到 jsp 页面。
我的问题是关于调用函数。它有一个sql查询,可以找到多个结果我遇到的问题是它只将结果集中的最后一个返回到jsp页面,而不是所有结果。
这是小服务程序:
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
String sql = "SELECT id, user_id" +
" FROM lab" +
" WHERE user_id=" + (Integer)session.getAttribute("id");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got boobs");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
ArrayList<String> list1 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1));
list1.add(res.getString(2));
}while(res.next());
request.setAttribute("res", res);
}
for(int i=0;i<list1.size();i++){
System.out.println(list1.get(i));
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("Student_manage.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
}
这是jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mars University Lab System</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>
<body>
<jsp:include page="headerStudent.jsp"/>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<div id = "centrecontent">
<br>
<h3>Manage Timetable</h3>
TESTING THE NO FORM REDIRECTION HERE:<br>
<% String data1 = String.valueOf(request.getAttribute("data1")); %>
<% String data2 = String.valueOf(request.getAttribute("data2")); %>
<%=data1 %>
<%=data2 %>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
我相信我需要在 jsp 页面中使用某种 do 语句来逐步检查每个结果。