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

标签 java jsp model-view-controller jdbc jstl

下面是我编写的用于从数据库中检索值的代码(我添加了整个代码以便您更容易理解我在这里要说的内容):

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?如果是这样我该怎么做?我如何从类 AddRecords 实例化对象并调用它的方法?有人可以帮帮我吗。提前致谢!

最佳答案

由于看起来您是 Java Web 编程的新手,您可以使用 JSP( View )、Servlet( Controller )和实体、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();
        }
    }
    

Controller :

  • Controller 还没有类。由于我假设您使用的是纯 Java EE,因此您将使用 Servlet(基于 Servlets StackOverflow wiki 的实现):

    @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 这样的代码阅读器很有用。
  • 通过不同的包分发您的类(class)。每个包应该只包含与其范围相关的类,即 edu.home.dao 用于 DAO 类,edu.home.service 用于服务/业务逻辑类,等等。 .

关于java - 从 JDBC 检索值并使用 JSTL 标记调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15149497/

相关文章:

Java EE vs JSP vs JSF

PHP/Zend Framework 2 - 无法在动态生成的表中显示表字段值

c# - 如何从列表/数组中删除对象属性?

java - 为 Maven Fitnesse 插件编写测试

java - 使用 Spark 高效读取 PDF/文本/word 文件

java - Play Framework : Pass date to view

java - 如何在JavaFX TableView中的表行之间设置空间?

java - 从数据库中检索数据并用单选按钮显示它,单选按钮包含 struts 1.2 中的数据值

java - 从 Eclipse 创建的 WAR 文件在浏览器中不起作用,但在 war 文件展开时起作用

c# - 从证书存储中获取 X509Certificate 列表 C# MVC