如何在 JSTL 而不是 scriplet 中获取查询参数

How to get query parameters in JSTL instead of scriplets

我一直在尝试在 JSP 中显示一个 table,为此我正在使用下面给出的 while 循环代码,问题是我很难将我的 scriptlet 转换成JSTL,尤其是 rs.getInt("id"),我正在使用 JSTL,以便我可以一起编码 URL。

Class.forName("com.mysql.cj.jdbc.Driver");
                        String url = "jdbc:mysql://localhost:3306/login";
                        String username = "root";
                        String password = "your-password";
                        String query = "select * from employeesloginaccount";
                        Connection conn = DriverManager.getConnection(url, username, password);
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery(query);
                        while (rs.next()) {
                %>
                <tr>
                    <td><%=rs.getInt("id")%></td>
                    <td><%=rs.getString("first_name")%></td>
                    <td><%=rs.getString("last_name")%></td>
                    <td>

                        <c:url value ="${pageContext.request.contextPath}/downloadFileServlet" var = "myURL">
                          <c:param name = "id" value = "<%=rs.getInt(id)%>"/>
                        </c:url>
                        <form method="get"
                            action="<c:import url = "${myURL}"/>">
                            <input style="text-align: center" type="submit" value="Save">
                        </form>
                    </td>
                </tr>
                <%
                    }

我认为可能值得考虑 BalusC 对这个问题的回答,"How to avoid Java code in JSP files?"

The use of scriptlets (those <% %> things) in JSP is indeed highly discouraged since the birth of taglibs (like JSTL) and EL (Expression Language, those ${} things) over a decade ago.

The major disadvantages of scriptlets are:

  1. Reusability: you can't reuse scriptlets.
  2. Replaceability: you can't make scriptlets abstract.
  3. OO-ability: you can't make use of inheritance/composition.
  4. Debuggability: if scriptlet throws an exception halfway, all you get is a blank page.
  5. Testability: scriptlets are not unit-testable.
  6. Maintainability: per saldo more time is needed to maintain mingled/cluttered/duplicated code logic.

您的具体问题是可维护性

你应该做的是分离你的应用程序的逻辑,这样你就可以拥有高水平的 reusability/testability/debuggability/maintainability 等等。让我们从创建一个 java class 开始您的数据库连接,可能是这样的:

public class DBConnection {
    private static String url = null;
    private static Connection conn = null;
     public static Connection getConnection(){
     try{

       Class.forName("com.mysql.jdbc.Driver");
       url = "jdbc:mysql://localhost:3306/login";

     conn = DriverManager.getConnection(url,"root","your-password");
     }   catch (Exception e) {
            System.out.println(e);
        } 
     return conn;
     }
}

然后你可以使用这个 class 只要你想连接到你的数据库并从其他 classes 做一些事情,在下面的例子中我们将创建一个对象来处理你的员工数据和然后使用它从您的数据库中获取信息:

public class EmployeeObject {

    int id;
    String firstname;
    String lastname;


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

}

现在我们有了这个对象 class,假设您有另一个 class 称为 Employees,在这个 class 中您有一个从 employeesloginaccount table:

public class Employees {    

    public List<EmployeeObject> getEmployeeInfo(){
        //this class will return a list of EmployeeObjects from the database.
        ArrayList<EmployeeObject> employees = new ArrayList<EmployeeObject>();
        //get connection from our DBConneciton class we created earlier
        try(Connection conn= DBConnection.getConnection()){
       PreparedStatement pst = conn.prepareStatement("select * from employeesloginaccount;"); 
                ResultSet rs = pst.executeQuery();
                while (rs.next()) {
                    //for each result in database, create an EmployeeObject
                    EmployeeObject employee = new EmployeeObject();

                    int id = rs.getInt("id");
                    employee.setId(id);

                    String fname = rs.getString("first_name"); 
                    employee.setFirstname(fname);

                    String lname = rs.getString("last_name"); 
                    employee.setLastname(lname);

                    employees.add(employee); // add each EmployeeObject to the arrayList of EmployeeObject's
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return employees; //return all the results      
    }   

}

然后你创建一个 Servlet 来获取这些信息,让我们简单点,把我们的代码放在 servlet 的 doGet 方法中,这样每当我们访问这个 Servlet 的 URL 时,我们都会调用这段代码(在这种情况下,我调用了我的 Servlet 测试,使用 url 映射 /Test:

@WebServlet("/Test")
public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Test() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Employees e = new Employees(); //instantiate the Employees class 

        List<EmployeeObject> employees = e.getEmployeeInfo(); //get employee info from database

        request.setAttribute("employees", employees); //set this list of employees to the request so we can access it in our jsp

        RequestDispatcher rd = request.getRequestDispatcher("example.jsp"); //change to whatever your jsp is that you want to view the information
        rd.forward(request, response);
    }

}

最后在我们的 jsp 页面中我们可以查看此信息:

<!DOCTYPE HTML>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Example Page</title>
</head>

<body>

<table style="width:100%;">
<thead>
<tr>
<td>id</td>
<td>Firstname</td>
<td>Lastname</td>
</tr>
</thead>

<tbody>
<!-- for each item in our employees list create a variable called "employee" -->
<c:forEach items="${employees}" var="employee">
<tr>
<td>${employee.id}</td>
<td>${employee.firstname}</td>
<td>${employee.lastname}</td>
</tr>
</c:forEach>

</tbody>
</table>

</body>
</html>

如果这对您有帮助或者您有任何疑问,请告诉我。 :)