使用MVC和DAO模式在JSP页面中在HTML中显示JDBC结果集

发布于 2025-01-21 15:43:15 字数 129 浏览 0 评论 0 原文

我正在使用JSP和JDBC实现MVC。我已经将数据库类文件导入了我的JSP文件,我想显示DB表的数据。我不知道如何将 Resultset 从Java类返回到JSP页面并将其嵌入HTML。

我该如何实现?

I'm implementing MVC using JSP and JDBC. I have imported a database class file to my JSP file and I would like to show the data of a DB table. I don't know how I should return the ResultSet from the Java class to the JSP page and embed it in HTML.

How can I achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

兮子 2025-01-28 15:43:15

在设计良好的MVC方法中,JSP文件不应包含任何Java代码行,而Servlet类不应包含任何JDBC代码行。

假设您想在网络商店中显示产品列表,则需要创建以下代码。

为了使其工作,只需通过其URL致电servlet。前提是servlet被注释 @webservlet(“/products”)或用 web.xml < url-pattern>/products</url-模式> ,然后您可以通过 http://example.com/contextname/products 来调用它

,请参见:

In a well designed MVC approach, the JSP file should not contain any line of Java code and the servlet class should not contain any line of JDBC code.

Assuming that you want to show a list of products in a webshop, the following code needs to be created.

  • A Product class representing a real world entity of a product, it should be just a Javabean.

    public class Product {
    
        private Long id; 
        private String name;
        private String description;
        private BigDecimal price;
    
        // Add/generate getters/setters/c'tors/equals/hashcode boilerplate.
    }
    
  • A DAO class which does all the nasty JDBC work and returns a nice List<Product>.

    public class ProductDAO {
    
        private DataSource dataSource;
    
        public ProductDAO(DataSource dataSource) {
            this.dataSource = dataSource;
        }
    
        public List<Product> list() throws SQLException {
            List<Product> products = new ArrayList<Product>();
    
            try (
                Connection connection = dataSource.getConnection();
                PreparedStatement statement = connection.prepareStatement("SELECT id, name, description, price FROM product");
                ResultSet resultSet = statement.executeQuery();
            ) {
                while (resultSet.next()) {
                    Product product = new Product();
                    product.setId(resultSet.getLong("id"));
                    product.setName(resultSet.getString("name"));
                    product.setDescription(resultSet.getString("description"));
                    product.setPrice(resultSet.getBigDecimal("price"));
                    products.add(product);
                }
            }
    
            return products;
        }
    
    }
    
  • A servlet class which obtains the list and puts it in the request scope.

    @WebServlet("/products")
    public class ProductsServlet extends HttpServlet {
    
        @Resource(name="jdbc/YourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml.
        private DataSource dataSource;
        private ProductDAO productDAO;
    
        @Override
        public void init() {
            productDAO = new ProductDAO(dataSource);
        }
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                List<Product> products = productDAO.list();
                request.setAttribute("products", products); // Will be available as ${products} in JSP
                request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
            } catch (SQLException e) {
                throw new ServletException("Cannot obtain products from DB", e);
            }
        }
    
    }
    
  • Finally a JSP file in /WEB-INF/products.jsp which uses JSTL <c:forEach> to iterate over List<Product> which is made available in EL by ${products}, and uses JSTL <c:out> to escape string properties in order to avoid XSS holes when it concerns user-controlled input.

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/format" prefix="fmt" %>
    ...
    <table>
        <c:forEach items="${products}" var="product">
            <tr>
                <td>${product.id}</td>
                <td><c:out value="${product.name}" /></td>
                <td><c:out value="${product.description}" /></td>
                <td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
            </tr>
        </c:forEach>
    </table>
    

To get it to work, just call the servlet by its URL. Provided that the servlet is annotated @WebServlet("/products") or mapped in web.xml with <url-pattern>/products</url-pattern>, then you can call it by http://example.com/contextname/products

See also:

独闯女儿国 2025-01-28 15:43:15

在Web应用程序上下文中,MVC不包括使用JSP的类。它在于使用以下模型:

  1. 浏览器将请求发送到Web服务器,
  2. 将请求配置为通过Servlet或过滤器(控制器:Java代码,而不是JSP代码)
  3. 处理该请求 的请求(称为操作,控制器的特定部分)
  4. 执行业务逻辑(即从示例中的数据库获取数据:模型)
  5. 基于配置/注释,操作 到JSP。 JSP的作用仅是生成HTML代码(即显示您的数据:视图),

因为JSP通常使用JSP标签(例如JSTL)和JSP Expression语言,并且由于JSP标签和EL设计为从Javabeans获取信息,您最好以Javabeans或Javabeans集合的形式获得数据。

因此,控制器(操作类)的作用是获取数据,创建包含数据的Javabean实例,以适合JSP的格式,将它们放在请求属性中,然后将其派往JSP。然后,JSP将通过Javabean实例迭代并显示其包含的内容。

您不应该自己实施MVC框架。使用现有的(条纹,支柱等)

MVC, in a web application context, doesn't consist in using a class from a JSP. It consists in using the following model :

  1. browser sends a request to a web server
  2. the web server is configured so that the request is handled by a servlet or a filter (the controller : Java code, not JSP code)
  3. The servlet/filter usually dispatches the request to a specific class (called an Action, the specific part of the controller), based on configuration/annotations
  4. The action executes the business logic (i.e. fetch the data from the database in your example : the model)
  5. The action forwards the request to a JSP. The role of the JSP is only to generate HTML code (i.e. display your data : the view)

Since the JSP usually uses JSP tags (the JSTL, for example) and the JSP expression language, and since JSP tags and the EL are designed to get information from JavaBeans, you'd better have your data available in the form of JavaBeans or collections of JavaBeans.

The role of the controller (the action class) is thus to fetch the data, to create JavaBean instances containing the data, in a suitable format for the JSP, to put them in request attributes, and then to dispatch to the JSP. The JSP will then iterate through the JavaBean instances and display what they contain.

You should not implement the MVC framework yourself. Use existing ones (Stripes, Struts, etc.)

扭转时空 2025-01-28 15:43:15

我不知道应该如何将结果集从类文件返回到JSP页面

好吧,您不这样做。

mvc 的点是将模型(在这种情况下为 m db信息)与您的视图( v a JSP)分开)以这种方式,您可以在不制动应用的情况下更改视图。

为此,您可能会使用中间对象表示您的数据(通常称为DTO - 在数据传输对象之后 - 不知道它们是如何称呼它的),而其他对象则获取它(通常是DAO)。

因此,基本上您有JSP文件,获取请求参数,然后从DAO中调用一种方法。 DAO在内部有连接到数据库并获取数据并构建DTO集合的方法,该集合将返回到JSP进行渲染。

像这样简化(和不安全)的代码类似的内容:

employee.java

class Employee {
   String name;
   int emplid;
}

opplyeedao.java

class EmployeeDAO { 
   ... method to connect 
   etc. 
   List<Employee> getAllNamed( String name ) { 
       String query = "SELECT name, emplid FROM employee where name like ?";
       ResultSet rs = preparedStatement.executeQuery etc etc.
       List<Employee> results = ....
       while( rs.hasNext() ) { 
          results.add( new Employee( rs.getString("name"), rs.getInt("emplid")));
       }
       // close resources etc 
       return results;
    }
}

employe.jsp

<%
   request.setAttribute("employees", dao.getAllNamed( request.getParameter("name") );
%>
<table>
<c:forEach items="${employees}" var="employee">
<tr><td>${employee.emplid}</td><td>${employee.name}</td></tr>
</c:forEach>
</table>

我希望这给您一个更好的主意。

I don't know how should I return the ResultSet from the class file to the JSP page

Well, you don't.

The point of MVC is to separate your model ( the M DB info in this case ) from your view ( V a jsp, in this case ) in such a way you can change the view without braking to application.

To do this you might use an intermediate object to represent your data ( usually called DTO - after Data Transfer Object -, don't know how they call it these days ), and other object to fetch it ( usually a DAO ).

So basically you have your JSP file, get the request parameters, and then invoke a method from the DAO. The dao, internally has the means to connect to the db and fetch the data and builds a collections of DTO's which are returned to the JSP for rendering.

Something like this extremely simplified ( and insecure ) code:

Employee.java

class Employee {
   String name;
   int emplid;
}

EmployeeDAO.java

class EmployeeDAO { 
   ... method to connect 
   etc. 
   List<Employee> getAllNamed( String name ) { 
       String query = "SELECT name, emplid FROM employee where name like ?";
       ResultSet rs = preparedStatement.executeQuery etc etc.
       List<Employee> results = ....
       while( rs.hasNext() ) { 
          results.add( new Employee( rs.getString("name"), rs.getInt("emplid")));
       }
       // close resources etc 
       return results;
    }
}

employee.jsp

<%
   request.setAttribute("employees", dao.getAllNamed( request.getParameter("name") );
%>
<table>
<c:forEach items="${employees}" var="employee">
<tr><td>${employee.emplid}</td><td>${employee.name}</td></tr>
</c:forEach>
</table>

I hope this give you a better idea.

夏日浅笑〃 2025-01-28 15:43:15

我有问题。我不明确理解代码。我的代码也有类似的问题。

我创建了数据库SQL并填写。然后,我想实现来自数据库和其他JSP页面中富裕数据的MainServlet(下面的代码),我想在H1,H2 ECC等部分中插入该数据...我必须使用$ {} Sintax,但我不喜欢知道这是怎么回事。

简而言之,在JSP文件(下面的代码,我必须使用$ {} sintax)我想“呼叫” Mainservlet,在那里我想从数据库中富裕数据并在JSP文件中查看。

希望我能正确解释,非常感谢!

mainservlet.java

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class MainServlet
 */
@WebServlet({ "/MainServlet" })
public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String PATH_JSP = "/WEB-INF/";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String doveAndare = request.getParameter("azione");
        if(doveAndare==null)
            doveAndare = "index";
        try {
            String driverString = "com.mysql.cj.jdbc.Driver";
            Class.forName(driverString);
            String connString = "jdbc:mysql://localhost:3306/ldd_jewels?user=root&password=";
            Connection conn = DriverManager.getConnection(connString);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM JEWEL");
            while (rs.next() == true) {
                System.out.println(rs.getString("Category") + "\t" + rs.getString("Name"));
                
                /* I try that but does not work
                request.setAttribute("name", rs.getString("Name"));
                javax.servlet.RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/widering_male.jsp");
                dispatcher.forward(request, response); */
            }
            stmt.close();
            conn.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher(PATH_JSP+doveAndare+".jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

dublerow.jsp

   <section id="portfolio-details" class="portfolio-details">
        <div class="container">
          <div class="row gy-4">
            <div class="col-lg-8">
              <div class="portfolio-details-slider swiper">
                <div class="swiper-wrapper align-items-center">
                  <div class="swiper-slide">
                    <img src="assets/img/jewels/doublerow_1.jpg" alt="" />
                  </div>

                  <div class="swiper-slide">
                    <img src="assets/img/jewels/doublerow_2.jpg" alt="" />
                  </div>

                  <div class="swiper-slide">
                    <img src="assets/img/jewels/doublerow_3.jpg" alt="" />
                  </div>
                </div>
                <div class="swiper-pagination"></div>
              </div>
            </div>

            <div class="col-lg-4">
              <div class="portfolio-info">
                <h3>Product details</h3>
                <ul>
                  <li><strong>Code</strong>: 1S3D5</li>
                  <li><strong>Category</strong>: Bracelets</li>
                  <li><strong>Name</strong>: Double Row Hinged Bangle</li>
                  <li><strong>Gender</strong>: Female</li>
                  <li><strong>Material</strong>: Yellow gold</li>
                  <li><strong>Size</strong>: 121mm</li>
                  <li><strong>Price</strong>: €5500</li>
                </ul>
              </div>
              <div class="portfolio-description">
                <h2>Description of product</h2>
                <p>
                  The entwined ends of Tiffany Knot’s signature motif symbolize
                  the power of connections between people. Balancing strength
                  and elegance, each Tiffany Knot design is a complex feat of
                  craftsmanship. This bangle is crafted with yellow gold and
                  polished by hand for high shine. Wear on its own or partnered
                  with classic silhouettes for an unexpected pairing.
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

这是我的数据库:

我想将每个珠宝插入不同页面(每个珠宝都有一个JSP文件)

I have a problem. I don't understand clearly the code. I have a similar problem with my code.

I have created database SQL and filled up. Then I want to implement a MainServlet (code below) that richieve data from database and in a different jsp page, I want to insert that data in section like h1, h2 ecc... I must use the ${} sintax but I don't know how do that.

Briefly, In jsp file (code below, I MUST USE ${} SINTAX) I want to "call" MainServlet and there I want to richieve data from database and view in jsp file.

I hope I have explained correctly, thank you very much!

MainServlet.java

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class MainServlet
 */
@WebServlet({ "/MainServlet" })
public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String PATH_JSP = "/WEB-INF/";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String doveAndare = request.getParameter("azione");
        if(doveAndare==null)
            doveAndare = "index";
        try {
            String driverString = "com.mysql.cj.jdbc.Driver";
            Class.forName(driverString);
            String connString = "jdbc:mysql://localhost:3306/ldd_jewels?user=root&password=";
            Connection conn = DriverManager.getConnection(connString);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM JEWEL");
            while (rs.next() == true) {
                System.out.println(rs.getString("Category") + "\t" + rs.getString("Name"));
                
                /* I try that but does not work
                request.setAttribute("name", rs.getString("Name"));
                javax.servlet.RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/widering_male.jsp");
                dispatcher.forward(request, response); */
            }
            stmt.close();
            conn.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher(PATH_JSP+doveAndare+".jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

doublerow.jsp

   <section id="portfolio-details" class="portfolio-details">
        <div class="container">
          <div class="row gy-4">
            <div class="col-lg-8">
              <div class="portfolio-details-slider swiper">
                <div class="swiper-wrapper align-items-center">
                  <div class="swiper-slide">
                    <img src="assets/img/jewels/doublerow_1.jpg" alt="" />
                  </div>

                  <div class="swiper-slide">
                    <img src="assets/img/jewels/doublerow_2.jpg" alt="" />
                  </div>

                  <div class="swiper-slide">
                    <img src="assets/img/jewels/doublerow_3.jpg" alt="" />
                  </div>
                </div>
                <div class="swiper-pagination"></div>
              </div>
            </div>

            <div class="col-lg-4">
              <div class="portfolio-info">
                <h3>Product details</h3>
                <ul>
                  <li><strong>Code</strong>: 1S3D5</li>
                  <li><strong>Category</strong>: Bracelets</li>
                  <li><strong>Name</strong>: Double Row Hinged Bangle</li>
                  <li><strong>Gender</strong>: Female</li>
                  <li><strong>Material</strong>: Yellow gold</li>
                  <li><strong>Size</strong>: 121mm</li>
                  <li><strong>Price</strong>: €5500</li>
                </ul>
              </div>
              <div class="portfolio-description">
                <h2>Description of product</h2>
                <p>
                  The entwined ends of Tiffany Knot’s signature motif symbolize
                  the power of connections between people. Balancing strength
                  and elegance, each Tiffany Knot design is a complex feat of
                  craftsmanship. This bangle is crafted with yellow gold and
                  polished by hand for high shine. Wear on its own or partnered
                  with classic silhouettes for an unexpected pairing.
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

This is my database:
Database
I want to insert each jewel in different pages (each jewel have a jsp file)

可爱咩 2025-01-28 15:43:15

您可以使用 &lt; c:foreach&gt; tag

您可以在以下链接中找到详细的示例 示例使用

You can use the <c:forEach > tag

you can find a detailed example in the following link example use

我爱人 2025-01-28 15:43:15

我认为,将表数据包含在列表之类的集合中,并从Java类返回列表,然后在JSP中重复使用此集合,这将更好。

I think it will be better for you to contain the data of the table into a collection such as list and return the list from the Java class and reuse this collection in the JSP.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文