How to handle optional query parameters in Play framework

后端 未结 6 1590
礼貌的吻别
礼貌的吻别 2020-12-07 22:28

Lets say I have an already functioning Play 2.0 framework based application in Scala that serves a URL such as:

http://localhost:9000/birthdays

which respond

6条回答
  •  悲&欢浪女
    2020-12-07 23:03

    My way of doing this involves using a custom QueryStringBindable. This way I express parameters in routes as:

    GET /birthdays/ controllers.Birthdays.getBirthdays(period: util.Period)
    

    The code for Period looks like this.

    public class Period implements QueryStringBindable {
    
      public static final String PATTERN = "dd.MM.yyyy";
      public Date start;
    
      public Date end;
    
      @Override
      public F.Option bind(String key, Map data) {
          SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
    
          try {
              start = data.containsKey("startDate")?sdf.parse(data.get("startDate")  [0]):null;
              end = data.containsKey("endDate")?sdf.parse(data.get("endDate")[0]):null;
          } catch (ParseException ignored) {
              return F.Option.None();
          }
          return F.Option.Some(this);
      }
    
      @Override
      public String unbind(String key) {
          SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
          return "startDate=" + sdf.format(start) + "&" + "endDate=" + sdf.format(end);
      }
    
      @Override
      public String javascriptUnbind() {
          return null;
      }
    
      public void applyDateFilter(ExpressionList el) {
          if (this.start != null)
              el.ge("eventDate", this.start);
          if (this.end != null)
              el.le("eventDate", new DateTime(this.end.getTime()).plusDays(1).toDate());
      }
    
    }
    

    applyDateFilter is just a convienence method i use in my controllers if I want to apply date filtering to the query. Obviously you could use other date defaults here, or use some other default than null for start and end date in the bind method.

提交回复
热议问题