如何在不使用request.setAttribute的情况下获取ArrayList值从Java类发送到Jsp页面

时间:2019-07-16 07:06:41

标签: jsp httprequest jstl httpsession

试图通过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>

// Servlet

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);

    }

1 个答案:

答案 0 :(得分:0)

据我所知,将参数从servlet传递到jsp的唯一方法是使用 request.setAttribute(...)

我会一直喜欢这种方式

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

        private static String VIEW= "/view.jsp";

        String forward = VIEW;
        request.setAttribute("LIST_TOUR",showTour());
        RequestDispatcher dispatcher = request.getRequestDispatcher(forward);
        dispatcher.forward(request, response);

    }

详细说明为什么不能使用 request.setAttribute(...)吗?

干杯:)