簡體   English   中英

在 Spring 中處理可選輸入 RESTful API 的最佳方法

[英]Best way to handle optional inputs RESTful API in Spring

我有一個為使用情況數據庫創建的 RESTful 服務。 必需的參數是開始日期和結束日期。 操作參數是用戶名、客戶端 IP 和遠程 IP。

我有這個工作,但想看看是否有更好的實現方法:

這是我的資源類:

@RequestMapping(value = "/usage", method = RequestMethod.GET)
@ApiOperation(value = "Usage Sessions - JSON Body", notes = "GET method for users by date range")
public List<DTO> getUsageByDate(@RequestParam(value = "start-date", required = true) final String startDate,
        @RequestParam(value = "end-date", required = true) final String endDate,
        @RequestParam(value = "user-name", required = false) final String userName,
        @RequestParam(value = "client-ip", required = false) final String clientIp,
        @RequestParam(value = "remote-ip", required = false) final String nasIp) throws BadParameterException {
    return aaaService.findUsageByDate(startDate, endDate, userName, clientIp,remoteIp);

}

我的 DAO 實現如下所示:

public List<DTO> getUsageByDate(String startDate, String endDate, String userName, String localIp, String remoteIp)
        throws BadParameterException {
    StringBuilder sql = new StringBuilder(
            "select * from usage where process_time >= :start_date and process_time < :end_date");

    if(userName != null) {
        sql.append(" AND user_name = :user_name");
    }
    if(localIp != null) {
        sql.append(" AND local_ip_address = :local_ip");
    }
    if(remoteIp != null){
        sql.append(" AND remote_ip_address = :remote_ip");
    }

    SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("start_date", startDate)
            .addValue("end_date", endDate).addValue("user_name", userName).addValue("local_ip", localIp)
            .addValue("nas_ip", remoteIp);

    try {
        return jdbcTemplate.query(sql.toString(), namedParameters,
                new BeanPropertyRowMapper<DTO>(DTO.class));

    } catch (EmptyResultDataAccessException e) {
        throw new BadParameterException();
    }
}

現在任何想法似乎都有些冗長。

謝謝

  1. 將必需的參數(開始日期、結束日期)作為 URI 的一部分,對於可選參數(用戶名、客戶端 ip、遠程 ip)使用查詢參數。 所以你的 URI 可能是/usage/05.05.2015/06.06.2016?user-name=Joe

  2. 不應在您的 DAO 中進行用戶輸入驗證。 它應該在 REST 控制器中完成。

  3. 如果您使用 Java 8,您可以在getUsageByDate方法簽名中表達哪些參數是可選的,哪些是強制性的:

     public List<DTO> getUsageByDate(String startDate, String endDate, Optional<String> userName, Optional<String> localIp, Optional<String> remoteIp)
  4. 您還應該驗證是否提供了所需的參數:

     Objects.requireNonNull(startDate); Objects.requireNonNull(endDate);
  5. 您應該確保用戶提供的日期是有效的,並且您不應該將日期作為字符串傳遞給您的 DAO。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM