【发布时间】:2019-11-24 20:47:20
【问题描述】:
试图通过 Servlet 将 ArrayList 从 java 类发送到 Jsp Page。 ResultSet 的返回值被传递给模型对象,并且该对象被添加到 ArrayList。 Java 代码不应该在 jsp 页面中使用 并且 Java 应该只返回 RequestDipature 路径(例如:View.jsp)。
//Java类
@Override
public String execute(Map<String, String> map){
return "#";
}
public List<Tour> showTour(){
List<Tour> list = new ArrayList<>();
String sql = "Select * from Tour";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = con.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
int tourId = resultSet.getInt("tourId");
String tourCode = resultSet.getString("tourCode");
String tourName = resultSet.getString("tourName");
String boardingPlace = resultSet.getString("boardingPlace");
String destinationPlace = resultSet.getString("destinationPlace");
Tour tour = new Tour(tourId, tourCode, tourName, boardingPlace, destinationPlace);
list.add(tour);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
preparedStatement.close();
con.close();
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
//Jsp页面
<c:forEach var="tourList" items="${LIST_TOUR}">
<tr>
<td>${tourList.tourId}</td>
<td>${tourList.tourCode}</td>
<td>${tourList.tourName}</td>
<td>${tourList.boardingPlace}</td>
<td>${tourList.destinationPlace}</td>
</tr>
//小服务程序
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Map Content Here
String responsePath = command.execute(map);
RequestDispatcher dispatcher = request.getRequestDispatcher(responsePath);
dispatcher.forward(request, response);
}
【问题讨论】:
-
为什么不使用
request.setAttribute(...)?这是作业吗? -
不,这是我的项目
-
您可以使用 CDI 执行此操作(反过来,CDI 仍将在幕后使用
request.setAttribute(...)等,但您不再需要手动执行此操作)。您的环境中是否有可用的 CDI?如果不是(确定),那么请告诉您您正在使用哪个环境。例如,Tomcat 默认没有内置 CDI,然后您必须手动安装它。但是普通的 Java EE 服务器已经内置了 CDI,但可能需要先激活它,具体取决于服务器版本。
标签: jsp httprequest jstl httpsession