我有一个为使用情况数据库创建的 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();
}
}
现在任何想法似乎都有点啰嗦。
谢谢
最佳答案
将必需参数(开始日期、结束日期)作为 URI 的一部分,对于可选参数(用户名、客户端 IP、远程 IP),使用查询参数。因此,您的 URI 可能是
/usage/05.05.2015/06.06.2016?user-name=Joe
。用户输入验证不应在您的 DAO 中完成。它应该在 REST Controller 中完成。
如果您使用 Java 8,您可以在
getUsageByDate
方法签名中表示哪些参数是可选的,哪些参数是必需的:public List<DTO> getUsageByDate(String startDate, String endDate, Optional<String> userName, Optional<String> localIp, Optional<String> remoteIp)
您还应该验证是否提供了所需的参数:
Objects.requireNonNull(startDate); Objects.requireNonNull(endDate);
您应该确保用户提供的日期有效,并且您不应该将日期作为字符串传递给 DAO。
关于java - 在 Spring 中处理可选输入 RESTful API 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390098/