2016-04-03 125 views
1

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

任何想法现在似乎有点长。

感谢

+0

required = true是默认值。对于那些可选的参数,您不需要添加必需的属性。 – pczeus

+0

感谢您的反馈。关于if语句的实现有没有更好的方法? – Xathras

+1

我通常通过JSR303来做到这一点。你有没有考虑过这个选项? – dambros

回答

1
  1. 进行必要的参数(开始日期,结束日期)的URI的和可选的参数(用户名,客户端IP,远程IP)使用的查询参数部分。所以你的URI可能是/usage/05.05.2015/06.06.2016?user-name=Joe

  2. 用户输入验证不应该在您的DAO中完成。它应该在REST控制器中完成。

  3. 你可以表达其参数是可选的,哪些是在getUsageByDate方法签名强制性的,如果你使用Java 8:

    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。

+0

您的(1)删除稍后确定日期参数是可选的功能。 –

+0

@EricStein这是正确的。这是REST API表现力和自由改变它的能力之间的折衷。 –

相关问题