简体   繁体   English

如何在REST API中强制执行日期值输入?

[英]How to enforce a date value input in a REST API?

The user needs to make a POST to /api/date with something like March 13, 2019 or 08/19/2020 . 用户需要使用March 13, 201908/19/2020类的东西对/api/date进行POST As long as it's a date, it should be accepted. 只要是日期,就应该接受。

I have something like this (Using Dropwizard framework) 我有这样的事情(使用Dropwizard框架)

@POST
public void post(String date)
{
  validateDate(date);
  //continue
}

private void validateDate(String date)
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    try
    {
        LocalDateTime.parse(date, formatter);
    }
    catch (DateTimeParseException e)
    {
      //not a date
    }
}

I'm not sure if I'm in the right approach, there must be a better way to validate strings as dates. 我不确定是否使用正确的方法,必须有更好的方法来将字符串验证为日期。

EDIT: It is not really clear if you want to know how to validate dates correctly or how to handle invalid inputs to your REST API. 编辑: 尚不清楚,如果您想知道如何正确验证日期或如何处理对REST API的无效输入。 My answer shows the latter. 我的回答显示了后者。

You should use a return value for your post method. 您应该为post方法使用返回值。 You can return javax.ws.rs.core.Response , with that you can control the HTTP code and response object you want to return. 您可以返回javax.ws.rs.core.Response ,从而可以控制要返回的HTTP代码和响应对象。

On success, you would normally return the created object with a 200 success code. 成功后,通常会返回带有200成功代码的创建对象。 On failure, you would return an error code (like 400 Bad request) with a detailed error message ("Date must be in the format yyyy-MM-dd"). 失败时,您将返回带有详细错误消息的错误代码(例如400 Bad request)(“日期必须采用yyyy-MM-dd格式”)。

To create the response, you can use the ResponseBuilder. 要创建响应,可以使用ResponseBuilder。

Example: 例:

Response.ok( yourObject ).build(); //success
Response.status( Status.BAD_REQUEST ).entity( yourErrorMessageObject ).build(); // failure

So I would change the code to this: 所以我将代码更改为此:

@POST
public Response post(String date)
{
  if(!isDateValid(date)){
     return Response.status( Status.BAD_REQUEST ).entity( buildErrorMessage()).build();
  }

  //continue
  Response.ok().build(); // returns nothing on success (like void)
}

private boolean isDateValid(String date)
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    try
    {
        LocalDateTime.parse(date, formatter);
        return true;
    }
    catch (DateTimeParseException e)
    {
      //not a date
      return false;
    }
}

You can accept multiple formats for a date time using the optional syntax ([<your format>])* . 您可以使用可选语法([<your format>])*接受日期时间的多种格式。 eg 例如

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
    "[yyyy-MM-dd][dd-MM-yyyy][MMMM dd, yyyy]");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM