How to trim request parameters automatically in pl

2019-04-06 20:16发布

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?

3条回答
霸刀☆藐视天下
2楼-- · 2019-04-06 20:18

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.

查看更多
The star\"
3楼-- · 2019-04-06 20:25

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.

查看更多
神经病院院长
4楼-- · 2019-04-06 20:33

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

Another possibility is to use the Before-Interception.

查看更多
登录 后发表回答