我在JSP <c:param name="names" value="${tempstudent.name}"/>
中具有用于显示用户名的字段,而我的servlet通过String names=request.getParameter("names")
来获取此字段,并将其作为参数传递给名为public List <studentrgister> showcourse(String names)
的方法中的student_db_util类,该参数具有要执行的任务一个名称,并在我的sql查询中使用它来显示2个表(具有firstName,lastName,id列的mytest表和具有id,class列的class表)的匹配结果。此应用程序的问题是,当我加入两个表时,在两个表中都有多个匹配结果,但我的应用程序仅在我的JSP页面上的匹配结果上显示
<body>
<table>
<form action="studentregister" method="get">
<input type="hidden" name ="comand" value="seecourse"/>
<c:forEach var="tempstudent" items="${mycourse}">
<td >${tempstudent.name}</td>
</c:forEach>
</form>
</table>
命名字段所在的jsp页面
<form action="studentregister" method="get">
<input type="hidden" name="command" value="pass" />
<table>
<c:forEach var="tempstudent" items="${studentlist}">
<c:url var="seecourse" value="studentregister">
<c:param name="command" value="seecourse"/>
<c:param name="names" value="${tempstudent.name}"/>
</c:url>
<td >${tempstudent.email}</td>
<td >${tempstudent.name}</td>
<a href="${seecourse}"
>
seecourse</a>
</c:forEach>
</table>
</form>
servlet方法
private void seecourse(HttpServletRequest request, HttpServletResponse response) throws Exception {
String names=request.getParameter("names");
student_db_util.showcourse(names);
List<studentrgister> student=student_db_util.showcourse(names);
request.setAttribute("mycourse", student);
RequestDispatcher rd=request.getRequestDispatcher("/showcourse.jsp");
rd.forward(request,response);
}
student_db_util类中的方法
public List <studentrgister> showcourse(String names) throws Exception {
List<studentrgister> students = new ArrayList<>();
String connectionURL = "jdbc:mysql://localhost:3306/web_student_tracker";
System.out.println("loding the driver");
Statement s=null;
studentrgister mystudent=null;
Connection myConn = null;
myConn= DriverManager.getConnection(connectionURL, "webstudent", "webstudent");
System.out.println("username and password is correect");
PreparedStatement myStmt=null;
ResultSet myRs = null;
String name=names;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver is loaded");
//myConn = dataSource.getConnection();
String sql = "SELECT mytest.firstName,class.name FROM mytest "
+ "INNER JOIN class ON mytest.id=class.id "
+ "where mytest.firstName = ? " ;
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1,name);
myRs=ps.executeQuery();
if (myRs.next()) {
String classname = myRs.getString("name");
//String numbername=myRs.getString("firstName");
mystudent = new studentrgister(classname);
students.add(mystudent);
}
else {
throw new Exception("Could not find student id: " );
}
return students;
}
finally {
close(myConn,myStmt,null);
}
}
此List声明在方法内部,但该方法返回变量,我认为学生变量应在可访问范围内使用。您应该在类中全局声明List,以便可以在方法外部访问它,或者如果要在外部返回另一个学生变量,则不能返回在方法中声明的局部范围变量。
List<studentrgister> students = new ArrayList<>();