java完成短地址辦事的辦法(附代碼)。本站提示廣大學習愛好者:(java完成短地址辦事的辦法(附代碼))文章只能為提供參考,不一定能成為您想要的結果。以下是java完成短地址辦事的辦法(附代碼)正文
假定上面是你的視頻網站鏈接列表,假如他人想爬取你的數據非常輕松,看規矩就曉得數據庫是序列自增的
http://www.xxxx.com/video/1
http://www.xxxx.com/video/2
http://www.xxxx.com/video/3
那末處理這一成績,我們可使用短地址,纰謬外裸露真實鏈接,應用對稱加密是一個很好的計劃。
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; } }
完成後果:
代碼地位:https://github.com/bladejava/blade-shorturl
以上就是本文的全體內容,願望對年夜家的進修有所贊助。