如何从DAO获取价值并将其转移到JSP

时间:2018-03-20 17:30:20

标签: java jsp servlets

我正在向DB添加数据,但如果记录存在,我想在JSP文件“Record already exists”中返回一个信息。我不知道如何在Java中处理它。我还在学习... 多数民众赞成我的DAO保存方法(顺便说一句,是否有可能在一个PreparedStatement上进行?我有2个查询,因为我必须将Insert和Select分开:

init_instance_callback: function(editor) {
    editor.on('keydown', function(e) {
        editor.lastKeyPressed = e.which;
    });
}

这是我的doGet servlet:

public void save(Event e) {
    PreparedStatement stm = null;
    PreparedStatement stmt = null;
    try {
        String query = "select room_number, description, event_date, eventend_date, screen from events where not exists (select * from events where ((? between event_date and eventend_date) OR (? between event_date and eventend_date) OR (? <= event_date and ? >= eventend_date)) AND room_number = ?)";
        stmt = DatabaseConnector.getConnection().prepareStatement(query);
        Timestamp startDate11 = new Timestamp(e.getEventDate().getTime());
        stmt.setTimestamp(1, startDate11);
        Timestamp endDate11 = new Timestamp(e.getEventEndDate().getTime());
        stmt.setTimestamp(2, endDate11);
        stmt.setTimestamp(3, startDate11);
        stmt.setTimestamp(4, endDate11);
        stmt.setString(5, e.getRoomNumber());
        ResultSet rs = stmt.executeQuery();

        if(rs.next()) {
            String sql = "insert into events (room_number, description, event_date, eventend_date, screen) values (?,?,?,?,?)";
            stm = DatabaseConnector.getConnection().prepareStatement(sql);
            //stm.setInt(1, e.getEventId());
            stm.setString(1, e.getRoomNumber());
            stm.setString(2, e.getDescription());
            Timestamp startDate = new Timestamp(e.getEventDate().getTime());
            stm.setTimestamp(3, startDate);
            Timestamp endDate = new Timestamp(e.getEventEndDate().getTime());
            stm.setTimestamp(4, endDate);
            stm.setString(5, e.getScreen());
            stm.executeUpdate();      
        } else {
            System.out.println("Record alrdy exist"); <- I wanna transfer that information to JSP.              
        }   
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            stm.close(); stmt.close();
        } catch (Exception ex) {
        }
    }
}

这是我的doPost servlet: 事件ev = new Event();

Event ev = new Event();
            request.setAttribute("events", ev);
            request.setAttribute("action", "new");
            request.getRequestDispatcher("JSP/AddNew.jsp").forward(request, response);

我的标准JSP文件只有少量输入,名为AddNew.jsp。 我的“保存”方法运行良好,但我不知道如何告诉用户他没有向DB添加事件,因为事件已经存在:/

1 个答案:

答案 0 :(得分:0)

如果发生故障,您可以从save()返回错误消息,并检查是否获得了一些非空值,在请求中设置属性并转发到jsp。