我有一个为使用情况数据库创建的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