我想换一个sql:query来查找一些用几个参数构建复杂查询的Java代码.当前的sql是一个简单的选择.
<sql:query
var="result"
dataSource="${dSource}"
sql="select * from TABLE ">
</sql:query>
如何获取我的Java ResultSet(即rs = stmt.executeQuery(sql);)并在我的JSP中提供结果,以便我可以使用这个教科书JSP?
为了更清楚,我想删除上面的查询并用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>
我是否在Java部分设置了session/page变量,或者是否有一些我可以用来访问变量的EL技巧?
型号(行):
public class Row {
private String name;
// Add/generate constructor(s), getters and setters.
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
控制器(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);
}
Run Code Online (Sandbox Code Playgroud)
查看(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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21007 次 |
| 最近记录: |