简体   繁体   English

播放框架URL验证器?

[英]Play framework URL validator?

URL comes from form in Play Framework 2. I would like to check whether URL really exists. URL来自Play Framework 2中的表单。我想检查URL是否确实存在。

So it seems like it could be done via combining two approached. 因此,似乎可以通过组合两个接近来完成。

Is there a built-in similar functionality using annotation in model? 在模型中是否有使用注释的内置类似功能?

How to create a custom validator in Play Framework 2.0? 如何在Play Framework 2.0中创建自定义验证器?

How to check if a URL exists or returns 404 with Java? 如何检查URL是否存在或使用Java返回404?

EDIT: for bounty you can provide implementation of URL validator (not build-in). 编辑:对于赏金,您可以提供URL验证器(不是内置)的实现。

Basically you need to perform an HTTP HEAD request for the target URL and check if you got an acceptable response code . 基本上,您需要对目标URL执行HTTP HEAD请求,并检查是否有可接受的响应代码 Acceptable response code might be OK (200), temporarily moved (???) and other codes that will lead to the page if not right now at least very soon. 可接受的响应代码可能是OK(200),暂时移动(???)以及其他将导致页面的代码,如果不是现在,至少很快。

Why HEAD ? 为什么HEAD Because GET will download the whole page and HEAD will download only the HTTP header. 因为GET将下载整个页面, HEAD将仅下载HTTP标头。 This will take less time and time is not a friend in this case. 在这种情况下,这将花费更少的时间和时间不是朋友。 The validation should be done very quickly, and making an HTTP request takes time. 验证应该很快完成,并且发出HTTP请求需要时间。 During those couple seconds (or more, depending on server and network load) the user will wonder what's happening and get frustrated. 在这几秒钟(或更长时间内,取决于服务器和网络负载),用户会想知道发生了什么并感到沮丧。 Unless you can show one of those animated progress indicators to let him know validating its input takes some time. 除非您能够显示其中一个动画进度指示器,让他知道验证其输入需要一些时间。

You should do this like those password strength validators where the value is validated in a background AJAX call once the focus leaves the input control and there's an animated indicator on the side where the result will be shown. 您应该像密码强度验证器那样执行此操作,其中一旦焦点离开输入控件并且在显示结果的一侧有一个动画指示符,则在后台AJAX调用中验证该值。 In the meantime the user can fill out other information. 在此期间,用户可以填写其他信息。

The code would something like this: 代码会是这样的:

public class UrlExistenceValidator ... {
    public boolean isValid(Object object) {
        if (!(object instanceof String)) {
            return false;
        }

        final String urlString = (String) object;

        final URL url = new URL(urlString);
        final HttpURLConnection huc =  (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("HEAD");
        huc.connect();

        final int code = huc.getResponseCode();
        return code != 404;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM