使用参数发送/接收GET请求

时间:2019-07-09 23:21:48

标签: javascript sql servlets

我遇到一种情况,我想从一个给定特定ID的数据库中选择所有记录。该请求首先从JavaScript发送,然后由Servlet接收,该Servlet访问DAO,而DAO又查询数据库。显然,这些数据将返回到前端。我对传递这些参数有点困惑,以便正确查询数据库。

我当前收到500错误,这是由于我的参数传递不正确造成的。

从JavaScript发出初始请求:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/project1attempt/reimbursement? 
employee_id=' + x._id, true);
xhr.send();

在Servlet上接收参数是我最大的困惑,因此此处的代码不完整(rs是一种报销服务):

protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {

    resp.setContentType("application/json");
    int id = ;
    List<Reimbursement> reimbursements = rs.findAllReimbursements(id);
    String json = new ObjectMapper().writeValueAsString(reimbursements);
    resp.getWriter().write(json);
}

查询:

public List<Reimbursement> findAllReimbursements(int id) {
    List<Reimbursement> reimbursements = new ArrayList<>();

    try
        (Connection c = manager.getConnection()) {

        String sql = "SELECT reimbursement_id, date, description, amount, 
typing_id, employee_id" +
                "FROM reimbursements" +
                "WHERE reimbursement_id = ?";

        PreparedStatement ps = c.prepareStatement(sql);
        ps.setInt(1, id);
        ResultSet rs = ps.executeQuery();

        Reimbursement r = null;
        while (rs.next()) {
            r = new Reimbursement();
            r.setId(rs.getInt("reimbursement_id"));
            r.setDate(rs.getDate("date"));
            r.setDescription(rs.getString("description"));
            r.setAmount(rs.getDouble("amount"));
            r.setTypingId(rs.getInt("typing_id"));
            r.setEmployeeId(rs.getInt("employee_id"));
            reimbursements.add(r);
        }
        return reimbursements;
    } catch (SQLException e) {
        throw new BlabApplicationDataException("Could not connect to 
Reimbursement Repository" + id);
    }
 }

1 个答案:

答案 0 :(得分:2)

您可以使用getParameter的{​​{1}}方法来获取所需的URL参数。

可能是您要查找的行。

HttpServletRequest