我有一個爲使用情況數據庫創建的RESTful服務。 必需的參數是開始日期&結束日期。操作參數是用戶名,客戶端ip & remote-ip。在Spring中處理可選輸入RESTful API的最佳方法
我有這個工作,但想看看有沒有實現一個更好的辦法:
這裏是我的資源類:
@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();
}
}
任何想法現在似乎有點長。
感謝
required = true是默認值。對於那些可選的參數,您不需要添加必需的屬性。 – pczeus
感謝您的反饋。關於if語句的實現有沒有更好的方法? – Xathras
我通常通過JSR303來做到這一點。你有沒有考慮過這個選項? – dambros