简体   繁体   English

JSP表单通过Java MVC从JDBC显示数据

[英]JSP form to display data from JDBC through java MVC

My servelet. 我的Servlet。

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
     String action = request.getParameter( "action" );
     String forward ="";
     if( action.equalsIgnoreCase( "search" ) ) {
         forward = FIND_COURSE;
         String coursename = request.getParameter("coursename");
         dao.findCourse(coursename);
     }
     RequestDispatcher view = request.getRequestDispatcher( forward );
        view.forward(request, response);
}

The DAO has the prepared statements etc. DAO已准备好声明等。

How can I call this in a jsp? 如何在一个jsp中调用它?

This is my attempt 这是我的尝试

<form action="search" method="GET">
<input type="text" name="coursename" />
<c:forEach var="course" items="${courses}">
 <td><a href="${pageContext.request.contextPath}/FindCourse?coursename=${course.coursename}">${course.coursename}</a></td>

Since you never showed us how you defined the courses variable, I'll just assume it's defined as (just for the sake of demonstration) 由于您从未向我们展示过如何定义课程变量,因此我仅假设将其定义为(仅出于演示目的)

public class Course{
public String coursename;//just to match your variable
public int numOfStudents; //students attending a particular course
}
List<Course> coursesList;

Provided that your JDBC code retrieves all the courses and stores them in a List object, you still need to add that list to the current request as either an attribute or a session (read up on JSP scoped objects) 如果您的JDBC代码检索了所有课程并将它们存储在List对象中,您仍然需要将该列表作为属性或会话添加到当前请求中(在JSP范围内的对象上读取)

In your servlet add 在您的servlet中添加

 request.setAttribute("courses", coursesList);//coursesList is defined as   List<Course> and has already been populated by the DAO/JDBC code

Now your table will get populated with all the courses fetched from the database. 现在,您的表将填充从数据库中获取的所有课程。

If you want to search by course name, then simply have your DAO/JDBC code filter by course name. 如果要按课程名称搜索,则只需按课程名称过滤DAO / JDBC代码。 In your servlet just add code to check that a course name isn't empty and then add the necessary filtering logic. 在您的Servlet中,只需添加代码以检查课程名称是否为空,然后添加必要的过滤逻辑即可。

Also, your form suggests that you want to call http://some_url/search (search is not a parameter but rather a part of the URL address) 此外,您的表单还建议您调用http:// some_url / search (搜索不是参数,而是URL地址的一部分)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM