如何在 playframework 中自动修剪请求参数 [英] How to trim request parameters automatically in playframework

查看:52
本文介绍了如何在 playframework 中自动修剪请求参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Play 会将请求参数分配给动作参数,例如:

Play will assign the parameters from request to action parameters, like:

public static void createArticle(String title, String content) {
}

但它不会修剪它们,所以我们通常在动作中使用这样的代码:

But it won't trim them, so we usually to such code in the actions:

public static void createArticle(String title, String content) {
    if(title!=null) title = title.trim();
    if(content!=null) content = content.trim();
}

有没有办法让播放自动修剪它们?

Is there any way to let play trim them automatically?

推荐答案

有多种方法可以使用自定义绑定器实现此目的.一种方法是这样的:

There are multiple ways to achive this with custom binders. One way of doing would be this:

  • 在修剪字符串的某处定义一个自定义的活页夹
  • 使用 @As(binder=TrimmedString.class)

public class Application extends Controller {

    public static class TrimmedString implements TypeBinder<String> {
        @Override
        public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception {
            if(value != null) {
                value = value.trim();
            }
            return value;
        }
    }

    public static void index(
            @As(binder=TrimmedString.class) String s1,
            @As(binder=TrimmedString.class) String s2,
            @As(binder=TrimmedString.class) String s3) {
        render(s1, s2, s3);
    }
}

如果这对你来说太冗长了,只需使用 @Global 绑定器来检查自定义的 @Trim@As('trimmed') 注释.TypeBinder 已经有所有可用的注释,所以这应该很容易实现.

If this is too verbose for you, simply use a @Global binder for String which checks for a custom @Trim or @As('trimmed') annotation. The TypeBinder already has all annotations available so this should be very easy to implement.

所有这些都可以在自定义绑定下的文档中找到.

All this can be found in the documentation under custom binding.

这篇关于如何在 playframework 中自动修剪请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆