由于您似乎不熟悉Java
Web编程,因此可以使用JSP(视图),Servlet(控制器)和实体,DAO和服务层(模型)来实现完整的MVC方案。这是您所拥有的:
模型:
DBConnection
作为数据库访问类(数据访问层)AddRecords
作为您的DAO类(数据访问层)- 没有类作为服务类(业务逻辑层)。对于此示例,让我们为此提供一个
RecordService
类:
public class RecordService { public RecordService() { } //since it has no real business logic, it will serve as facade public String[] getRecords() { AddRecords addRecords = new AddRecords(); return addRecords.populateSelect(); } }控制器:
- 尚无控制器类。由于我假设您使用的是普通Java EE:
@WebServlet("/RecordServlet") public class RecordsServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //it will fire on a GET request (like accessing directly to the URL //from the browser) //here you should load the data for the View (JSP) loadData(request); //forward to show the view request.getRequestDispatcher("hello.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //it will fire on a POST request (like submitting the form using POST method) String selectedRecord = request.getParameter("selectedRecord"); System.out.println(selectedRecord); request.setAttribute("selectedRecord", selectedRecord); loadData(request); //forward to show the view request.getRequestDispatcher("hello.jsp").forward(request, response); } //method to load the data available to select private void loadData(HttpServletRequest request) { RecordService recordService = new RecordService(); String[] records = recordService.getRecords(); //set the data as attribute on the request to be available on the View request.setAttribute("records", records); } }视图:
- 您已经有一个JSP文件。由于您尚未发布姓名,因此称它为
hello.jsp
。我将使用JSTL调整您的实际JSP代码:
<!-- at the beginning of the JSP, call the JSTL library --> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <form action="RecordServlet" method="POST"> Please select an element: <select id="selectedRecord" name="selectedRecord"> <c:forEach items="${records}" var="record"> <option value="${record}">${record}</option> </c:forEach> </select> <br /> <input type="submit" value="Show selected record" /> <c:if test="${not empty selectedRecord}"> <br /> You've selected ${selectedRecord}! </c:if> </form>现在,要运行该示例,请构建项目并使用进行访问
http://localhost:8080/YourWebProjectName/RecordServlet。另外,您可以在
web.xml文件中进行设置:
<welcome-file-list> <welcome-file>RecordServlet</welcome-file> </welcome-file-list>
只需运行Web项目。
一些注意事项:
- 使用相关名称的类/方法,我用了
RecordXXX
,因为你有这个AddRecord
类(它应该是RecordDAO
或读码器更有用的东西像UserDAO
或YourEntityDAO
)。 - 通过不同的包分发您的类。每个包都应只包含与其范围相关的类,即
edu.home.dao
DAO类,edu.home.service
服务/业务逻辑类,等等。



