How to trim request parameters automatically in playframework

半世苍凉 提交于 2019-12-04 03:25:13

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

  • Define acustom binder somewhere that trims the string
  • Annotate every parameter you want to trim with @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);
        }
    }
    

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.

A simple way to do it would be to use object mappings instead, of individual String mappings.

So, you could create a class call Article, and create a setter that trims the content. Normally Play doesn't need you to create the setters, and they are autogenerated behind the scenes, but you can still use them if you have special processing.

public class Article {
    public String title;
    public String content;

    public void setTitle(String title) {
         this.title = title.trim();
    } 
    public void setContent(String content) {
         this.content = content.trim();
    }
}

You then need to pass the Article into your action method, rather than the individual String elements, and your attributes will be trimmed as part of the object mapping process.

niels

You can write a PlayPlugin and trim all parameters of the request.

Another possibility is to use the Before-Interception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!