如何使 Java ResultSet 在我的 jsp 中可用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/384189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make a Java ResultSet available in my jsp?
提问by
I'd like to swap out an sql:query for some Java code that builds a complex query with several parameters. The current sql is a simple select.
我想为一些构建具有多个参数的复杂查询的 Java 代码替换 sql:query。当前的sql是一个简单的select。
<sql:query var="result" dataSource="${dSource}" sql="select * from TABLE "> </sql:query>
How do I take my Java ResultSet (ie. rs = stmt.executeQuery(sql);) and make the results available in my JSP so I can do this textbook JSP?
我如何获取我的 Java ResultSet(即 rs = stmt.executeQuery(sql);)并使结果在我的 JSP 中可用,以便我可以执行这本教科书 JSP?
To be more clear, I want to remove the above query and replace it with Java.
为了更清楚,我想删除上面的查询并将其替换为 Java。
<% ResultSet rs = stmt.executeQuery(sql); // Messy code will be in some Controller %>
<c:forEach var="row" items="${result.rows}"> <c:out value="${row.name}"/> </c:forEach>
Do I set the session/page variable in the Java section or is there some EL trick that I can use to access the variable?
我是在 Java 部分设置 session/page 变量还是有一些 EL 技巧可以用来访问变量?
采纳答案by BalusC
Model (Row):
型号(行):
public class Row {
private String name;
// Add/generate constructor(s), getters and setters.
}
DAO:
道:
public List<Row> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Row> rows = new ArrayList<Row>();
try {
connection = database.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(SQL_LIST);
while (resultSet.next()) {
Row row = new Row();
row.setName(resultSet.getString("name"));
// ...
rows.add(row);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return rows;
}
Controller (servlet):
控制器(小服务程序):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Row> rows = someDAO.list();
request.setAttribute("rows", rows);
} catch (SQLException e) {
request.setAttribute("error", "Retrieving rows failed.");
e.printStackTrace();
}
request.getRequestDispatcher("page.jsp").forward(request, response);
}
View (page.jsp):
查看(page.jsp):
<c:forEach items="${rows}" var="row">
<c:out value="${row.name}" />
...
</c:forEach>
<c:if test="${not empty error}">Error: ${error}</c:if>
回答by krosenvold
If you're using a web framework like spring mvn or struts, you have a controller class that is executed before the actual jsp. This can have a method
如果您使用的是 web 框架,如 spring mvn 或 struts,那么您有一个在实际 jsp 之前执行的控制器类。这可以有一个方法
ResultSet getResult()
This method will be available as ${result} within your jsp.
此方法将在您的 jsp 中以 ${result} 的形式提供。
If you're not using any of these frameworks you can still use jsp usebean and bind a javaclass to a variable (check usebean documentation). If you usebean to a variable of myBean you access it with ${myBean.result}
如果您不使用这些框架中的任何一个,您仍然可以使用 jsp usebean 并将 javaclass 绑定到变量(查看 usebean 文档)。如果您将bean 用于myBean 的变量,您可以使用${myBean.result} 访问它
Lastly you can also bind the result to the request parameters "somewhere else". In this case you address it as ${param.result}
最后,您还可以将结果绑定到“其他地方”的请求参数。在这种情况下,您将其寻址为 ${param.result}
回答by MetroidFan2002
You don't.
你没有。
First, placing SQL into JSP, even via tags, is indicative of a horrible design choice. The JSP page is the "view" in the Model View Controller pattern. Its job is to display your model, not actually do anything with it other than display it.
首先,将 SQL 放入 JSP 中,即使是通过标签,也是一种糟糕的设计选择。JSP 页面是模型视图控制器模式中的“视图”。它的工作是显示您的模型,除了显示它之外实际上不对其进行任何操作。
In your controller class, execute your SQL and retrieve actual Java objects that can be displayed via the JSP. Then, in your JSP, display them. Leave your SQL to your controller, and let the JSP focus on simply displaying the data. Not only do you gain clean separation of concerns, but your JSP becomes a lot simpler as a result, and it is much easier to refactor Java code than JSP code later on if it needs to be done (it is a lot simpler to test Java code as well).
在您的控制器类中,执行您的 SQL 并检索可通过 JSP 显示的实际 Java 对象。然后,在您的 JSP 中,显示它们。将 SQL 留给控制器,让 JSP 专注于简单地显示数据。您不仅获得了清晰的关注点分离,而且您的 JSP 也因此变得更加简单,并且如果需要重构 Java 代码,那么稍后重构它比 JSP 代码容易得多(测试 Java 会简单得多)代码)。
回答by alex
You set up a session/request attribute from the Java code.
您从 Java 代码设置会话/请求属性。
However, I would suggest notusing a ResultSet, as it has some lifecycle issues (i.e. needs to be closed). I would suggest fetching the ResultSet object in the Java code, iterating over it building, say a List, closing the ResultSet and pass the List to the JSP.
但是,我建议不要使用 ResultSet,因为它有一些生命周期问题(即需要关闭)。我建议在 Java 代码中获取 ResultSet 对象,迭代它构建,比如说一个 List,关闭 ResultSet 并将 List 传递给 JSP。
If you are using Spring, the JdbcTemplates provide methods that take an SQL string and parameters and return a List> with the results of the query, which might come in very handy for this.
如果您使用的是 Spring,JdbcTemplates 提供了接受 SQL 字符串和参数并返回带有查询结果的 List> 的方法,这可能会非常方便。