当前位置: 移动技术网 > IT编程>开发语言>Java > java实现短地址服务的方法(附代码)

java实现短地址服务的方法(附代码)

2019年07月22日  | 移动技术网IT编程  | 我要评论

寄生前夜 第三次生日,锵锵三人行 王蒙,淘色影视

假设下面是你的视频网站链接列表,如果别人想爬取你的数据十分轻松,看规则就知道数据库是序列自增的



那么解决这一问题,我们可以使用短地址,不对外暴露真实链接,使用对称加密是一个很好的方案。

hashids是一个很好的选择,它提供了js/php/java/python等编程语言的实现,这里我使用的就是它。

下面是我基于blade框架搭建的java短地址服务。

create table `t_url` (
 `id` int(10) not null auto_increment,
 `url` text not null,
 primary key (`id`)
) engine=innodb auto_increment=15 default charset=utf8;

路由

@path
public class indexroute {
    // 盐值
  private static final hashids hashids = new hashids("blade-shorturl");
   
  private urlmodel urlmodel = new urlmodel();
 
  @route("/:key")
  public void get(request req, response response) {
    string key = req.pathparam(":key").replaceall("[^a-za-z0-9]", "");
    long[] numbers = hashids.decode(key);
 
    if (null == numbers || numbers.length < 1) {
      response.text("没有找到");
      return;
    }
    int id = (int) numbers[0];
    string result = get(id).geturl();
    if (result == null) {
      response.text("没有找到");
      return;
    }
    response.redirect(result);
  }
   
  @route(value = "/", method = httpmethod.get)
  public string index() {
    return "index";
  }
   
  @route(value = "/", method = httpmethod.post)
  public string save(request request, response response) {
    string resjsp = "index";
     
    string longurl = request.query("url");
     
    if (!isurl(longurl)) {
      request.attribute("error", "无效的url");
      return resjsp;
    }
     
    integer id = this.save(longurl);
    if (id == 0) {
      request.attribute("error", "保存失败");
      return resjsp;
    }
     
    string hash = hashids.encode(id);
    request.attribute("url_hash", hash);
     
    system.out.println("id = " + id + ",url_hash=" + hash);
     
    return resjsp;
  }
 
  private integer save(string url) {
    return urlmodel.insert().param("url", url).executeandcommit();
  }
   
  private urlmodel get(int id) {
    return urlmodel.fetchbypk(id);
  }
   
  private final string regex = "\\b(https?|ftp|file)://[-a-za-z0-9+&@#/%?=~_|!:,.;]*[-a-za-z0-9+&@#/%=~_|]";
   
  private boolean isurl(string url) {
    if(stringkit.isnotblank(url)){
      pattern pattern = pattern.compile(regex);
      matcher matcher = pattern.matcher(url);
      if (matcher.find()) {
        return true;
      }
    }
    return false;
  }
}

实现效果:

代码位置:

以上就是本文的全部内容,希望对大家的学习有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网