小编典典

从JDBC检索值并使用JSTL标记调用方法

jsp

以下是我为从数据库中检索值而编写的代码(我添加了整个代码,因此您可以更轻松地理解我在这里要说的内容):

package ipscheme;

import java.sql.*;

public class AddRecords {

Connection con = new DBConnection().getConnection();
ResultSet  resultSet = null;

public String [] populateSelect() throws SQLException {

    Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

    resultSet = statement.executeQuery("SELECT * FROM ipsections");

    resultSet.last();
    int size = resultSet.getRow();
    resultSet.beforeFirst();

    String [] sectionName = new String[size];

    int j = 0;
    while (resultSet.next()){
        sectionName[j] = resultSet.getString("section_name");
        j = j + 1;
    }

    resultSet.close();
    statement.close();
    con.close();

    return sectionName;

}

}

下面是我用来将数据库中的值填充到选择框的JSP代码。

<select name="sltSection">
 <% 
    AddRecords added = new AddRecords();
    String sectionNm  [] = added.populateSelect();
        for(int i=0; i<sectionNm.length; i++){ %>   
    <option>
        <% out.print(sectionNm[i]); %>
    </option>
 <% } %>
</select>

上面的代码工作正常,没有任何编译错误。如您所见,我在.jsp页面中使用Java代码来完成任务,这是错误的做法。

我需要根据MVC实现此代码,因此我应该使用JSTL标记将代码实现为.jsp?如果是这样,我该怎么做?如何从类实例化Object
AddRecords并调用其方法?有人可以帮帮我吗。提前致谢!


阅读 310

收藏
2020-06-08

共1个答案

小编典典

由于您似乎不熟悉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或读码器更有用的东西像UserDAOYourEntityDAO)。
  • 通过不同的包分发您的类。每个包都应只包含与其范围相关的类,即edu.home.daoDAO类,edu.home.service服务/业务逻辑类,等等。
2020-06-08