从 JDBC 检索值并使用 JSTL 标记调用方法 [英] Retrieve values from JDBC and use JSTL tags to call the methods

查看:34
本文介绍了从 JDBC 检索值并使用 JSTL 标记调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Below is the code which i have written to retrieve values from the database (I have added the whole code so it will be easier for you to understand what i am trying to say here):

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 代码.

And down here is the JSP Code which i have used to populate values from the database into a selectbox.

<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 代码来完成任务,这是错误的做法.

The above code works fine without any compilation errors. As you can see i have used Java code in my .jsp page to fulfill the task, which is a wrong thing to do.

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

I need to implement this code according to the MVC and therefore i should use JSTL tags to implement the code to .jsp? if so how do i do that? How do i instantiate Object from the class AddRecords and call its methods? Can someone please help me. Thanks in advance!

推荐答案

由于看起来您是 Java Web 编程的新手,您可以使用 JSP(视图)、Servlet(控制器)和实体、DAO 来实现完整的 MVC 场景和服务层(模型).这就是你所拥有的:

Since it looks you're new to Java Web Programming, you can implement a full MVC scenario using JSP (View), Servlet (Controller) and Entities, DAOs and Service layer (Model). This is what you have:

型号:

  • DBConnection 作为数据库访问类(数据访问层)
  • AddRecords 作为您的 DAO 类(数据访问层)
  • 没有作为服务类(业务逻辑层)的类.对于这个例子,让我们有一个 RecordService 类:

  • DBConnection as a database access class (Data access layer)
  • AddRecords as your DAO class (Data access layer)
  • No class as Service class (Business logic layer). For this example, let's have a RecordService class for this:

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 代码:

  • You already have a JSP file. Since you haven't posted the name, let's call it hello.jsp. I will just adap your actual JSP code using JSTL:

<!-- 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 文件中设置:

Now, to run the example, build the project and access to it using http://localhost:8080/YourWebProjectName/RecordServlet. Also, you can set in the web.xml file:

<welcome-file-list>
    <welcome-file>RecordServlet</welcome-file>
</welcome-file-list>

然后运行网络项目.

一些注意事项:

  • 为类/方法使用相关名称,我使用 RecordXXX 因为你有这个 AddRecord 类(它应该是 RecordDAO 或更多对 UserDAOYourEntityDAO 等代码阅读器很有用.
  • 通过不同的包分发您的类.每个包都应该只包含与其作用域相关的类,即 DAO 类的 edu.home.dao,服务/业务逻辑类的 edu.home.service,等等..
  • Use relevant names for the class/methods, I used RecordXXX since you had this AddRecord class (it should be RecordDAO or something more useful to code readers like UserDAO or YourEntityDAO).
  • Distribute your classes through different packages. Every package should contain only relevant classes to its scope i.e. edu.home.dao for DAO classes, edu.home.service for service/business logic classes, and on...

这篇关于从 JDBC 检索值并使用 JSTL 标记调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆