如何在playframework中自动修剪请求参数
Play会将请求中的参数分配给动作参数,例如:
public static void createArticle(String title, String content) {
}
但它不会修剪它们,所以我们通常在动作中添加这样的代码:
public static void createArticle(String title, String content) {
if(title!=null) title = title.trim();
if(content!=null) content = content.trim();
}
有没有办法让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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有多种方法可以使用自定义活页夹来实现此目的。
一种方法是:
用
@As(binder=TrimmedString.class) 注释要修剪的每个参数
如果这对您来说太冗长,只需使用
@Global
code> String 绑定器,用于检查自定义@Trim
或@As('trimmed')
注释。 TypeBinder 已经拥有所有可用的注释,因此这应该很容易实现。所有这些都可以在自定义绑定下的文档中找到。
There are multiple ways to achive this with custom binders.
One way of doing would be this:
Annotate every parameter you want to trim with
@As(binder=TrimmedString.class)
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.
一种简单的方法是使用对象映射而不是单独的字符串映射。
因此,您可以创建一个名为 Article 的类,并创建一个修剪内容的 setter。通常 Play 不需要您创建 setter,它们是在幕后自动生成的,但如果您进行特殊处理,您仍然可以使用它们。
然后,您需要将 Article (而不是单个 String 元素)传递到操作方法中,并且您的属性将作为对象映射过程的一部分进行修剪。
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.
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.
您可以编写 PlayPlugin 并修剪请求的所有参数。
另一种可能性是使用Before-Interception。
You can write a PlayPlugin and trim all parameters of the request.
Another possibility is to use the Before-Interception.