【问题标题】:Retrieve values from JDBC and use JSTL tags to call the methods从 JDBC 检索值并使用 JSTL 标签调用方法
【发布时间】:2013-02-15 11:14:03
【问题描述】:

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

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 类中实例化 Object 并调用它的方法?有人可以帮帮我吗。提前致谢!

【问题讨论】:

  • 使用JPA 代替与数据库通信。
  • 您已经使用servlet 来执行该代码并将数据保存在会话或请求对象中。然后您可以使用EL 访问数据(并使用JSTL 显示)。我建议您浏览这些链接,它们非常棒。

标签: java jsp model-view-controller jdbc jstl


【解决方案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,因此您将使用 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)。
  • 通过不同的包分发您的类。每个包都应该只包含与其范围相关的类,即 edu.home.dao 用于 DAO 类,edu.home.service 用于服务/业务逻辑类,等等......

【讨论】:

  • 非常感谢这个很棒的答案。我也需要配置我的 web.xml 吗?
  • @frozenhaart 答案已更新,表明您可以在 web.xml 中添加 RecordServlet 作为欢迎文件。
  • 你的代码帮了我很多 Luiggi,我还在coreservlets找到了一些很棒的教程
  • @frozenhaart 我猜网上有很多关于类似问题的教程,他们可以提供更多信息,这只是一个基本的开始。不客气:)。
【解决方案2】:

使用类中的列表作为返回值,

 List<String> sectionName = new ArrayList<String>();

while (resultSet.next())
   sectionName.add(resultSet.getString("section_name"));

然后做

 <select name='name'>
 <c:forEach var="parameter" items="${sectionName }"> 
  <option value="${parameter}">${parameter}</option> 
  </c:forEach> 
</select>

这里的参数是访问列表变量值的中介变量 你也可以使用字符串数组

【讨论】:

  • 我不能返回一个字符串数组并在 JSTL 标签中使用它吗?
  • 你可以使用任何东西,列表或字符串数​​组。没问题
  • 我不明白,什么是 var="ipsection",它没有在任何地方声明?
  • 在我的场景中应该是什么参数?我不需要从类 AddRecords 实例化 Object 以访问其方法 populateSelect() 的返回值吗?
【解决方案3】:

首先,如果你想用 MVC 做一些事情,你应该解耦你的代码。 JSP文件只访问请求,完全没有java代码。

所以你的控制器需要做这样的事情。

 request.setAttribute("ipsections",added.populateSelect());

然后,在你的 jsp 文件中

<select name='anything'>
     <c:forEach items="${ipsections}" var="ipsection">
          <option value="${ipsection}">${ipsection}</option>
    </c:forEach>
</select>

【讨论】:

  • 您的回答不完整。如果您只这样做,则在直接访问 JSP 时,根本不会调用 servlet GET 请求。
  • 我假设一个 MVC 流。你的假设是什么?
  • 由于 OP 没有定义他/她如何实现这个 MVC,你至少应该使用普通的 Servlet 来展示这个例子。然后,推荐如何通过使用 Struts 2、Spring、JSF、GAE 等 MVC 框架来利用这一点。
  • @LuiggiMendoza 所以你想让我编写整个 MVC 流程?也许您也可以这样做并发布您的框架建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 2013-03-07
  • 2011-09-16
  • 1970-01-01
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多